diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 84bb89d82a..e765e3136e 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -61,7 +61,7 @@ body: value: | ```python # /// script - # requires-python = ">=3.11" + # requires-python = ">=3.12" # dependencies = [ # "zarr@git+https://github.com/zarr-developers/zarr-python.git@main", # ] diff --git a/.github/ISSUE_TEMPLATE/release-checklist.md b/.github/ISSUE_TEMPLATE/release-checklist.md index ca973c8c38..309c76b4dc 100644 --- a/.github/ISSUE_TEMPLATE/release-checklist.md +++ b/.github/ISSUE_TEMPLATE/release-checklist.md @@ -16,39 +16,17 @@ assignees: '' **Before release**: -- [ ] Make sure the release branch (e.g., `3.1.x`) is up to date with any backports. -- [ ] Make sure that all pull requests which will be included in the release have been properly documented as changelog files in the [`changes/` directory](https://github.com/zarr-developers/zarr-python/tree/main/changes). -- [ ] Run ``towncrier build --version x.y.z`` to create the changelog, and commit the result to the release branch. - [ ] Check [SPEC 0](https://scientific-python.org/specs/spec-0000/#support-window) to see if the minimum supported version of Python or NumPy needs bumping. -- [ ] Check to ensure that: - - [ ] Deprecated workarounds/codes/tests are removed. Run `grep "# TODO" **/*.py` to find all potential TODOs. - - [ ] All tests pass in the ["Tests" workflow](https://github.com/zarr-developers/zarr-python/actions/workflows/test.yml). - - [ ] All tests pass in the ["GPU Tests" workflow](https://github.com/zarr-developers/zarr-python/actions/workflows/gpu_test.yml). - - [ ] All tests pass in the ["Hypothesis" workflow](https://github.com/zarr-developers/zarr-python/actions/workflows/hypothesis.yaml). - - [ ] Check that downstream libraries work well (maintainers can make executive decisions about whether all checks are required for this release). - - [ ] numcodecs - - [ ] Xarray (@jhamman @dcherian @TomNicholas) - - Zarr's upstream compatibility is tested via the [Upstream Dev CI worklow](https://github.com/pydata/xarray/actions/workflows/upstream-dev-ci.yaml). - - Click on the most recent workflow and check that the `upstream-dev` job has run and passed. `upstream-dev` is not run on all all workflow runs. - - Check that the expected version of Zarr-Python was tested using the `Version Info` step of the `upstream-dev` job. - - If testing on a branch other than `main` is needed, open a PR modifying https://github.com/pydata/xarray/blob/90ee30943aedba66a37856b2332a41264e288c20/ci/install-upstream-wheels.sh#L56 and add the `run-upstream` label. - - [ ] Titiler.Xarray (@maxrjones) - - [Modify dependencies](https://github.com/developmentseed/titiler/blob/main/src/titiler/xarray/pyproject.toml) for titiler.xarray. - - Modify triggers for running [the test workflow](https://github.com/developmentseed/titiler/blob/61549f2de07b20cca8fb991cfcdc89b23e18ad05/.github/workflows/ci.yml#L5-L7). - - Push the branch to the repository and check for the actions for any failures. +- [ ] Verify that the latest CI workflows on `main` are passing: [Tests](https://github.com/zarr-developers/zarr-python/actions/workflows/test.yml), [GPU Tests](https://github.com/zarr-developers/zarr-python/actions/workflows/gpu_test.yml), [Hypothesis](https://github.com/zarr-developers/zarr-python/actions/workflows/hypothesis.yaml), [Docs](https://github.com/zarr-developers/zarr-python/actions/workflows/docs.yml), [Lint](https://github.com/zarr-developers/zarr-python/actions/workflows/lint.yml), [Wheels](https://github.com/zarr-developers/zarr-python/actions/workflows/releases.yml). +- [ ] Run the [downstream tests](https://github.com/zarr-developers/zarr-python/actions/workflows/downstream.yml) against `main`: go to the workflow page, click "Run workflow", and select the `main` branch. Verify that the Xarray and numcodecs integration tests pass. +- [ ] Open a release PR with the changelog entries for the upcoming release, generated with `uv run --only-group release towncrier build --version x.y.z`. +- [ ] Review the release PR and verify the changelog in `docs/release-notes.md` looks correct. +- [ ] Merge the release PR. **Release**: -- [ ] Go to https://github.com/zarr-developers/zarr-python/releases. - - [ ] Click "Draft a new release". - - [ ] Choose a version number prefixed with a `v` (e.g. `v0.0.0`). For pre-releases, include the appropriate suffix (e.g. `v0.0.0a1` or `v0.0.0rc2`). - - [ ] Set the target branch to the release branch (e.g., `3.1.x`) - - [ ] Set the description of the release to: `See release notes https://zarr.readthedocs.io/en/stable/release-notes.html#release-0-0-0`, replacing the correct version numbers. For pre-release versions, the URL should omit the pre-release suffix, e.g. "a1" or "rc1". - - [ ] Click on "Generate release notes" to auto-fill the description. - - [ ] Make a release by clicking the 'Publish Release' button, this will automatically create a tag too. -- [ ] Verify that release workflows succeeded. - - [ ] The latest version is correct on [PyPI](https://pypi.org/project/zarr/). - - [ ] The stable version is correct on [ReadTheDocs](https://zarr.readthedocs.io/en/stable/). +- [ ] [Draft a new GitHub Release](https://github.com/zarr-developers/zarr-python/releases/new) with tag `vX.Y.Z` targeting `main`. Use "Generate release notes" for the description. +- [ ] Verify the release is published on [PyPI](https://pypi.org/project/zarr/) and [ReadTheDocs](https://zarr.readthedocs.io/en/stable/). **After release**: @@ -57,3 +35,19 @@ assignees: '' --- - [ ] Party :tada: + +--- + +
+Releasing from a branch other than main + +In rare cases (e.g. patch releases for an older minor version), you may need to release from a dedicated release branch (e.g. `3.1.x`): + +- Create the release branch from the appropriate tag if it doesn't already exist. +- Cherry-pick or backport the necessary commits onto the branch. +- Run `towncrier build --version x.y.z` and open the release PR against the release branch instead of `main`. +- Run the downstream tests against the release branch instead of `main`. +- When drafting the GitHub Release, set the target to the release branch instead of `main`. +- After the release, ensure any relevant changelog updates are also reflected on `main`. + +
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index c36428b300..47adb4b19e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,6 +1,24 @@ -[Description of PR] + + +## Summary + +[Describe what this PR changes and why, in your own words.] + +## For reviewers + +[What would you most value a second look at? What are you already confident in? For a refactor, say whether behavior is meant to be unchanged.] + +## Author attestation + +- [ ] I am a human, these are my changes, and I have reviewed and understood every change and can explain why each is correct. + + + +## TODO -TODO: * [ ] Add unit tests and/or doctests in docstrings * [ ] Add docstrings and API docs for any new/modified user-facing classes and functions * [ ] New/modified features documented in `docs/user-guide/*.md` diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 82419a5143..0c794d9b08 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,12 +10,24 @@ updates: actions: patterns: - "*" - - package-ecosystem: "github-actions" + cooldown: + default-days: 7 + # Keep the pinned dev tooling in pyproject.toml's [dependency-groups] and the + # uv.lock current. Without this the exact pins (e.g. pytest) would never be + # bumped automatically and would silently rot. + # + # `allow: dependency-type: direct` restricts updates to dependencies declared + # in pyproject.toml. Transitive deps in uv.lock are then only updated as a + # side effect of a direct bump, never via a standalone PR. + - package-ecosystem: "uv" directory: "/" - target-branch: "support/v2" + allow: + - dependency-type: "direct" schedule: interval: "weekly" groups: - actions: + python-dependencies: patterns: - "*" + cooldown: + default-days: 7 diff --git a/.github/workflows/check_changelogs.yml b/.github/workflows/check_changelogs.yml index 02b57a5e36..c391f63738 100644 --- a/.github/workflows/check_changelogs.yml +++ b/.github/workflows/check_changelogs.yml @@ -7,16 +7,31 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: check-changelogs: name: Check changelog entries runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install uv - uses: astral-sh/setup-uv@61cb8a9741eeb8a550a1b8544337180c0fc8476b # v7.2.0 + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - - name: Check changelog entries + - name: Check zarr-python changelog entries run: uv run --no-sync python ci/check_changelog_entries.py + + - name: Check zarr-metadata changelog entries + run: uv run --no-sync python ci/check_changelog_entries.py packages/zarr-metadata/changes + + - name: Check zarr-indexing changelog entries + run: uv run --no-sync python ci/check_changelog_entries.py packages/zarr-indexing/changes + + - name: Check zarr-http-server changelog entries + run: uv run --no-sync python ci/check_changelog_entries.py packages/zarr-http-server/changes diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index bc4f1c1d4c..f36fbff233 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -10,6 +10,10 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: benchmarks: name: Run benchmarks @@ -19,19 +23,18 @@ jobs: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'benchmark')) steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - name: Set up Python - uses: actions/setup-python@v6 - with: - python-version: "3.11" + persist-credentials: false - name: Install Hatch uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc with: version: '1.16.5' - name: Run the benchmarks - uses: CodSpeedHQ/action@v4 + uses: CodSpeedHQ/action@0ca9cbbf4623b599a6c3ed4fc8a922942705d9f1 # v5.0.2 + env: + ZARR_BENCHMARK_CLEAR_CACHE: '1' with: mode: walltime - run: hatch run test.py3.11-minimal:pytest tests/benchmarks --codspeed + run: hatch run test.py3.12-minimal:pytest tests/benchmarks --codspeed diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000000..792ee431ab --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,40 @@ +name: Docs + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + docs: + name: Check docs + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - run: uv sync --group docs + # Fast source-level guards that need no built site, so they run before the (slower) + # build for a quick failure: every public export is in the API reference, and no + # docstring/Markdown carries reStructuredText markup that MkDocs won't render. + - run: uv run python ci/check_documented_exports.py docs/api + - run: uv run python ci/lint_docs.py + # --strict turns warnings into errors, so a docs code block that fails to execute + # at build time (e.g. a non-exec python fence disrupting a later exec="true" block) + # fails CI instead of merging as a silent warning. + - run: uv run mkdocs build --strict + env: + DISABLE_MKDOCS_2_WARNING: "true" + NO_MKDOCS_2_WARNING: "true" + - run: uv run python ci/check_unlinked_types.py + continue-on-error: true diff --git a/.github/workflows/downstream.yml b/.github/workflows/downstream.yml new file mode 100644 index 0000000000..98cd0fee3f --- /dev/null +++ b/.github/workflows/downstream.yml @@ -0,0 +1,129 @@ +name: Downstream + +on: + workflow_dispatch: + pull_request: + types: [labeled, synchronize, opened, reopened] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + xarray: + name: Xarray zarr backend tests + if: | + github.event_name == 'workflow_dispatch' + || contains(github.event.pull_request.labels.*.name, 'run-downstream') + runs-on: ubuntu-latest + steps: + - name: Check out zarr-python + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Check out xarray + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: pydata/xarray + path: xarray + persist-credentials: false + + # We install xarray with plain pip/uv rather than pixi. pixi solves + # xarray's entire manifest (it has no committed lockfile), which drags in + # the `mypy-upstream` environment; that environment sources numcodecs from + # git and fails to build under newer pixi with + # `meson-python: error: Unknown option "pixi-conda-environment"`, breaking + # the job before any test runs. Tests that need a backend we don't install + # are skipped via xarray's `requires_*` markers, not failed. + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + + - name: Install xarray and test dependencies + working-directory: xarray + run: | + uv venv + # xarray's pytest tooling lives in the PEP 735 `dev` dependency group; + # the zarr-relevant backends come from the `io` and `parallel` extras. + uv pip install --group dev ".[io,parallel,accel]" + + - name: Override zarr-python with branch version + working-directory: xarray + run: uv pip install --no-deps .. + + - name: Show versions + working-directory: xarray + run: | + uv run python -c " + import zarr; print(f'zarr {zarr.__version__}') + import xarray; print(f'xarray {xarray.__version__}') + " + + - name: Run xarray zarr backend tests + working-directory: xarray + run: | + uv run python -m pytest --no-header -q \ + xarray/tests/test_backends.py \ + xarray/tests/test_backends_api.py \ + xarray/tests/test_backends_datatree.py + + numcodecs: + name: numcodecs zarr3 codec tests + if: | + github.event_name == 'workflow_dispatch' + || contains(github.event.pull_request.labels.*.name, 'run-downstream') + runs-on: ubuntu-latest + steps: + - name: Check out zarr-python + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Check out numcodecs + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: zarr-developers/numcodecs + fetch-depth: 0 + path: numcodecs + submodules: recursive + persist-credentials: false + + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + + - name: Install numcodecs with test-zarr-main group + working-directory: numcodecs + run: | + uv venv + uv pip install --group dev + uv sync --group dev --group test-zarr-main + uv pip install --no-build-isolation -e . + + - name: Override zarr-python with branch version + working-directory: numcodecs + run: uv pip install --no-deps .. + + - name: Show versions + working-directory: numcodecs + run: | + uv run python -c " + import zarr; print(f'zarr {zarr.__version__}') + import numcodecs; print(f'numcodecs {numcodecs.__version__}') + " + + - name: Run numcodecs zarr3 tests + working-directory: numcodecs + run: uv run python -m pytest -x --no-header -q tests/test_zarr3.py diff --git a/.github/workflows/gpu_test.yml b/.github/workflows/gpu_test.yml index c474485dc0..bf8700400e 100644 --- a/.github/workflows/gpu_test.yml +++ b/.github/workflows/gpu_test.yml @@ -12,6 +12,8 @@ on: env: LD_LIBRARY_PATH: /usr/local/cuda/extras/CUPTI/lib64:/usr/local/cuda/lib64 + # Use the uv from astral-sh/setup-uv instead of hatch's bundled (pyapp) uv. + HATCH_ENV_TYPE_VIRTUAL_UV_PATH: uv permissions: contents: read @@ -23,16 +25,19 @@ concurrency: jobs: test: name: py=${{ matrix.python-version }} - + environment: + name: codecov-upload + deployment: false runs-on: gpu-runner strategy: matrix: - python-version: ['3.11'] + python-version: ['3.12'] steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 # grab all branches and tags + persist-credentials: false # - name: cuda-toolkit # uses: Jimver/cuda-toolkit@v0.2.16 # id: cuda-toolkit @@ -52,24 +57,31 @@ jobs: echo $LD_LIBRARY_PATH nvcc -V - name: Set up Python - uses: actions/setup-python@v6 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install Hatch uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc with: version: '1.16.5' - name: Set Up Hatch Env + env: + HATCH_ENV: gputest.py${{ matrix.python-version }} run: | - hatch env create gputest.py${{ matrix.python-version }} - hatch env run -e gputest.py${{ matrix.python-version }} list-env + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env - name: Run Tests + env: + HATCH_ENV: gputest.py${{ matrix.python-version }} run: | - hatch env run --env gputest.py${{ matrix.python-version }} run-coverage + hatch env run --env "$HATCH_ENV" run-coverage - name: Upload coverage - uses: codecov/codecov-action@13ce06bfc6bbe3ecf90edbbf1bc32fe5978ca1d3 # v5.3.1 + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: token: ${{ secrets.CODECOV_TOKEN }} + flags: gpu verbose: true # optional (default = false) diff --git a/.github/workflows/hypothesis.yaml b/.github/workflows/hypothesis.yaml index 1ec6b4806d..f463397c85 100644 --- a/.github/workflows/hypothesis.yaml +++ b/.github/workflows/hypothesis.yaml @@ -12,13 +12,25 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + env: FORCE_COLOR: 3 + # Use the uv from astral-sh/setup-uv instead of hatch's bundled (pyapp) uv. + HATCH_ENV_TYPE_VIRTUAL_UV_PATH: uv jobs: hypothesis: name: Slow Hypothesis Tests + permissions: + contents: read + issues: write + environment: + name: codecov-upload + deployment: false runs-on: "ubuntu-latest" defaults: run: @@ -30,31 +42,39 @@ jobs: dependency-set: ["optional"] steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Set HYPOTHESIS_PROFILE based on trigger + env: + EVENT_NAME: ${{ github.event_name }} run: | - if [[ "${{ github.event_name }}" == "schedule" || "${{ github.event_name }}" == "workflow_dispatch" ]]; then + if [[ "$EVENT_NAME" == "schedule" || "$EVENT_NAME" == "workflow_dispatch" ]]; then echo "HYPOTHESIS_PROFILE=nightly" >> $GITHUB_ENV else echo "HYPOTHESIS_PROFILE=ci" >> $GITHUB_ENV fi - name: Set up Python - uses: actions/setup-python@v6 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install Hatch uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc with: version: '1.16.5' - name: Set Up Hatch Env + env: + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} run: | - hatch env create test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} - hatch env run -e test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} list-env + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env # https://github.com/actions/cache/blob/main/tips-and-workarounds.md#update-a-cache - name: Restore cached hypothesis directory id: restore-hypothesis-cache - uses: actions/cache/restore@v5 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: .hypothesis/ key: cache-hypothesis-${{ runner.os }}-${{ github.run_id }} @@ -64,23 +84,27 @@ jobs: - name: Run slow Hypothesis tests if: success() id: status + env: + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} + PYTEST_ADDOPTS: "--report-log=output-${{ matrix.python-version }}-log.jsonl" run: | echo "Using Hypothesis profile: $HYPOTHESIS_PROFILE" - hatch env run --env test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} run-hypothesis + hatch env run --env "$HATCH_ENV" run-hypothesis # explicitly save the cache so it gets updated, also do this even if it fails. - name: Save cached hypothesis directory id: save-hypothesis-cache if: always() && steps.status.outcome != 'skipped' - uses: actions/cache/save@v5 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: .hypothesis/ key: cache-hypothesis-${{ runner.os }}-${{ github.run_id }} - name: Upload coverage - uses: codecov/codecov-action@v5 + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: token: ${{ secrets.CODECOV_TOKEN }} + flags: tests verbose: true # optional (default = false) - name: Generate and publish the report @@ -89,8 +113,8 @@ jobs: && steps.status.outcome == 'failure' && github.event_name == 'schedule' && github.repository_owner == 'zarr-developers' - uses: scientific-python/issue-from-pytest-log-action@v1 + uses: scientific-python/issue-from-pytest-log-action@35b4e0a9e06f8e7e261778289cf4b968b722662d # v1.6.2 with: log-path: output-${{ matrix.python-version }}-log.jsonl issue-title: "Nightly Hypothesis tests failed" - issue-label: "topic-hypothesis" + issue-label: "automated issue" diff --git a/.github/workflows/issue-metrics.yml b/.github/workflows/issue-metrics.yml index 5f3a098611..adbd2748a0 100644 --- a/.github/workflows/issue-metrics.yml +++ b/.github/workflows/issue-metrics.yml @@ -7,13 +7,17 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: build: name: issue metrics runs-on: ubuntu-latest permissions: - issues: write - pull-requests: read + issues: write # Required to create the metrics report issue + pull-requests: read # Required to read PR metrics steps: - name: Get dates for last month shell: bash @@ -29,13 +33,13 @@ jobs: echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV" - name: Run issue-metrics tool - uses: github/issue-metrics@v3 + uses: github-community-projects/issue-metrics@df8c49d20958f9345281fa2124858bd0ad227e1f # v5.0.0 env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} SEARCH_QUERY: 'repo:zarr-developers/zarr-python is:issue created:${{ env.last_month }} -reason:"not planned"' - name: Create issue - uses: peter-evans/create-issue-from-file@v6 + uses: peter-evans/create-issue-from-file@fca9117c27cdc29c6c4db3b86c48e4115a786710 # v6.0.0 with: title: Monthly issue metrics report token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/links.yml b/.github/workflows/links.yml new file mode 100644 index 0000000000..d52639a708 --- /dev/null +++ b/.github/workflows/links.yml @@ -0,0 +1,32 @@ +name: Check links + +on: + repository_dispatch: + workflow_dispatch: + # pull_request: + schedule: + - cron: "00 18 * * 1" # weekly, Mondays at 18:00 UTC + +jobs: + linkChecker: + runs-on: ubuntu-latest + permissions: + issues: write # required for peter-evans/create-issue-from-file + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Link Checker + id: lychee + uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 + with: + fail: false + + - name: Create Issue From File + if: steps.lychee.outputs.exit_code != 0 + uses: peter-evans/create-issue-from-file@fca9117c27cdc29c6c4db3b86c48e4115a786710 # v6.0.0 + with: + title: Link Checker Report + content-filepath: ./lychee/out.md + labels: report, automated issue diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0050b2f06a..83cc0a1b3e 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -19,5 +19,15 @@ jobs: name: Lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: j178/prek-action@v1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - uses: j178/prek-action@4e14d07f9231acabce116ccfca13b13dd9755ece # v3.0.0 diff --git a/.github/workflows/needs_release_notes.yml b/.github/workflows/needs_release_notes.yml index b7b467d790..e001e8cd43 100644 --- a/.github/workflows/needs_release_notes.yml +++ b/.github/workflows/needs_release_notes.yml @@ -1,18 +1,27 @@ name: "Pull Request Labeler" on: - - pull_request_target: - types: [opened, reopened, synchronize] + # pull_request_target is needed to label PRs from forks. + # This workflow only runs actions/labeler (no code checkout), so it's safe. + pull_request_target: # zizmor: ignore[dangerous-triggers] + types: [opened, reopened, synchronize] + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true jobs: labeler: - if: ${{ github.event.pull_request.user.login != 'dependabot[bot]' }} && ${{ github.event.pull_request.user.login != 'pre-commit-ci[bot]' }} + name: Label pull request + if: ${{ github.event.pull_request.user.login != 'dependabot[bot]' && github.event.pull_request.user.login != 'pre-commit-ci[bot]' }} permissions: - contents: read - pull-requests: write + contents: read # Required to read label configuration + pull-requests: write # Required to add labels to PRs runs-on: ubuntu-latest steps: - - uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1 + - uses: actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13 # v7.0.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} sync-labels: true diff --git a/.github/workflows/nightly_wheels.yml b/.github/workflows/nightly_wheels.yml index 834d563722..5b99c523a1 100644 --- a/.github/workflows/nightly_wheels.yml +++ b/.github/workflows/nightly_wheels.yml @@ -9,21 +9,29 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: build_and_upload_nightly: name: Build and upload nightly wheels + environment: + name: nightly-wheel-upload + deployment: false runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: submodules: true fetch-depth: 0 + persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 name: Install Python with: - python-version: '3.13' + python-version: '3.14' - name: Install Hatch uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc @@ -34,7 +42,7 @@ jobs: run: hatch build - name: Upload nightly wheels - uses: scientific-python/upload-nightly-action@5748273c71e2d8d3a61f3a11a16421c8954f9ecf + uses: scientific-python/upload-nightly-action@e76cfec8a4611fd02808a801b0ff5a7d7c1b2d99 with: artifacts_path: dist anaconda_nightly_upload_token: ${{ secrets.ANACONDA_ORG_UPLOAD_TOKEN }} diff --git a/.github/workflows/releases.yml b/.github/workflows/releases.yml index bb9256568c..a08d5a6d3f 100644 --- a/.github/workflows/releases.yml +++ b/.github/workflows/releases.yml @@ -1,6 +1,9 @@ name: Wheels on: + release: + types: + - published push: branches: [main] pull_request: @@ -23,15 +26,16 @@ jobs: fail-fast: false steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: submodules: true fetch-depth: 0 + persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 name: Install Python with: - python-version: '3.11' + python-version: '3.12' - name: Install Hatch uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc @@ -39,16 +43,17 @@ jobs: version: '1.16.5' - name: Build wheel and sdist run: hatch build - - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: releases path: dist test_dist_pypi: + name: Test distribution artifacts needs: [build_artifacts] runs-on: ubuntu-latest steps: - - uses: actions/download-artifact@v7 + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: releases path: dist @@ -59,24 +64,25 @@ jobs: ls dist upload_pypi: + name: Upload to PyPI needs: [build_artifacts, test_dist_pypi] runs-on: ubuntu-latest - if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags/v') + if: github.event_name == 'release' environment: name: releases url: https://pypi.org/p/zarr permissions: - id-token: write - attestations: write - artifact-metadata: write + id-token: write # Required for OIDC trusted publishing to PyPI + attestations: write # Required for artifact attestation + artifact-metadata: write # Required for artifact attestation metadata steps: - - uses: actions/download-artifact@v7 + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: releases path: dist - name: Generate artifact attestation - uses: actions/attest@v4 + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-path: dist/* - name: Publish package to PyPI - uses: pypa/gh-action-pypi-publish@v1.13.0 + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5af29c960e..50bb85ff5c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,6 +13,11 @@ on: permissions: contents: read +env: + # Use the uv from astral-sh/setup-uv; without an explicit path hatch + # bootstraps its own (pyapp) uv, which fails on non-3.12 runners. + HATCH_ENV_TYPE_VIRTUAL_UV_PATH: uv + concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true @@ -20,114 +25,134 @@ concurrency: jobs: test: name: os=${{ matrix.os }}, py=${{ matrix.python-version }}, deps=${{ matrix.dependency-set }} + environment: + name: codecov-upload + deployment: false + defaults: + run: + shell: bash strategy: matrix: - python-version: ['3.11', '3.12', '3.13'] + python-version: ['3.12', '3.13', '3.14'] dependency-set: ["minimal", "optional"] os: ["ubuntu-latest"] include: - - python-version: '3.11' + - python-version: '3.12' dependency-set: 'optional' os: 'macos-latest' - - python-version: '3.13' + - python-version: '3.14' dependency-set: 'optional' os: 'macos-latest' - - python-version: '3.11' + - python-version: '3.12' dependency-set: 'optional' os: 'windows-latest' - - python-version: '3.13' + - python-version: '3.14' dependency-set: 'optional' os: 'windows-latest' runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 # grab all branches and tags + persist-credentials: false - name: Set up Python - uses: actions/setup-python@v6 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install Hatch - uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc - with: - version: '1.16.5' + run: python -m pip install hatch==1.16.5 - name: Set Up Hatch Env + env: + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} run: | - hatch env create test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} - hatch env run -e test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} list-env + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env - name: Run Tests env: HYPOTHESIS_PROFILE: ci + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} run: | - hatch env run --env test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} run-coverage + hatch env run --env "$HATCH_ENV" run-coverage - name: Upload coverage if: ${{ matrix.dependency-set == 'optional' && matrix.os == 'ubuntu-latest' }} - uses: codecov/codecov-action@v5 + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: token: ${{ secrets.CODECOV_TOKEN }} + flags: tests verbose: true # optional (default = false) test-upstream-and-min-deps: name: py=${{ matrix.python-version }}-${{ matrix.dependency-set }} - + environment: + name: codecov-upload + deployment: false runs-on: ubuntu-latest strategy: matrix: - python-version: ['3.11', "3.13"] + python-version: ['3.12', "3.14"] dependency-set: ["upstream", "min_deps"] exclude: - - python-version: "3.13" + - python-version: "3.14" dependency-set: min_deps - - python-version: "3.11" + - python-version: "3.12" dependency-set: upstream steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + persist-credentials: false - name: Set up Python - uses: actions/setup-python@v6 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install Hatch - uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc - with: - version: '1.16.5' + run: python -m pip install hatch==1.16.5 - name: Set Up Hatch Env + env: + HATCH_ENV: ${{ matrix.dependency-set }} run: | - hatch env create ${{ matrix.dependency-set }} - hatch env run -e ${{ matrix.dependency-set }} list-env + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env - name: Run Tests + env: + HATCH_ENV: ${{ matrix.dependency-set }} run: | - hatch env run --env ${{ matrix.dependency-set }} run-coverage + hatch env run --env "$HATCH_ENV" run-coverage - name: Upload coverage - uses: codecov/codecov-action@v5 + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: token: ${{ secrets.CODECOV_TOKEN }} + flags: tests verbose: true # optional (default = false) doctests: name: doctests runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 # required for hatch version discovery, which is needed for numcodecs.zarr3 + persist-credentials: false - name: Set up Python - uses: actions/setup-python@v6 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: '3.13' cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install Hatch - uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc - with: - version: '1.16.5' + run: python -m pip install hatch==1.16.5 - name: Set Up Hatch Env run: | hatch run doctest:pip list @@ -135,6 +160,29 @@ jobs: run: | hatch run doctest:test + benchmarks: + name: Benchmark smoke test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install Hatch + run: python -m pip install hatch==1.16.5 + - name: Run Benchmarks + env: + ZARR_BENCHMARK_CLEAR_CACHE: '1' + run: | + hatch env run --env "test.py3.13-minimal" run-benchmark + test-complete: name: Test complete @@ -142,7 +190,8 @@ jobs: [ test, test-upstream-and-min-deps, - doctests + doctests, + benchmarks ] if: always() runs-on: ubuntu-latest diff --git a/.github/workflows/zarr-http-server-release.yml b/.github/workflows/zarr-http-server-release.yml new file mode 100644 index 0000000000..b78fa29ab7 --- /dev/null +++ b/.github/workflows/zarr-http-server-release.yml @@ -0,0 +1,117 @@ +name: zarr-http-server release + +on: + workflow_dispatch: + push: + tags: + - 'zarr_http_server-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-http-server + 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@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + + - name: Build + run: hatch build + + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: zarr-http-server-dist + path: packages/zarr-http-server/dist + + test_artifacts: + name: Test built artifacts + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-http-server-dist + path: dist + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.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_http_server; print('zarr_http_server', zarr_http_server.__version__)" + + upload_pypi: + name: Upload to PyPI + needs: [build, test_artifacts] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zarr_http_server-v') + runs-on: ubuntu-latest + environment: + name: zarr-http-server-releases + url: https://pypi.org/p/zarr-http-server + permissions: + id-token: write # required for OIDC trusted publishing + attestations: write # required for artifact attestations + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-http-server-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@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + + upload_testpypi: + name: Upload to TestPyPI + needs: [build, test_artifacts] + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: + name: zarr-http-server-releases-test + url: https://test.pypi.org/p/zarr-http-server + permissions: + id-token: write + attestations: write + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-http-server-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@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + with: + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/zarr-http-server.yml b/.github/workflows/zarr-http-server.yml new file mode 100644 index 0000000000..16589f0d7d --- /dev/null +++ b/.github/workflows/zarr-http-server.yml @@ -0,0 +1,139 @@ +name: zarr-http-server + +# Job steps delegate to packages/zarr-http-server/justfile, the single source +# of truth for this package's verbs; CI owns only the python matrix and +# caching. Keeping the commands in one place is what makes `just check` +# locally mean the same thing as a green run here. + +on: + push: + branches: [main] + paths: + - 'packages/zarr-http-server/**' + - '.github/workflows/zarr-http-server.yml' + # The package resolves zarr from the repo root for its own tests, so a + # core change can break it. Run this suite when core changes too. + - 'src/zarr/**' + pull_request: + paths: + - 'packages/zarr-http-server/**' + - '.github/workflows/zarr-http-server.yml' + # The package resolves zarr from the repo root for its own tests, so a + # core change can break it. Run this suite when core changes too. + - 'src/zarr/**' + 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-http-server + strategy: + fail-fast: false + matrix: + python-version: ['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@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Sync test dependency groups + # The examples group carries the deps the README examples need, so the + # test that reads a served array back with a zarr client runs here + # instead of silently skipping. + run: uv sync --group test --group examples --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-http-server + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run ruff + run: just lint + + mypy: + name: mypy + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-http-server + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Set up Python + run: uv python install 3.12 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Sync test dependency group + run: uv sync --group test --python 3.12 + - name: Run mypy + run: just typecheck + + docs: + name: docs + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-http-server + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Build docs + run: just docs-check + + zarr-http-server-complete: + name: zarr-http-server complete + needs: [test, ruff, mypy, 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/.github/workflows/zarr-indexing-release.yml b/.github/workflows/zarr-indexing-release.yml new file mode 100644 index 0000000000..2c35abad9f --- /dev/null +++ b/.github/workflows/zarr-indexing-release.yml @@ -0,0 +1,117 @@ +name: zarr-indexing release + +on: + workflow_dispatch: + push: + tags: + - 'zarr_indexing-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-indexing + 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@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + + - name: Build + run: hatch build + + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: zarr-indexing-dist + path: packages/zarr-indexing/dist + + test_artifacts: + name: Test built artifacts + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-indexing-dist + path: dist + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.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_indexing; print('zarr_indexing', zarr_indexing.__version__)" + + upload_pypi: + name: Upload to PyPI + needs: [build, test_artifacts] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zarr_indexing-v') + runs-on: ubuntu-latest + environment: + name: zarr-indexing-releases + url: https://pypi.org/p/zarr-indexing + permissions: + id-token: write # required for OIDC trusted publishing + attestations: write # required for artifact attestations + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-indexing-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@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + + upload_testpypi: + name: Upload to TestPyPI + needs: [build, test_artifacts] + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: + name: zarr-indexing-releases-test + url: https://test.pypi.org/p/zarr-indexing + permissions: + id-token: write + attestations: write + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-indexing-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@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + with: + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/zarr-indexing.yml b/.github/workflows/zarr-indexing.yml new file mode 100644 index 0000000000..61776df913 --- /dev/null +++ b/.github/workflows/zarr-indexing.yml @@ -0,0 +1,136 @@ +name: zarr-indexing + +on: + push: + branches: [main] + paths: + - 'packages/zarr-indexing/**' + - '.github/workflows/zarr-indexing.yml' + pull_request: + paths: + - 'packages/zarr-indexing/**' + - '.github/workflows/zarr-indexing.yml' + 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-indexing + strategy: + fail-fast: false + matrix: + python-version: ['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@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + # The transform tests exercise chunk resolution against zarr's ChunkGrid, + # so they run against the repo-root environment (which provides `zarr`) + # with this package as an editable overlay rather than in package + # isolation. The recipes carry that invocation; this step only fixes the + # interpreter the matrix asked for. + - name: Sync test dependency group + run: uv sync --project ../.. --group test --python ${{ matrix.python-version }} + - name: Run pytest + # Suites and invocation live in packages/zarr-indexing/justfile. + run: just test + - name: Run pytest (tensorstore parity) + run: just test-tensorstore + + ruff: + name: ruff + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run ruff + # The ruff version pin lives in packages/zarr-indexing/justfile. + run: just lint + + pyright: + name: pyright + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Set up Python + run: uv python install 3.12 + - name: Sync test dependency group + run: uv sync --group test --python 3.12 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run pyright + # The pyright invocation lives in packages/zarr-indexing/justfile. + run: just typecheck + + docs: + name: docs + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Build docs + # The strict mkdocs build lives in packages/zarr-indexing/justfile. + run: just docs-check + + zarr-indexing-complete: + name: zarr-indexing 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/.github/workflows/zarr-metadata-release.yml b/.github/workflows/zarr-metadata-release.yml new file mode 100644 index 0000000000..17c285ded6 --- /dev/null +++ b/.github/workflows/zarr-metadata-release.yml @@ -0,0 +1,117 @@ +name: zarr-metadata release + +on: + workflow_dispatch: + push: + tags: + - 'zarr_metadata-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-metadata + 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@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + + - name: Build + run: hatch build + + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: zarr-metadata-dist + path: packages/zarr-metadata/dist + + test_artifacts: + name: Test built artifacts + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-metadata-dist + path: dist + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.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_metadata; print('zarr_metadata', zarr_metadata.__version__)" + + upload_pypi: + name: Upload to PyPI + needs: [build, test_artifacts] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zarr_metadata-v') + runs-on: ubuntu-latest + environment: + name: zarr-metadata-releases + url: https://pypi.org/p/zarr-metadata + permissions: + id-token: write # required for OIDC trusted publishing + attestations: write # required for artifact attestations + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-metadata-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@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + + upload_testpypi: + name: Upload to TestPyPI + needs: [build, test_artifacts] + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: + name: zarr-metadata-releases-test + url: https://test.pypi.org/p/zarr-metadata + permissions: + id-token: write + attestations: write + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-metadata-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@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + with: + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/zarr-metadata.yml b/.github/workflows/zarr-metadata.yml new file mode 100644 index 0000000000..5b3b83b0e0 --- /dev/null +++ b/.github/workflows/zarr-metadata.yml @@ -0,0 +1,125 @@ +name: zarr-metadata + +# Job steps delegate to packages/zarr-metadata/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-metadata/**' + - '.github/workflows/zarr-metadata.yml' + pull_request: + paths: + - 'packages/zarr-metadata/**' + - '.github/workflows/zarr-metadata.yml' + 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-metadata + 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@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - 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-metadata + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run ruff + run: just lint + + pyright: + name: pyright + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-metadata + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run pyright + # The pyright version and interpreter pins live in the justfile. + run: just typecheck + + docs: + name: docs + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-metadata + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Build docs + run: just docs-check + + zarr-metadata-complete: + name: zarr-metadata 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/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 0000000000..c90ba718f6 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,35 @@ +name: GitHub Actions Security Analysis + +on: + push: + branches: [main] + paths: + - '.github/workflows/**' + - '.github/actions/**' + pull_request: + branches: ["**"] + paths: + - '.github/workflows/**' + - '.github/actions/**' + workflow_dispatch: + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + zizmor: + name: Run zizmor + runs-on: ubuntu-latest + permissions: + security-events: write # Required by zizmor-action to upload SARIF files + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run zizmor + uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 diff --git a/.gitignore b/.gitignore index b79ce264c8..59b6632a3c 100644 --- a/.gitignore +++ b/.gitignore @@ -91,3 +91,10 @@ tests/.hypothesis zarr/version.py zarr.egg-info/ + +# Local agent / planning notes (not versioned) +.claude/ +CLAUDE.md +docs/superpowers/ +# zarr-metadata package lockfile (a library, not an app) +packages/zarr-metadata/uv.lock diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000000..3dfdf96856 --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,54 @@ +// markdownlint-cli2 configuration for zarr-python docs. +// +// We keep the rules that catch real rendering/structure problems and disable those that +// are pure style, conflict with house conventions, or fire false positives against our +// MkDocs/mkdocstrings + pymdownx toolchain. Complementary, not overlapping, with +// ci/lint_docs.py (RST residue + list-breaking fences) and `mkdocs build --strict`. +{ + "config": { + "default": true, + + // House style: Markdown paragraphs are single unwrapped lines, so line length is not + // a meaningful constraint. + "MD013": false, + + // Purely stylistic marker/emphasis choices -- not worth the churn across existing docs. + "MD004": false, // ul bullet style (-, *, +) + "MD007": false, // ul indentation width + "MD050": false, // strong (bold) style + "MD035": false, // hr style + + // False positives from our toolchain: + // mkdocstrings cross-refs `[`X`][zarr.X]` read as undefined reference links (MD052); + // pymdownx.magiclink auto-links bare URLs (MD034); + // md_in_html lets us embed intentional raw HTML (MD033); + // generated/included files (api stubs, snippets) need not open with an H1 (MD041). + "MD052": false, + "MD034": false, + "MD033": false, + "MD041": false, + + // Duplicate headings are legitimate under different sections (e.g. repeated + // "Documentation"); only flag true sibling duplicates. + "MD024": { "siblings_only": true }, + + // Opinionated table/link/command rules with low value for these docs. + "MD055": false, // table pipe style + "MD060": false, // table column style + "MD059": false, // "descriptive" link text (no "click here") + "MD014": false, // $ before commands without shown output + + // markdownlint does not understand MkDocs `!!!` admonitions, so it reads their + // 4-space-indented bodies as indented code blocks and flags them (and, via inferred + // file style, flags real fenced blocks too). Cannot coexist with our admonitions. + "MD046": false // code block style (fenced vs indented) + // Kept on (structural / real rendering bugs): MD012 (multiple blanks), MD022/MD031/MD032 + // (blanks around headings/fences/lists), MD025 (single H1), MD029 (ordered-list prefix), + // MD040 (fenced code language), MD042 (empty links), + // MD047 (trailing newline), MD056 (table column count), among others. + }, + "globs": ["docs/**/*.md"], + "ignores": [ + "docs/api/**" // mkdocstrings stubs (`::: zarr.X`) + ] +} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 37f41b8222..54345c819e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,22 +2,28 @@ ci: autoupdate_commit_msg: "chore: update pre-commit hooks" autoupdate_schedule: "monthly" autofix_prs: false - skip: [] # pre-commit.ci only checks for updates, prek runs hooks locally + # Both of these are `language: system` hooks that shell out to the local + # toolchain — `uv` for mypy, `uv` and `just` for the docs build — and need + # the repo checkout to resolve their environments from `uv.lock`. Neither is + # available on pre-commit.ci's runners. Each is covered instead by a GitHub + # Actions job (Lint for mypy, zarr-http-server for the docs build) and by + # local prek runs. + skip: [mypy, zarr-http-server-docs] default_stages: [pre-commit, pre-push] default_language_version: - python: python3.11 + python: python3.12 repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.15.4 + rev: v0.16.0 hooks: - id: ruff-check args: ["--fix", "--show-fixes"] - id: ruff-format - repo: https://github.com/codespell-project/codespell - rev: v2.4.1 + rev: v2.4.2 hooks: - id: codespell args: ["-L", "fo,ihs,kake,te", "-S", "fixture"] @@ -27,31 +33,50 @@ repos: - id: check-yaml exclude: mkdocs.yml - id: trailing-whitespace - - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.19.1 + - repo: https://github.com/DavidAnson/markdownlint-cli2 + rev: v0.22.1 + hooks: + # Markdown structure/hygiene. Rule selection and ignores are in + # .markdownlint-cli2.jsonc; complements ci/lint_docs.py (RST residue, + # list-breaking fences) and `mkdocs build --strict`. Scoped to docs/ to + # match the config's globs (pre-commit passes filenames, which would + # otherwise override that scoping and lint all repo Markdown). + - id: markdownlint-cli2 + files: ^docs/ + - repo: local hooks: - id: mypy - files: src|tests - additional_dependencies: - # Package dependencies - - packaging - - donfig - - numcodecs - - google-crc32c>=1.5 - - numpy==2.1 # until https://github.com/numpy/numpy/issues/28034 is resolved - - typing_extensions - - universal-pathlib - - obstore>=0.5.1 - # Tests - - pytest - - hypothesis - - s3fs + name: mypy + language: system + entry: uv run --frozen mypy + pass_filenames: false + always_run: true + types_or: [python, pyi] + # Builds the zarr-http-server docs site with warnings as errors, which + # catches a dead cross-reference or a nav entry pointing at a file that + # no longer exists before it reaches CI. + # + # `stages: [pre-push]` overrides the default of running on every commit: + # this is a whole-site build, too slow to pay per commit and only + # actionable before the code leaves the machine. `files:` limits it to + # changes that touch the package, and `pass_filenames: false` because + # mkdocs builds the site, not a list of files. Delegating to the + # justfile keeps one definition of the build shared with CI. + - id: zarr-http-server-docs + name: zarr-http-server docs build + language: system + entry: >- + just --justfile packages/zarr-http-server/justfile + --working-directory packages/zarr-http-server docs-check + pass_filenames: false + files: ^packages/zarr-http-server/ + stages: [pre-push] - repo: https://github.com/scientific-python/cookie - rev: 2026.03.02 + rev: 2026.06.18 hooks: - id: sp-repo-review - repo: https://github.com/numpy/numpydoc - rev: v1.10.0 + rev: v1.11.0rc0 hooks: - id: numpydoc-validation - repo: local @@ -63,6 +88,10 @@ repos: entry: "\\.(lstrip|rstrip)\\([\"'][^\"']{2,}[\"']\\)" types: [python] files: ^(src|tests)/ + - repo: https://github.com/zizmorcore/zizmor-pre-commit + rev: v1.26.1 + hooks: + - id: zizmor - repo: https://github.com/twisted/towncrier rev: 25.8.0 hooks: diff --git a/.python-version b/.python-version new file mode 100644 index 0000000000..e4fba21835 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.12 diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 1edd099ebd..dddf8449a4 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -5,6 +5,18 @@ build: tools: python: "3.12" jobs: + post_checkout: + # Cancel pull request builds whose changes are confined to the packages + # that have their own Read the Docs projects. 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. Read the Docs strips shell quoting from commands, so the + # exclude pathspecs must use the quote-free :! form, not ':(exclude)'. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- :!packages/zarr-metadata :!packages/zarr-indexing; + then + exit 183; + fi install: - pip install --upgrade pip - pip install .[remote] --group docs diff --git a/README.md b/README.md index 3911ba17b8..330c1da5ea 100644 --- a/README.md +++ b/README.md @@ -4,111 +4,28 @@ # Zarr - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Latest Release - - latest release - -
- - latest release - -
Package Status - - status - -
License - - license - -
Build Status - - build status - -
Pre-commit Status - - pre-commit status - -
Coverage - - coverage - -
Downloads - - pypi downloads - -
Developer Chat - - - -
Funding - - CZI's Essential Open Source Software for Science - -
Citation - - DOI - -
+[![Latest Release](https://badge.fury.io/py/zarr.svg)](https://pypi.org/project/zarr/) +[![CondaForge](https://anaconda.org/conda-forge/zarr/badges/version.svg)](https://anaconda.org/anaconda/zarr/) +[![Package Status](https://img.shields.io/pypi/status/zarr.svg)](https://pypi.org/project/zarr/) +[![License](https://img.shields.io/pypi/l/zarr.svg)](https://github.com/zarr-developers/zarr-python/blob/main/LICENSE.txt) +[![Coverage](https://codecov.io/gh/zarr-developers/zarr-python/branch/main/graph/badge.svg)](https://app.codecov.io/gh/zarr-developers/zarr-python) +[![Downloads](https://static.pepy.tech/badge/zarr)](https://zarr.readthedocs.io/en/stable/) +[![Developer Chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://ossci.zulipchat.com/#narrow/channel/423692-Zarr-Python) +[![Citation](https://zenodo.org/badge/DOI/10.5281/zenodo.3773450.svg)](https://doi.org/10.5281/zenodo.3773450) ## What is it? -Zarr is a Python package providing an implementation of compressed, chunked, N-dimensional arrays, designed for use in parallel computing. See the [documentation](https://zarr.readthedocs.io) for more information. +The `zarr` library is a Python implementation of the [Zarr storage format](https://zarr.dev/). `zarr` delivers compressed, chunked, N-dimensional arrays that work well for parallel computing and object storage. See the [documentation](https://zarr.readthedocs.io/en/stable/) for more information. ## Main Features -- [**Create**](https://zarr.readthedocs.io/en/stable/user-guide/arrays.html#creating-an-array) N-dimensional arrays with any NumPy `dtype`. -- [**Chunk arrays**](https://zarr.readthedocs.io/en/stable/user-guide/performance.html#chunk-optimizations) along any dimension. -- [**Compress**](https://zarr.readthedocs.io/en/stable/user-guide/arrays.html#compressors) and/or filter chunks using any NumCodecs codec. -- [**Store arrays**](https://zarr.readthedocs.io/en/stable/user-guide/storage.html) in memory, on disk, inside a zip file, on S3, etc... -- [**Read**](https://zarr.readthedocs.io/en/stable/user-guide/arrays.html#reading-and-writing-data) an array [**concurrently**](https://zarr.readthedocs.io/en/stable/user-guide/performance.html#parallel-computing-and-synchronization) from multiple threads or processes. -- [**Write**](https://zarr.readthedocs.io/en/stable/user-guide/arrays.html#reading-and-writing-data) to an array concurrently from multiple threads or processes. -- Organize arrays into hierarchies via [**groups**](https://zarr.readthedocs.io/en/stable/quickstart.html#hierarchical-groups). +- [**Create**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#creating-an-array) N-dimensional arrays with NumPy-compatible `dtype`s. +- [**Chunk arrays**](https://zarr.readthedocs.io/en/stable/user-guide/performance/#chunk-optimizations) along any dimension. +- [**Encode**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#compressors) chunks using a variety of useful encodings (e.g., compression). +- [**Store arrays**](https://zarr.readthedocs.io/en/stable/user-guide/storage/) in memory, on disk, inside a zip file, on S3, etc... +- [**Read**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#reading-and-writing-data) an array [**concurrently**](https://zarr.readthedocs.io/en/stable/user-guide/performance/#parallel-computing-and-synchronization) from multiple threads or processes. +- [**Write**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#reading-and-writing-data) to an array concurrently from multiple threads or processes. +- Organize arrays into hierarchies via [**groups**](https://zarr.readthedocs.io/en/stable/quick-start/#hierarchical-groups). ## Where to get it @@ -124,4 +41,12 @@ or via `conda`: conda install -c conda-forge zarr ``` -For more details, including how to install from source, see the [installation documentation](https://zarr.readthedocs.io/en/stable/index.html#installation). +For more details, including how to install from source, see the [installation documentation](https://zarr.readthedocs.io/en/stable/#installation). + +## Repository sub-packages + +In addition to the primary `zarr` implementation, this repository contains other packages that provide specialized functionality with minimal dependencies: + +- [`zarr-metadata`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata): Tools for Zarr metadata. Install with `pip install zarr-metadata`. +- [`zarr-indexing`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing): Tools for lazily indexing chunked arrays. Install with `pip install zarr-indexing`. +- [`zarr-http-server`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server): An HTTP server implementation targeting Zarr data. Install with `pip install zarr-http-server`. diff --git a/TEAM.md b/TEAM.md index e6975d7c04..ce9de1d486 100644 --- a/TEAM.md +++ b/TEAM.md @@ -10,6 +10,8 @@ - @dstansby (David Stansby) - @dcherian (Deepak Cherian) - @TomAugspurger (Tom Augspurger) +- @maxrjones (Max Jones) +- @ilan-gold (Ilan Gold) ## Emeritus core-developers - @alimanfoo (Alistair Miles) diff --git a/changes/3285.feature.md b/changes/3285.feature.md new file mode 100644 index 0000000000..3809c0ab02 --- /dev/null +++ b/changes/3285.feature.md @@ -0,0 +1,13 @@ +JSON metadata validation now delegates to ``msgspec.convert`` for the type +coercions it supports (``Literal`` membership, ``int`` / ``bool`` strictness, +list-to-tuple), replacing the per-field hand-written ``parse_*`` logic. A small +fallback validates the recursive JSON values msgspec cannot, now with an +explicit nesting-depth limit, and a latent generator-exhaustion bug in +``parse_storage_transformers`` is fixed. See #3285. + +As a result some metadata inputs are now parsed more strictly. The previous +per-field checks compared values with ``==``, which accepts any numerically +equal object, so a float such as ``2.0`` was accepted as ``zarr_format``; it is +now rejected because it is not an ``int``. Booleans are likewise no longer +accepted where an ``int`` is expected, since ``bool`` is an ``int`` subclass. +Metadata that conforms to the Zarr specification is unaffected. diff --git a/changes/3464.doc.md b/changes/3464.doc.md deleted file mode 100644 index 155a4575f4..0000000000 --- a/changes/3464.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add documentation example for creating uncompressed arrays in the Compression section of the user guide. diff --git a/changes/3562.misc.md b/changes/3562.misc.md deleted file mode 100644 index e164ab39f8..0000000000 --- a/changes/3562.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add continuous performance benchmarking infrastructure. \ No newline at end of file diff --git a/changes/3603.bugfix.md b/changes/3603.bugfix.md deleted file mode 100644 index 37e1da5cb1..0000000000 --- a/changes/3603.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Correct the target bytes number for auto-chunking when auto-sharding. \ No newline at end of file diff --git a/changes/3605.misc.md b/changes/3605.misc.md deleted file mode 100644 index b8c0757b69..0000000000 --- a/changes/3605.misc.md +++ /dev/null @@ -1 +0,0 @@ -Fix a bug in the test suite that prevented stand-alone example scripts from being tested. \ No newline at end of file diff --git a/changes/3619.misc.md b/changes/3619.misc.md deleted file mode 100644 index 8c36e473b5..0000000000 --- a/changes/3619.misc.md +++ /dev/null @@ -1 +0,0 @@ -Remove upper bounds on `pytest` and `pytest-asyncio` test dependencies. \ No newline at end of file diff --git a/changes/3623.misc.md b/changes/3623.misc.md deleted file mode 100644 index 4060e55e5f..0000000000 --- a/changes/3623.misc.md +++ /dev/null @@ -1,5 +0,0 @@ -This PR contains minor, non-function-altering, changes to use `ZarrFormat` across the repo as opposed to duplicating is with `Literal[2,3]`. - -Additionally, it fixes broken linting by using a `Literal[True, False]` type hint for Numpy hypothesis testing, as opposed to `bool`. - -Basically improves the typehints and reduces fat-finger error surface area slightly. diff --git a/changes/3636.misc.md b/changes/3636.misc.md deleted file mode 100644 index a814160c8b..0000000000 --- a/changes/3636.misc.md +++ /dev/null @@ -1 +0,0 @@ -The minimum required version of NumPy is now 2.0. diff --git a/changes/3648.misc.md b/changes/3648.misc.md deleted file mode 100644 index 156f8671de..0000000000 --- a/changes/3648.misc.md +++ /dev/null @@ -1 +0,0 @@ -Fix deprecation of setting a shape on an array directly in ``numpy`` 2.5+. diff --git a/changes/3655.bugfix.md b/changes/3655.bugfix.md deleted file mode 100644 index 67d384f00d..0000000000 --- a/changes/3655.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Fixed a bug in the sharding codec that prevented nested shard reads in certain cases. \ No newline at end of file diff --git a/changes/3656.misc.md b/changes/3656.misc.md deleted file mode 100644 index 159f24d072..0000000000 --- a/changes/3656.misc.md +++ /dev/null @@ -1 +0,0 @@ -Removed *rich* and *mypy* from the `[test]` dependencies, and added a new `[dev]` dependency group that can be used to install all the development dependencies. diff --git a/changes/3657.bugfix.md b/changes/3657.bugfix.md deleted file mode 100644 index 1411704674..0000000000 --- a/changes/3657.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Fix obstore _transform_list_dir implementation to correctly relativize paths (removing lstrip usage). \ No newline at end of file diff --git a/changes/3658.misc.md b/changes/3658.misc.md deleted file mode 100644 index f400d97473..0000000000 --- a/changes/3658.misc.md +++ /dev/null @@ -1 +0,0 @@ -Switch from `pre-commit` to [`prek`](https://github.com/j178/prek) for pre-commit checks. \ No newline at end of file diff --git a/changes/3668.feature.md b/changes/3668.feature.md deleted file mode 100644 index def196ec8a..0000000000 --- a/changes/3668.feature.md +++ /dev/null @@ -1,4 +0,0 @@ -Exposes the array runtime configuration as an attribute called `config` on the `Array` and -`AsyncArray` classes. The previous `AsyncArray._config` attribute is now a deprecated alias for `AsyncArray.config`. - -Adds a method for creating a new `Array` / `AsyncArray` instance with a new runtime configuration, and fixes inaccurate documentation about the `write_empty_chunks` configuration parameter. \ No newline at end of file diff --git a/changes/3673.misc.md b/changes/3673.misc.md deleted file mode 100644 index 83643f5d3c..0000000000 --- a/changes/3673.misc.md +++ /dev/null @@ -1 +0,0 @@ -Benchmark CI now only runs for PRs with the `benchmark` label, reducing CodSpeed credit usage. diff --git a/changes/3695.bugfix.md b/changes/3695.bugfix.md deleted file mode 100644 index a7d847e4f1..0000000000 --- a/changes/3695.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Raise error when trying to encode :class:`numpy.dtypes.StringDType` with `na_object` set. \ No newline at end of file diff --git a/changes/3700.bugfix.md b/changes/3700.bugfix.md deleted file mode 100644 index 86acb71d0e..0000000000 --- a/changes/3700.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -CacheStore, LoggingStore and LatencyStore now support with_read_only. \ No newline at end of file diff --git a/changes/3702.bugfix.md b/changes/3702.bugfix.md deleted file mode 100644 index 94a2902567..0000000000 --- a/changes/3702.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Skip chunk coordinate enumeration in resize when the array is only growing, avoiding unbounded memory usage for large arrays. \ No newline at end of file diff --git a/changes/3704.misc.md b/changes/3704.misc.md deleted file mode 100644 index d15d4924e0..0000000000 --- a/changes/3704.misc.md +++ /dev/null @@ -1 +0,0 @@ -Remove an expensive `isinstance` check from the bytes codec decoding routine. \ No newline at end of file diff --git a/changes/3705.bugfix.md b/changes/3705.bugfix.md deleted file mode 100644 index 2abcb4ee7c..0000000000 --- a/changes/3705.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Fix a performance bug in morton curve generation. \ No newline at end of file diff --git a/changes/3706.misc.md b/changes/3706.misc.md deleted file mode 100644 index 70a0e44c58..0000000000 --- a/changes/3706.misc.md +++ /dev/null @@ -1 +0,0 @@ -Allow NumPy ints as input when declaring a shape. \ No newline at end of file diff --git a/changes/3708.misc.md b/changes/3708.misc.md deleted file mode 100644 index dce7546c97..0000000000 --- a/changes/3708.misc.md +++ /dev/null @@ -1 +0,0 @@ -Optimize Morton order computation with hypercube optimization, vectorized decoding, and singleton dimension removal, providing 10-45x speedup for typical chunk shapes. diff --git a/changes/3710.bugfix.md b/changes/3710.bugfix.md deleted file mode 100644 index a40ddcee23..0000000000 --- a/changes/3710.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Add a dedicated in-memory cache for byte-range requests to the experimental `CacheStore`. \ No newline at end of file diff --git a/changes/3712.misc.md b/changes/3712.misc.md deleted file mode 100644 index 8fa2f2d2f7..0000000000 --- a/changes/3712.misc.md +++ /dev/null @@ -1 +0,0 @@ -Added benchmarks for Morton order computation in sharded arrays. diff --git a/changes/3713.misc.md b/changes/3713.misc.md deleted file mode 100644 index 9b0680dfc0..0000000000 --- a/changes/3713.misc.md +++ /dev/null @@ -1 +0,0 @@ -Vectorize get_chunk_slice for faster sharded array writes. diff --git a/changes/3717.misc.md b/changes/3717.misc.md deleted file mode 100644 index 5fed76b2b7..0000000000 --- a/changes/3717.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add benchmarks for Morton order computation with non-power-of-2 and near-miss shard shapes, covering both pure computation and end-to-end read/write performance. diff --git a/changes/3721.misc.md b/changes/3721.misc.md deleted file mode 100644 index c170712882..0000000000 --- a/changes/3721.misc.md +++ /dev/null @@ -1 +0,0 @@ -Adds synchronous (non-async) encoding and decoding methods to CPU-bound codecs. This is necessary for performance optimizations based on avoiding `asyncio` overhead. These new methods are described by a new protocol: `SupportsSyncCodec`. \ No newline at end of file diff --git a/changes/3728.misc.md b/changes/3728.misc.md deleted file mode 100644 index a3cbb8d3f0..0000000000 --- a/changes/3728.misc.md +++ /dev/null @@ -1 +0,0 @@ -Move development dependencies (`test`, `remote_tests`, `docs`, `dev`) from optional dependencies to [dependency groups](https://packaging.python.org/en/latest/specifications/dependency-groups/). This may cause breakage for anyone who used e.g. `pip install zarr[test]` to get access to test dependencies. To install these dependency groups from a local checkout, use `pip install --group ` (pip 25.1+) or `uv run --group `. \ No newline at end of file diff --git a/changes/3769.doc.md b/changes/3769.doc.md deleted file mode 100644 index f622ac525f..0000000000 --- a/changes/3769.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add AI-assisted code policy to the contributing guide. diff --git a/changes/3778.misc.md b/changes/3778.misc.md deleted file mode 100644 index 17f26666ed..0000000000 --- a/changes/3778.misc.md +++ /dev/null @@ -1 +0,0 @@ -`Group.tree()` no longer requires the `rich` dependency. Tree rendering now uses built-in ANSI bold for terminals and HTML bold for Jupyter. New parameters: `plain=True` for unstyled output, and `max_nodes` (default 500) to truncate large hierarchies with early bailout. diff --git a/changes/4149.doc.md b/changes/4149.doc.md new file mode 100644 index 0000000000..8a473acac9 --- /dev/null +++ b/changes/4149.doc.md @@ -0,0 +1 @@ +Added a Roadmap page to the documentation outlining future plans and intended changes to the library. diff --git a/changes/4189.bugfix.md b/changes/4189.bugfix.md new file mode 100644 index 0000000000..76ef7e7a5e --- /dev/null +++ b/changes/4189.bugfix.md @@ -0,0 +1 @@ +Allow `Group.require_array` to accept a `ZDType` for `dtype`, matching the other array creation methods. Previously an existing array could only be required with a string or NumPy dtype. diff --git a/changes/4193.doc.md b/changes/4193.doc.md new file mode 100644 index 0000000000..0972e8be2c --- /dev/null +++ b/changes/4193.doc.md @@ -0,0 +1,4 @@ +Converted remaining reStructuredText-style double-backtick markup to Markdown +single backticks in the docstrings of `zarr.api.asynchronous`, +`zarr.api.synchronous`, `zarr.core.array`, `zarr.registry`, and +`zarr.storage._common`. No functional changes. diff --git a/changes/4213.misc.md b/changes/4213.misc.md new file mode 100644 index 0000000000..150e60b57b --- /dev/null +++ b/changes/4213.misc.md @@ -0,0 +1 @@ +Updated ruff to 0.16.0 and fixed the violations surfaced by its expanded default rule set: narrowed a blind `except Exception` in `StorePath.__eq__` to `AttributeError`, removed unnecessary `global` declarations in `zarr.core.sync`, made `subprocess.run` calls in tests pass `check=False` explicitly, and applied automatic fixes (`None` moved to the end of type unions, unused `noqa` directives removed). diff --git a/changes/4227.bugfix.md b/changes/4227.bugfix.md new file mode 100644 index 0000000000..18293178bd --- /dev/null +++ b/changes/4227.bugfix.md @@ -0,0 +1 @@ +Consolidated metadata is now reconstructed independently of the order the keys appear in on disk. Previously, sibling subtrees whose keys were not adjacent in the persisted mapping lost their children, which made nodes unreachable through consolidated metadata -- most visibly for sibling groups whose names differ only by case. diff --git a/changes/4239.bugfix.md b/changes/4239.bugfix.md new file mode 100644 index 0000000000..b5bc92f18b --- /dev/null +++ b/changes/4239.bugfix.md @@ -0,0 +1 @@ +`FsspecStore.from_mapper` and `FsspecStore.from_url` no longer fail when converting a synchronous instance of an async-capable filesystem whose storage options contain objects that cannot be serialized to JSON (e.g. an `azure.identity.DefaultAzureCredential`). The async instance is now constructed from the original filesystem arguments instead of a JSON round-trip. diff --git a/changes/4247.doc.md b/changes/4247.doc.md new file mode 100644 index 0000000000..6dbca1d3d6 --- /dev/null +++ b/changes/4247.doc.md @@ -0,0 +1,5 @@ +Added a "Related Projects" page to the documentation listing the companion +packages developed in this repository — `zarr-metadata` and `zarr-indexing` — +and linked it from the landing page. Links to those packages now use the +canonical `https://zarr.readthedocs.io/projects/...` URLs, and each companion +package's documentation links back to the `zarr-python` docs. diff --git a/changes/4257.bugfix.md b/changes/4257.bugfix.md new file mode 100644 index 0000000000..6f2740ccb4 --- /dev/null +++ b/changes/4257.bugfix.md @@ -0,0 +1 @@ +Numpy integers are accepted as chunk sizes again. Since 3.3.0 a per-dimension chunk size that was a numpy integer (e.g. `chunks=(np.int64(2), np.int64(2))`, as produced by any computed chunk shape) raised `TypeError: 'numpy.int64' object is not iterable`, because the scalar chunk path narrowed on `int` while its caller dispatched on `numbers.Integral`. Numpy arrays are now also accepted as chunk specifications, and a chunk specification that is neither an integer nor iterable now reports the offending value instead of failing with an opaque iteration error. diff --git a/changes/4260.bugfix.md b/changes/4260.bugfix.md new file mode 100644 index 0000000000..b703c47a35 --- /dev/null +++ b/changes/4260.bugfix.md @@ -0,0 +1 @@ +The `cast_value` codec now requires `cast-value-rs>=0.4.2`. Earlier versions of that backend silently corrupted data when handed an array that was not row-major — the layout the `transpose` codec produces — so a `cast_value` codec next to a `transpose` codec would either write transposed values with no error or fail with `ValueError: Input array must be contiguous`. The minimum version is enforced at runtime as well as in the package metadata, so an environment that already has an older `cast-value-rs` installed now raises `ImportError` when the codec is used, instead of corrupting data. diff --git a/changes/4261.misc.md b/changes/4261.misc.md new file mode 100644 index 0000000000..ca2a3fbb1e --- /dev/null +++ b/changes/4261.misc.md @@ -0,0 +1 @@ +The contents of the `zarr` source distribution are now defined by an explicit allowlist rather than a blocklist. Previously the sdist bundled the whole `packages/` tree — `zarr-indexing`, `zarr-metadata` and `zarr-http-server`, which are released as their own distributions — along with CI configuration and other repository files. The sdist also now ships `docs/`, so the test suite it carries can be collected and run from an unpacked sdist. diff --git a/changes/4265.bugfix.md b/changes/4265.bugfix.md new file mode 100644 index 0000000000..6daf0fc7d0 --- /dev/null +++ b/changes/4265.bugfix.md @@ -0,0 +1,13 @@ +Accept [universal-pathlib](https://github.com/fsspec/universal_pathlib) `UPath` objects wherever +zarr accepts a `StoreLike` value. A remote `UPath` now creates an `FsspecStore` using the +filesystem and storage options the `UPath` already carries, and a local `UPath` creates a +`LocalStore`, so that `UPath('/data')` and `Path('/data')` behave the same. + +Previously this worked only by accident: in universal-pathlib < 0.3 every `UPath` subclassed +`pathlib.Path` and implemented `__fspath__`, so remote paths were either converted to a URI string +by the caller or wrapped in a `LocalStore` that happened to dispatch through fsspec. Since +universal-pathlib 0.3 remote paths do neither, and passing one raised +`TypeError: Unsupported type for store_like`. + +`FsspecStore.from_upath` also now converts the `UPath`'s filesystem to async mode, instead of +raising `TypeError` for synchronous filesystems and warning for sync-mode instances of async ones. diff --git a/changes/4279.bugfix.md b/changes/4279.bugfix.md new file mode 100644 index 0000000000..7d99a49ccf --- /dev/null +++ b/changes/4279.bugfix.md @@ -0,0 +1 @@ +A `scale_offset` codec configured with a string-valued zero scale is now rejected. `scale` accepts strings, and no string is ever equal to `0`, so `"0"`, `"0.0"` and the hex form `"0x0000000000000000"` skipped the "scale must be non-zero" check that the numeric `0` triggers. On float data types the array was created, every chunk was written as zero and read back as `nan` with no error, and the zero scale was persisted to the metadata so reopening the store reproduced it; on integer data types the codec raised `ZeroDivisionError` instead of `ValueError`. The check now runs on the parsed scalar rather than the value as supplied. diff --git a/ci/check_changelog_entries.py b/ci/check_changelog_entries.py index da2700e32a..42d7cc1708 100644 --- a/ci/check_changelog_entries.py +++ b/ci/check_changelog_entries.py @@ -1,12 +1,18 @@ """ Check changelog entries have the correct filename structure. + +Usage: + python check_changelog_entries.py [DIRECTORY] + +DIRECTORY defaults to the repo-root `changes/`. """ import sys from pathlib import Path VALID_CHANGELOG_TYPES = ["feature", "bugfix", "doc", "removal", "misc"] -CHANGELOG_DIRECTORY = (Path(__file__).parent.parent / "changes").resolve() +REPO_ROOT = Path(__file__).parent.parent.resolve() +DEFAULT_DIRECTORY = REPO_ROOT / "changes" def is_int(s: str) -> bool: @@ -18,34 +24,47 @@ def is_int(s: str) -> bool: return True -if __name__ == "__main__": - print(f"Looking for changelog entries in {CHANGELOG_DIRECTORY}") - entries = CHANGELOG_DIRECTORY.glob("*") +def check(directory: Path) -> int: + print(f"Looking for changelog entries in {directory}") + entries = list(directory.glob("*")) entries = [e for e in entries if e.name not in [".gitignore", "README.md"]] print(f"Found {len(entries)} entries") print() bad_suffix = [e for e in entries if e.suffix != ".md"] bad_issue_no = [e for e in entries if not is_int(e.name.split(".")[0])] - bad_type = [e for e in entries if e.name.split(".")[1] not in VALID_CHANGELOG_TYPES] + # Only flag bad_type for files that have already passed the prior two + # checks; otherwise `e.name.split(".")[1]` may raise IndexError on a + # malformed name like `notes.md`. + bad_type = [ + e + for e in entries + if e.suffix == ".md" + and is_int(e.name.split(".")[0]) + and e.name.split(".")[1] not in VALID_CHANGELOG_TYPES + ] - if len(bad_suffix) or len(bad_issue_no) or len(bad_type): - if len(bad_suffix): + if bad_suffix or bad_issue_no or bad_type: + if bad_suffix: print("Changelog entries without .md suffix") print("-------------------------------------") - print("\n".join([p.name for p in bad_suffix])) + print("\n".join(p.name for p in bad_suffix)) print() - if len(bad_issue_no): + if bad_issue_no: print("Changelog entries without integer issue number") print("----------------------------------------------") - print("\n".join([p.name for p in bad_issue_no])) + print("\n".join(p.name for p in bad_issue_no)) print() - if len(bad_type): + if bad_type: print("Changelog entries without valid type") print("------------------------------------") - print("\n".join([p.name for p in bad_type])) + print("\n".join(p.name for p in bad_type)) print(f"Valid types are: {VALID_CHANGELOG_TYPES}") print() - sys.exit(1) + return 1 + return 0 - sys.exit(0) + +if __name__ == "__main__": + directory = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else DEFAULT_DIRECTORY + sys.exit(check(directory)) diff --git a/ci/check_documented_exports.py b/ci/check_documented_exports.py new file mode 100644 index 0000000000..0772954399 --- /dev/null +++ b/ci/check_documented_exports.py @@ -0,0 +1,161 @@ +"""Check that every public top-level export is in the API reference. + +The API reference is authored as explicit mkdocstrings directives (``::: target``) +under ``docs/api/`` -- one per documented symbol -- rather than autodoc, so a newly +added ``zarr.__all__`` entry will not appear in the docs until someone writes a page +for it (or it becomes a rendered member of an already-documented module). This script +catches that gap: it resolves every ``:::`` target, expands module directives into the +members they render (honoring ``members: false``), and asserts each name in +``zarr.__all__`` resolves to a documented object. + +Usage: + python ci/check_documented_exports.py [API_DOCS_DIR] + +API_DOCS_DIR defaults to the repo-root ``docs/api``. Exits non-zero (and prints the +undocumented exports to stderr) if any public export is missing from the reference. +""" + +from __future__ import annotations + +import importlib +import re +import sys +from pathlib import Path +from types import ModuleType +from typing import TYPE_CHECKING, Any + +import zarr + +if TYPE_CHECKING: + from collections.abc import Iterator + +REPO_ROOT = Path(__file__).parent.parent.resolve() +DEFAULT_API_DOCS_ROOT = REPO_ROOT / "docs" / "api" + +# Names in zarr.__all__ that are intentionally absent from the API reference. +# Keep this list short and justified -- it is the only escape hatch from the guard. +EXEMPT_EXPORTS = { + "__version__", # version string, not an API symbol + "print_debug_info", # debugging helper, deliberately not in the reference +} + +# A mkdocstrings autodoc directive: `::: some.dotted.target` at the start of a line. +DIRECTIVE_RE = re.compile(r"^:::[ \t]+(?P\S+)") +# `members: false` (or `members: []`) within a directive's option block disables +# rendering of a module's members. +MEMBERS_DISABLED_RE = re.compile(r"^\s+members:\s*(false|\[\s*\])\s*$") + + +def resolve(target: str) -> Any: + """Resolve a `:::` target (a dotted path) to the Python object it documents.""" + try: + return importlib.import_module(target) + except ImportError: + pass + module_path, _, attr = target.rpartition(".") + try: + return getattr(importlib.import_module(module_path), attr) + except (ImportError, AttributeError): + return None + + +def iter_directives(text: str) -> Iterator[tuple[str, bool]]: + """Yield ``(target, members_enabled)`` for each ``:::`` directive in ``text``. + + The file is split into lines once; for each directive we scan its indented option + block -- stopping at the first non-indented line, which ends the block -- so options + belonging to a later directive are never consulted. ``members_enabled`` is False when + that block sets ``members: false`` (or ``members: []``).""" + lines = text.splitlines() + i = 0 + while i < len(lines): + match = DIRECTIVE_RE.match(lines[i]) + if match is None: + i += 1 + continue + members_enabled = True + i += 1 + while i < len(lines): + line = lines[i] + if line.strip() == "": + i += 1 + continue + if not line.startswith((" ", "\t")): + break # non-indented line: end of this directive's option block + if MEMBERS_DISABLED_RE.match(line): + members_enabled = False + i += 1 + yield match.group("target"), members_enabled + + +def module_member_ids(module: ModuleType) -> Iterator[int]: + """Yield the id() of each public member a module directive renders. + + The rendered members are the module's ``__all__`` if defined, else its public + (non-underscore) attributes.""" + member_names = getattr(module, "__all__", None) or [ + name for name in dir(module) if not name.startswith("_") + ] + for name in member_names: + member = getattr(module, name, None) + if member is not None: + yield id(member) + + +def documented_object_ids(api_docs_root: Path) -> set[int]: + """Collect the id()s of every object rendered by a `:::` directive under api_docs_root. + + A directive pointing at an object documents that object. A directive pointing at a + module documents the module's public members unless the directive sets + ``members: false``.""" + documented: set[int] = set() + for md_file in sorted(api_docs_root.rglob("*.md")): + for target, members_enabled in iter_directives(md_file.read_text(encoding="utf-8")): + obj = resolve(target) + if obj is None: + continue + documented.add(id(obj)) + if isinstance(obj, ModuleType) and members_enabled: + documented.update(module_member_ids(obj)) + return documented + + +def find_undocumented_exports(api_docs_root: Path) -> list[str]: + documented = documented_object_ids(api_docs_root) + return sorted( + name + for name in zarr.__all__ + if name not in EXEMPT_EXPORTS and id(getattr(zarr, name)) not in documented + ) + + +def main() -> int: + args = sys.argv[1:] + api_docs_root = Path(args[0]).resolve() if args else DEFAULT_API_DOCS_ROOT + if not api_docs_root.exists(): + print(f"{api_docs_root} does not exist.", file=sys.stderr) + return 1 + + missing = find_undocumented_exports(api_docs_root) + if not missing: + print(f"All {len(zarr.__all__)} public exports are documented.") + return 0 + + print( + f"Found {len(missing)} public export(s) in zarr.__all__ missing from the API " + "reference (docs/api/):\n", + file=sys.stderr, + ) + for name in missing: + print(f" - zarr.{name}", file=sys.stderr) + print( + "\nAdd a `::: zarr.` page under docs/api/zarr/ (and register it in " + "mkdocs.yml and docs/api/zarr/index.md), or -- if the export is intentionally " + "undocumented -- add it to EXEMPT_EXPORTS in this script with a reason.", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ci/check_unlinked_types.py b/ci/check_unlinked_types.py new file mode 100644 index 0000000000..3ccfaab397 --- /dev/null +++ b/ci/check_unlinked_types.py @@ -0,0 +1,88 @@ +"""Check for unlinked type annotations in built documentation. + +mkdocstrings renders resolved types as links and unresolved +types as Name without an anchor. +This script finds all such unlinked types in the built HTML and reports them. + +Usage: + python ci/check_unlinked_types.py [site_dir] + +Raises ValueError if unlinked types are found. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +# Matches the griffe/mkdocstrings pattern for unlinked cross-references: +# Name +UNLINKED_PATTERN = re.compile( + r'(?P[^<]+)' +) + +# Patterns to exclude from the report +EXCLUDE_PATTERNS = [ + # TypeVars and type parameters (single brackets like Foo[T]) + re.compile(r"\[.+\]$"), + # Dataclass field / namedtuple field references (contain parens) + re.compile(r"\("), + # Private names + re.compile(r"\._"), + # Dunder attributes + re.compile(r"\.__\w+__$"), + # Testing utilities + re.compile(r"^zarr\.testing\."), + # Third-party types (hypothesis, pytest, etc.) + re.compile(r"^(hypothesis|pytest|typing_extensions|builtins|dataclasses)\."), +] + + +def should_exclude(qualname: str) -> bool: + return any(p.search(qualname) for p in EXCLUDE_PATTERNS) + + +def find_unlinked_types(site_dir: Path) -> dict[str, set[str]]: + """Find all unlinked types in built HTML files. + + Returns a dict mapping qualified type names to the set of pages where they appear. + """ + api_dir = site_dir / "api" + if not api_dir.exists(): + raise FileNotFoundError(f"{api_dir} does not exist. Run 'mkdocs build' first.") + + unlinked: dict[str, set[str]] = {} + for html_file in api_dir.rglob("*.html"): + content = html_file.read_text(errors="replace") + rel_path = str(html_file.relative_to(site_dir)) + for match in UNLINKED_PATTERN.finditer(content): + qualname = match.group("qualname") + if not should_exclude(qualname): + unlinked.setdefault(qualname, set()).add(rel_path) + + return unlinked + + +def main() -> None: + site_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("site") + unlinked = find_unlinked_types(site_dir) + + if not unlinked: + print("No unlinked types found.") + return + + lines = [f"Found {len(unlinked)} unlinked types:\n"] + for qualname in sorted(unlinked): + pages = sorted(unlinked[qualname]) + lines.append(f" {qualname}") + lines.extend(f" - {page}" for page in pages) + + all_pages = {p for ps in unlinked.values() for p in ps} + lines.append(f"\nTotal: {len(unlinked)} unlinked types across {len(all_pages)} pages") + report = "\n".join(lines) + raise ValueError(report) + + +if __name__ == "__main__": + main() diff --git a/ci/lint_docs.py b/ci/lint_docs.py new file mode 100644 index 0000000000..a847e8aa9d --- /dev/null +++ b/ci/lint_docs.py @@ -0,0 +1,341 @@ +"""Lint docstrings and Markdown for reStructuredText markup that won't render. + +This project renders API docs with mkdocstrings (``docstring_style: numpy``) and prose +with MkDocs + Markdown -- not Sphinx/reStructuredText. RST constructs that survive from +older docstrings (or muscle memory) are not interpreted: a Sphinx role passes through as +literal text instead of becoming a link, an ``.. note::`` directive renders as a stray +line, and a ``:param:`` field list never becomes a documented parameter. + +Crucially, none of this is caught by the rest of the docs CI. ``mkdocs build --strict`` +sees the residue as ordinary prose (no warning), and ``ci/check_unlinked_types.py`` only +finds cross-references mkdocstrings *attempted* to resolve -- a raw ``:class:`` role is +never attempted, so it leaves no unlinked-type span. This linter fills that gap with a +fast, source-level check that needs no docs build. + +Checks fall into two groups -- RST markup that silently fails under MkDocs/mkdocstrings, +and Markdown structural problems that render as valid-but-wrong HTML (so `mkdocs build` +emits no warning): + + sphinx-role :class:`X`, :func:`X`, :py:meth:`X` -> [`X`][zarr.X] + rst-directive .. note:: / .. code-block:: python -> MkDocs admonition / fenced code + rst-field :param x:, :returns:, :rtype: -> numpydoc Parameters/Returns/Raises + rst-link `text `_ -> [text](https://example) + list-break unindented code fence between list items -> indent the fence under its item + list-indent continuation block indented < 4 spaces -> indent it 4 spaces + list-blank list item directly after indented block -> blank line before the item + +The ``list-break`` check catches a fenced code block at column 0 placed *between* two list +items: because the fence is not indented into the preceding item, Markdown ends the list at +the fence and the following item starts a fresh list -- renumbering an ordered list (1, 1, 2 +instead of 1, 2, 3) or breaking the grouping/spacing of any list. markdownlint's MD029 only +notices this for sequentially-numbered ordered lists; lazily-numbered (1., 1.) and unordered +lists slip past it, so this structural check covers the gap. + +The ``list-indent`` and ``list-blank`` checks catch the two halves of Python-Markdown's +strict list-continuation rules, which differ from CommonMark. A blank-line-separated +block (paragraph, nested list, table) belongs to a list item only when indented at least +4 spaces; at the 2-space indent other renderers accept, Python-Markdown ends the list and +the block escapes to the top level (``list-indent``). And a new list item can not start +directly after an indented continuation block: without a blank line first, the ``- `` line +is lazily absorbed into the preceding paragraph as literal text (``list-blank``). Both +produced silently-broken changelog rendering in ``docs/release-notes.md``. + +Usage: + python ci/lint_docs.py [PATH ...] + +PATH defaults to the repo-root ``src/zarr`` and ``docs``. Each PATH may be a file or a +directory (directories are searched for ``*.py`` and ``*.md``). Exits non-zero if any +issues are found. +""" + +from __future__ import annotations + +import ast +import re +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import NamedTuple + +REPO_ROOT = Path(__file__).parent.parent.resolve() +DEFAULT_PATHS = (REPO_ROOT / "src" / "zarr", REPO_ROOT / "docs") + +# A Sphinx interpreted-text role: an optional domain, a role name, then a backtick +# target -- e.g. :class:`Foo` or :py:meth:`Foo.bar`. Requires the trailing backtick so +# plain "::" (RST literal markers, time strings, mkdocs-material :icon: shortcodes) and +# URLs ("https://") never match. +SPHINX_ROLE = re.compile(r":[a-zA-Z_]\w*(?::[a-zA-Z_]\w*)?:`[^`\n]+`") + +# An RST directive line: ".. name::" (with or without an argument after it). RST hyperlink +# targets (".. _label:") and comments (".. text") lack the "::" and are not flagged. +RST_DIRECTIVE = re.compile(r"^\s*\.\.[ \t]+[\w-]+::") + +# An RST field-list entry used for docstring fields. The role names above (class, func, +# ...) are deliberately excluded so a role is reported as a role, not a field. +RST_FIELD = re.compile( + r"^\s*:(param|parameter|arg|argument|key|keyword|kwarg|type|returns?|rtype" + r"|raises?|except|exception|yields?|ytype|var|cvar|ivar)\b[^:]*:" +) + +# An RST external hyperlink: `text `_ +RST_LINK = re.compile(r"`[^`\n]+\n]+>`_") + +# A list item at column 0: an ordered marker (1. / 1)) or a bullet (-, *, +) followed by +# whitespace and content. Leading-whitespace (nested/continuation) lines are intentionally +# not matched -- the list-break check only fires on top-level items. +LIST_ITEM = re.compile(r"^(?:\d+[.)]|[-*+])\s+\S") + + +class Check(NamedTuple): + """One docs-residue check: its category, the line pattern that flags it (None for a + structural check matched outside ``_scan_line``), and the user-facing remediation + shown by ``main()``. Keeping ``example``/``fix`` here makes this the single source for + the help text, so adding a check can't leave the help out of date.""" + + category: str + pattern: re.Pattern[str] | None + example: str + fix: str + + +# The ``list-*`` checks carry no pattern -- they are detected structurally, not by scanning +# a single line -- but they appear here so they share the remediation help. +CHECKS = ( + Check("sphinx-role", SPHINX_ROLE, ":class:`X`", "[`X`][zarr.X]"), + Check("rst-directive", RST_DIRECTIVE, ".. note::", "MkDocs admonition (!!! note)"), + Check("rst-field", RST_FIELD, ":param x:", "numpydoc Parameters/Returns/Raises section"), + Check("rst-link", RST_LINK, "`text `_", "[text](url)"), + Check("list-break", None, "fence between items", "indent the fence 4 spaces to nest it"), + Check("list-indent", None, "2-space continuation", "indent the block 4 spaces under its item"), + Check("list-blank", None, "item after indented block", "add a blank line before the item"), +) + + +@dataclass(frozen=True) +class Finding: + path: Path + line: int + category: str + snippet: str + + def format(self) -> str: + try: + location: Path | str = self.path.relative_to(REPO_ROOT) + except ValueError: + location = self.path + return f" {location}:{self.line}: [{self.category}] {self.snippet.strip()}" + + +def _scan_line(text: str) -> list[str]: + """Return every RST-residue category found in a single line (a line can carry more + than one, e.g. a role and an external link).""" + return [c.category for c in CHECKS if c.pattern is not None and c.pattern.search(text)] + + +def lint_python(path: Path) -> list[Finding]: + """Scan the docstrings (module, classes, functions) of a Python file. + + Only docstrings are checked -- they are what mkdocstrings renders -- so RST-looking + text inside ordinary code or string literals is never misreported.""" + source = path.read_text(encoding="utf-8") + try: + tree = ast.parse(source) + except SyntaxError as exc: # pragma: no cover - surfaced, not silently skipped + return [Finding(path, exc.lineno or 0, "syntax-error", str(exc.msg))] + + doc_nodes = (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef) + # node.body[0].value is the docstring literal; its lineno is the line the string opens + # on, so content line i maps to source line (start + i). + docstrings = [ + (docstring, node.body[0].value.lineno) # type: ignore[attr-defined] + for node in ast.walk(tree) + if isinstance(node, doc_nodes) + if (docstring := ast.get_docstring(node, clean=False)) + ] + return [ + Finding(path, start + offset, category, line) + for docstring, start in docstrings + for offset, line in enumerate(docstring.splitlines()) + for category in _scan_line(line) + ] + + +class Fence(NamedTuple): + """A fenced code block, by 0-based line index. ``terminated`` is False when the fence + has no closing delimiter before EOF, in which case ``close`` is the last line.""" + + open: int + close: int + terminated: bool + + +def fenced_blocks(lines: list[str]) -> list[Fence]: + """Index every fenced code block in ``lines``. + + An unterminated fence is malformed Markdown that `mkdocs build` surfaces anyway; it is + still returned (with ``terminated=False``, ``close`` at the last line) so callers that + skip code can skip to EOF.""" + blocks: list[Fence] = [] + fence: str | None = None + open_idx = -1 + for i, line in enumerate(lines): + stripped = line.lstrip() + if fence is None: + if stripped.startswith(("```", "~~~")): + fence, open_idx = stripped[:3], i + elif stripped.startswith(fence): + blocks.append(Fence(open_idx, i, terminated=True)) + fence = None + if fence is not None: + blocks.append(Fence(open_idx, len(lines) - 1, terminated=False)) + return blocks + + +def find_list_breaking_fences(lines: list[str], blocks: list[Fence]) -> list[tuple[int, str]]: + """Return ``(lineno, snippet)`` for each fenced code block at column 0 that splits a + list -- i.e. one whose nearest non-blank neighbours on both sides are top-level list + items. Such a fence is not indented into the preceding item, so Markdown closes the + list at the fence and the following item starts a new one. The fix is to indent the + fence (4 spaces) so it nests inside its list item. See the module docstring. + + Conservative on purpose: it requires a list item *directly* before and after (a + continuation line or paragraph in between is not matched), keeping false positives low + for a check that fails CI. Unterminated fences are ignored.""" + + def neighbour(start: int, step: int) -> str | None: + j = start + step + while 0 <= j < len(lines): + if lines[j].strip(): + return lines[j] + j += step + return None + + def splits_a_list(open_i: int, close_i: int) -> bool: + if lines[open_i][:1].isspace(): + return False # indented fence: already nested in the list item, not a break + before = neighbour(open_i, -1) + after = neighbour(close_i, +1) + return bool(before and after and LIST_ITEM.match(before) and LIST_ITEM.match(after)) + + return [ + (fence.open + 1, lines[fence.open]) + for fence in blocks + if fence.terminated and splits_a_list(fence.open, fence.close) + ] + + +def find_list_continuation_issues( + lines: list[str], in_code: set[int] +) -> list[tuple[int, str, str]]: + """Return ``(lineno, category, snippet)`` for list continuations Python-Markdown will + mis-render (see the module docstring): + + - ``list-indent``: a blank-line-separated block inside a list item indented 1-3 + spaces. Python-Markdown requires 4; at less, the block escapes the list. + - ``list-blank``: a top-level list item directly after a line indented 4+ spaces. + Without a blank line in between, the item is absorbed into the preceding paragraph + as literal ``- `` text. + + Lazy continuations (an indented line with no blank line before it) are valid at any + indent and are not flagged. Fenced-code lines are opaque: never flagged themselves, + but they keep the item scope open and their indent feeds the ``list-blank`` check so + an item directly after an indented fence is still caught.""" + findings: list[tuple[int, str, str]] = [] + in_item = False # inside a top-level list item's scope + prev_blank = True + prev_indent = 0 + for i, line in enumerate(lines): + stripped = line.strip() + if not stripped: + prev_blank = True + continue + indent = len(line) - len(line.lstrip(" ")) + if i not in in_code: + if indent == 0: + is_item = bool(LIST_ITEM.match(line)) + if is_item and in_item and not prev_blank and prev_indent >= 4: + findings.append((i + 1, "list-blank", line)) + in_item = is_item + elif in_item and prev_blank and indent < 4: + findings.append((i + 1, "list-indent", line)) + prev_blank = False + prev_indent = indent + return findings + + +def lint_markdown(path: Path) -> list[Finding]: + """Scan a Markdown file: RST residue in prose (skipping fenced code blocks), plus + list-structure problems (see find_list_breaking_fences and + find_list_continuation_issues).""" + lines = path.read_text(encoding="utf-8").splitlines() + blocks = fenced_blocks(lines) + in_code = {i for fence in blocks for i in range(fence.open, fence.close + 1)} + + prose = [ + Finding(path, lineno, category, line) + for lineno, line in enumerate(lines, start=1) + if lineno - 1 not in in_code + for category in _scan_line(line) + ] + breaks = [ + Finding(path, lineno, "list-break", snippet) + for lineno, snippet in find_list_breaking_fences(lines, blocks) + ] + continuations = [ + Finding(path, lineno, category, snippet) + for lineno, category, snippet in find_list_continuation_issues(lines, in_code) + ] + return prose + breaks + continuations + + +def iter_files(paths: tuple[Path, ...]) -> list[Path]: + files: list[Path] = [] + for path in paths: + if path.is_file(): + files.append(path) + elif path.is_dir(): + files.extend(sorted(path.rglob("*.py"))) + files.extend(sorted(path.rglob("*.md"))) + else: + raise FileNotFoundError(f"{path} does not exist") + return files + + +LINTERS = {".py": lint_python, ".md": lint_markdown} + + +def lint(paths: tuple[Path, ...]) -> list[Finding]: + return [ + finding + for file in iter_files(paths) + if file.suffix in LINTERS + for finding in LINTERS[file.suffix](file) + ] + + +def main() -> int: + args = sys.argv[1:] + paths = tuple(Path(a).resolve() for a in args) if args else DEFAULT_PATHS + findings = lint(paths) + + if not findings: + print("No reStructuredText residue or list-breaking fences found in docs.") + return 0 + + print( + f"Found {len(findings)} docs issue(s) -- RST markup that will not render under " + "MkDocs/mkdocstrings, or Markdown that renders as valid-but-wrong HTML:\n", + file=sys.stderr, + ) + for finding in findings: + print(finding.format(), file=sys.stderr) + remediation = "\n".join(f" {c.category:<13} {c.example:<19} -> {c.fix}" for c in CHECKS) + print( + f"\nFix each issue (see ci/lint_docs.py header):\n{remediation}", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/codecov.yml b/codecov.yml index ef535fd8fe..a3783cc39a 100644 --- a/codecov.yml +++ b/codecov.yml @@ -8,9 +8,21 @@ coverage: default: target: auto threshold: 0.1 + flags: + - tests +flags: + tests: + paths: + - src/ + carryforward: true + gpu: + paths: + - src/ + carryforward: true codecov: notify: - after_n_builds: 10 # Wait for all 10 reports before updating the status + # 6 = test.yml: 3 (optional+ubuntu) + 2 (upstream + min_deps), hypothesis: 1 + after_n_builds: 6 wait_for_ci: yes comment: layout: "diff, files" diff --git a/design/chunk-grid.md b/design/chunk-grid.md new file mode 100644 index 0000000000..0f12e35c4b --- /dev/null +++ b/design/chunk-grid.md @@ -0,0 +1,720 @@ +# Unified Chunk Grid + +Version: 6 + +Design document for adding rectilinear (variable) chunk grid support to **zarr-python**, conforming to the [rectilinear chunk grid extension spec](https://github.com/zarr-developers/zarr-extensions/pull/25). + +**Related:** + +- [#3750](https://github.com/zarr-developers/zarr-python/issues/3750) (single ChunkGrid proposal) +- [#3534](https://github.com/zarr-developers/zarr-python/pull/3534) (rectilinear implementation) +- [#3735](https://github.com/zarr-developers/zarr-python/pull/3735) (chunk grid module/registry) +- [ZEP0003](https://github.com/zarr-developers/zeps/blob/main/draft/ZEP0003.md) (variable chunking spec) +- [zarr-specs#370](https://github.com/zarr-developers/zarr-specs/pull/370) (sharding v1.1: non-divisible subchunks) +- [zarr-extensions#25](https://github.com/zarr-developers/zarr-extensions/pull/25) (rectilinear extension) +- [zarr-extensions#34](https://github.com/zarr-developers/zarr-extensions/issues/34) (sharding + rectilinear) + +## Problem + +Chunk grids form a hierarchy — the rectilinear grid is strictly more general than the regular grid. Any regular grid is expressible as a rectilinear grid. There is no known chunk grid that is both (a) more general than rectilinear and (b) retains the axis-aligned tessellation properties Zarr assumes. All known grids are special cases: + +| Grid type | Description | Example | +|---|---|---| +| Regular | Uniform chunk size, boundary chunks padded with fill_value | `[10, 10, 10, 10]` | +| Regular-bounded (zarrs) | Uniform chunk size, boundary chunks trimmed to array extent | `[10, 10, 10, 5]` | +| HPC boundary-padded | Regular interior, larger boundary chunks ([VirtualiZarr#217](https://github.com/zarr-developers/VirtualiZarr/issues/217)) | `[10, 8, 8, 8, 10]` | +| Fully variable | Arbitrary per-chunk sizes | `[5, 12, 3, 20]` | + +Prior iterations on the chunk grid design were based on the Zarr V3 spec's definition of chunk grids as an extension point alongside codecs, dtypes, etc. Therefore, we started designing the chunk grid implementation following a similar registry-based approach. However, in practice chunk grids are fundamentally different than codecs. Codecs are independent; supporting `zstd` tells you nothing about `gzip`. Chunk grids are not: every regular grid is a valid rectilinear grid. A registry-based plugin system makes sense for codecs but adds complexity without clear benefit for chunk grids. Here we start from some basic goals and propose a more fitting design for supporting different chunk grids in zarr-python. + +## Goals + +1. **Follow the zarr extension proposal.** The implementation should conform to the [rectilinear chunk grid spec](https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear), not innovate on the metadata format. +2. **Minimize changes to the public API.** Users creating regular arrays should see no difference. Rectilinear is additive. +3. **Maintain backwards compatibility.** Existing code using `.chunks`, `isinstance` checks, or importing `RegularChunkGrid`/`RectilinearChunkGrid` from `zarr.core.chunk_grids` should continue to work where practical (with deprecation warnings where appropriate). Internal code paths/imports may be broken with justification. +4. **Design for future iteration.** The internal architecture should allow refactoring (e.g., metadata/array separation, new dimension types) without breaking the public API. +5. **Minimize downstream changes.** xarray, VirtualiZarr, Icechunk, Cubed, etc. should need minimal updates. +6. **Minimize time to stable release.** Ship behind a feature flag, stabilize through real-world usage, promote to stable API. +7. **The new API should be useful.** `read_chunk_sizes`/`write_chunk_sizes`, `ChunkGrid.__getitem__`, `is_regular` — these should solve real problems, not just expose internals. +8. **Extensible for other serialization structures.** The per-dimension design should support future encodings (tile, temporal) without changes to indexing or codecs. + +## Design + +### Design choices + +1. **A chunk grid is a concrete arrangement of chunks.** Not an abstract tiling pattern. This means that the chunk grid is bound to specific array dimensions, which enables the chunk grid to answer any question about any chunk (offset, size, count) without external parameters. +2. **One implementation, multiple serialization forms.** A single `ChunkGrid` class handles all chunking logic. The serialization format (`"regular"` vs `"rectilinear"`) is chosen by the metadata layer, not the grid. +3. **No chunk grid registry.** Simple name-based dispatch in the metadata layer's `parse_chunk_grid()`. +4. **Fixed vs Varying per dimension.** `FixedDimension(size, extent)` for uniform chunks; `VaryingDimension(edges, extent)` for per-chunk edge lengths with precomputed prefix sums. Avoids expanding regular dimensions into lists of identical values. +5. **Transparent transitions.** Operations like `resize()` can move an array from regular to rectilinear chunking. + +### Internal representation + +```python +@dataclass(frozen=True) +class FixedDimension: + """Uniform chunk size. Boundary chunks contain less data but are + encoded at full size by the codec pipeline.""" + size: int # chunk edge length (>= 0) + extent: int # array dimension length + + def __post_init__(self) -> None: + # validates size >= 0 and extent >= 0 + + @property + def nchunks(self) -> int: + if self.size == 0: + return 0 + return ceildiv(self.extent, self.size) + + def index_to_chunk(self, idx: int) -> int: + return idx // self.size # raises IndexError if OOB + def chunk_offset(self, chunk_ix: int) -> int: + return chunk_ix * self.size # raises IndexError if OOB + def chunk_size(self, chunk_ix: int) -> int: + return self.size # always uniform; raises IndexError if OOB + def data_size(self, chunk_ix: int) -> int: + return max(0, min(self.size, self.extent - chunk_ix * self.size)) # raises IndexError if OOB + @property + def unique_edge_lengths(self) -> Iterable[int]: + return (self.size,) # O(1) + def indices_to_chunks(self, indices: NDArray) -> NDArray: + return indices // self.size + def with_extent(self, new_extent: int) -> FixedDimension: + return FixedDimension(size=self.size, extent=new_extent) + def resize(self, new_extent: int) -> FixedDimension: + return FixedDimension(size=self.size, extent=new_extent) + +@dataclass(frozen=True) +class VaryingDimension: + """Explicit per-chunk sizes. The last chunk may extend past the array + extent (extent < sum(edges)), in which case data_size clips to the + valid region while chunk_size returns the full edge length for codec + processing. This underflow is allowed to match how regular grids + handle boundary chunks, and to support shrinking an array without + rewriting chunk edges (the spec allows trailing edges beyond the extent).""" + edges: tuple[int, ...] # per-chunk edge lengths (all > 0) + cumulative: tuple[int, ...] # prefix sums for O(log n) lookup + extent: int # array dimension length (may be < sum(edges)) + + def __init__(self, edges: Sequence[int], extent: int) -> None: + # validates edges non-empty, all > 0, extent >= 0, extent <= sum(edges) + # computes cumulative via itertools.accumulate + # uses object.__setattr__ for frozen dataclass + + @property + def nchunks(self) -> int: + # number of chunks that overlap [0, extent) + if extent == 0: + return 0 + return bisect.bisect_left(self.cumulative, extent) + 1 + + @property + def ngridcells(self) -> int: + return len(self.edges) + + def index_to_chunk(self, idx: int) -> int: + return bisect.bisect_right(self.cumulative, idx) # raises IndexError if OOB + def chunk_offset(self, chunk_ix: int) -> int: + return self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 # raises IndexError if OOB + def chunk_size(self, chunk_ix: int) -> int: + return self.edges[chunk_ix] # raises IndexError if OOB + def data_size(self, chunk_ix: int) -> int: + offset = self.chunk_offset(chunk_ix) + return max(0, min(self.edges[chunk_ix], self.extent - offset)) # raises IndexError if OOB + @property + def unique_edge_lengths(self) -> Iterable[int]: + # lazy generator: yields unseen values, short-circuits deduplication + def indices_to_chunks(self, indices: NDArray) -> NDArray: + return np.searchsorted(self.cumulative, indices, side='right') + def with_extent(self, new_extent: int) -> VaryingDimension: + # validates cumulative[-1] >= new_extent (O(1)), re-binds extent + return VaryingDimension(self.edges, extent=new_extent) + def resize(self, new_extent: int) -> VaryingDimension: + # grow past edge sum: append chunk of size (new_extent - sum(edges)) + # shrink or grow within edge sum: preserve all edges, re-bind extent +``` + +Both types implement the `DimensionGrid` protocol: `nchunks`, `extent`, `index_to_chunk`, `chunk_offset`, `chunk_size`, `data_size`, `indices_to_chunks`, `unique_edge_lengths`, `with_extent`, `resize`. Memory usage scales with the number of *varying* dimensions, not total chunks. + +All per-chunk methods (`chunk_offset`, `chunk_size`, `data_size`) raise `IndexError` for out-of-bounds chunk indices, providing consistent fail-fast behavior across both dimension types. + +The two size methods serve different consumers: + +| Method | Returns | Consumer | +|---|---|---| +| `chunk_size` | Buffer size for codec processing | Codec pipeline (`ArraySpec.shape`) | +| `data_size` | Valid data region within the buffer | Indexing pipeline (`chunk_selection` slicing) | + +For `FixedDimension`, these differ only at the boundary. For `VaryingDimension`, these differ only when the last chunk extends past the extent (i.e., `extent < sum(edges)`). This matches current zarr-python behavior: `get_chunk_spec` passes the full `chunk_shape` to the codec for all chunks, and the indexer generates a `chunk_selection` that clips the decoded buffer. + +### DimensionGrid Protocol + +```python +@runtime_checkable +class DimensionGrid(Protocol): + """Structural interface shared by FixedDimension and VaryingDimension.""" + + @property + def nchunks(self) -> int: ... + @property + def ngridcells(self) -> int: ... + @property + def extent(self) -> int: ... + def index_to_chunk(self, idx: int) -> int: ... + def chunk_offset(self, chunk_ix: int) -> int: ... # raises IndexError if OOB + def chunk_size(self, chunk_ix: int) -> int: ... # raises IndexError if OOB + def data_size(self, chunk_ix: int) -> int: ... # raises IndexError if OOB + def indices_to_chunks(self, indices: NDArray[np.intp]) -> NDArray[np.intp]: ... + @property + def unique_edge_lengths(self) -> Iterable[int]: ... + def with_extent(self, new_extent: int) -> DimensionGrid: ... + def resize(self, new_extent: int) -> DimensionGrid: ... +``` + +The protocol is `@runtime_checkable`, enabling polymorphic handling of both dimension types without `isinstance` checks. + +`nchunks` and `ngridcells` differ when `extent < sum(edges)`: `nchunks` counts only chunks that overlap `[0, extent)`, while `ngridcells` counts total defined grid cells (i.e., `len(edges)`). For `FixedDimension`, both are equal. For `VaryingDimension`, they differ after a resize that shrinks the extent below the edge sum. + +### ChunkSpec + +```python +@dataclass(frozen=True) +class ChunkSpec: + slices: tuple[slice, ...] # valid data region in array coordinates + codec_shape: tuple[int, ...] # buffer shape for codec processing + + @property + def shape(self) -> tuple[int, ...]: + return tuple(s.stop - s.start for s in self.slices) + + @property + def is_boundary(self) -> bool: + return self.shape != self.codec_shape +``` + +For interior chunks, `shape == codec_shape`. For boundary chunks of a regular grid, `codec_shape` is the full declared chunk size while `shape` is clipped. For rectilinear grids, `shape == codec_shape` unless the last chunk extends past the extent. + +### API + +```python +# Creating arrays +arr = zarr.create_array(shape=(100, 200), chunks=(10, 20)) # regular +arr = zarr.create_array(shape=(60, 100), chunks=[[10, 20, 30], [25, 25, 25, 25]]) # rectilinear + +# ChunkGrid as a collection +grid = arr._chunk_grid # ChunkGrid (bound to array shape) +grid.grid_shape # (10, 10) — number of chunks per dimension +grid.ndim # 2 +grid.is_regular # True if all dimensions are Fixed + +spec = grid[0, 1] # ChunkSpec for chunk at grid position (0, 1) +spec.slices # (slice(0, 10), slice(20, 40)) +spec.shape # (10, 20) — data shape +spec.codec_shape # (10, 20) — same for interior chunks + +boundary = grid[9, 0] # boundary chunk (extent=100, size=10) +boundary.shape # (10, 20) — data shape +boundary.codec_shape # (10, 20) — codec sees full buffer + +grid[99, 99] # None — out of bounds + +for spec in grid: # iterate all chunks + ... + +# .chunks property: retained for regular grids, raises NotImplementedError for rectilinear +arr.chunks # (10, 20) + +# .read_chunk_sizes / .write_chunk_sizes: works for all grids (dask-style) +arr.write_chunk_sizes # ((10, 10, ..., 10), (20, 20, ..., 20)) +``` + +`ChunkGrid.__getitem__` constructs `ChunkSpec` using `chunk_size` for `codec_shape` and `data_size` for `slices`: + +```python +def __getitem__(self, coords: int | tuple[int, ...]) -> ChunkSpec | None: + if isinstance(coords, int): + coords = (coords,) + slices = [] + codec_shape = [] + for dim, ix in zip(self.dimensions, coords): + if ix < 0 or ix >= dim.nchunks: + return None + offset = dim.chunk_offset(ix) + slices.append(slice(offset, offset + dim.data_size(ix))) + codec_shape.append(dim.chunk_size(ix)) + return ChunkSpec(tuple(slices), tuple(codec_shape)) +``` + +#### Construction + +`from_sizes` requires `array_shape`, binding the extent per dimension at construction time. This is a core design choice: a chunk grid is a concrete arrangement for a specific array, not an abstract tiling pattern. + +```python +# Regular grid — all FixedDimension +grid = ChunkGrid.from_sizes(array_shape=(100, 200), chunk_sizes=(10, 20)) + +# Rectilinear grid — extent = sum(edges) when shape matches +grid = ChunkGrid.from_sizes(array_shape=(60, 100), chunk_sizes=[[10, 20, 30], [25, 25, 25, 25]]) + +# Rectilinear grid with boundary clipping — last chunk extends past array extent +# e.g., shape=(55, 90) but edges sum to (60, 100): data_size clips at extent +grid = ChunkGrid.from_sizes(array_shape=(55, 90), chunk_sizes=[[10, 20, 30], [25, 25, 25, 25]]) + +# Direct construction +grid = ChunkGrid(dimensions=(FixedDimension(10, 100), VaryingDimension([10, 20, 30], 55))) +``` + +When `extent < sum(edges)`, the dimension is always stored as `VaryingDimension` (even if all edges are identical) to preserve the explicit edge count. The last chunk's `chunk_size` returns the full declared edge (codec buffer) while `data_size` clips to the extent. This mirrors how `FixedDimension` handles boundary chunks in regular grids. + +#### Serialization + +```python +# Regular grid: +{"name": "regular", "configuration": {"chunk_shape": [10, 20]}} + +# Rectilinear grid (with RLE compression and "kind" field): +{ + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20, 30], [[25, 4]]]}, +} +``` + +Both names deserialize to the same `ChunkGrid` class. The serialized form does not include the array extent — that comes from `shape` in array metadata and is combined with the chunk grid when constructing a `ChunkGrid` via `ChunkGrid.from_metadata()`. + +**The `ChunkGrid` does not serialize itself.** The format choice (`"regular"` vs `"rectilinear"`) belongs to `ArrayV3Metadata`. Serialization and deserialization are handled by the metadata-layer chunk grid classes (`RegularChunkGridMetadata` and `RectilinearChunkGridMetadata` in `metadata/v3.py`), which provide `to_dict()` and `from_dict()` methods. + +For `create_array`, the format is inferred from the `chunks` argument: a flat tuple produces `"regular"`, a nested list produces `"rectilinear"`. The `_is_rectilinear_chunks()` helper detects nested sequences like `[[10, 20], [5, 5]]`. + +##### Rectilinear spec compliance + +The rectilinear format requires `"kind": "inline"` (validated by `validate_rectilinear_kind()`). Per the spec, each element of `chunk_shapes` can be: + +- A bare integer `m`: repeated until `sum >= array_extent` +- A list of bare integers: explicit per-chunk sizes +- A mixed array of bare integers and `[value, count]` RLE pairs + +RLE compression is used when serializing: runs of identical sizes become `[value, count]` pairs, singletons stay as bare integers. + +```python +# compress_rle([10, 10, 10, 5]) -> [[10, 3], 5] +# expand_rle([[10, 3], 5]) -> [10, 10, 10, 5] +``` + +For a single-element `chunk_shapes` tuple like `(10,)`, `RectilinearChunkGridMetadata.to_dict()` serializes it as a bare integer `10`. Per the rectilinear spec, a bare integer is repeated until the sum >= extent, preserving the full codec buffer size for boundary chunks. + +**Zero-extent handling:** Regular grids serialize zero-extent dimensions without issue (the format encodes only `chunk_shape`, no edges). Rectilinear grids cannot represent zero-extent dimensions because the spec requires at least one positive-integer edge length per axis. + +#### read_chunk_sizes / write_chunk_sizes + +The `read_chunk_sizes` and `write_chunk_sizes` properties provide universal access to per-dimension chunk data sizes, matching the dask `Array.chunks` convention. They work for both regular and rectilinear grids: + +- `write_chunk_sizes`: always returns outer (storage) chunk sizes +- `read_chunk_sizes`: returns inner chunk sizes when sharding is used, otherwise same as `write_chunk_sizes` + +```python +>>> arr = zarr.create_array(store, shape=(100, 80), chunks=(30, 40)) +>>> arr.write_chunk_sizes +((30, 30, 30, 10), (40, 40)) + +>>> arr = zarr.create_array(store, shape=(60, 100), chunks=[[10, 20, 30], [50, 50]]) +>>> arr.write_chunk_sizes +((10, 20, 30), (50, 50)) +``` + +The underlying `ChunkGrid.chunk_sizes` property (on the grid, not the array) returns the same as `write_chunk_sizes`. + +#### Resize + +```python +arr.resize((80, 100)) # re-binds extent; FixedDimension stays fixed +arr.resize((200, 100)) # VaryingDimension grows by appending a new chunk +arr.resize((30, 100)) # VaryingDimension shrinks: preserves all edges, re-binds extent +``` + +Resize uses `ChunkGrid.update_shape(new_shape)`, which delegates to each dimension's `.resize()` method: +- `FixedDimension.resize()`: simply re-binds the extent (identical to `with_extent`) +- `VaryingDimension.resize()`: grow past `sum(edges)` appends a chunk covering the gap; shrink or grow within `sum(edges)` preserves all edges and re-binds the extent (the spec allows trailing edges beyond the array extent) + +**Known limitation (deferred):** When growing a `VaryingDimension`, the current implementation always appends a single chunk covering the new region. For example, `[10, 10, 10]` resized from 30 to 45 produces `[10, 10, 10, 15]` instead of the more natural `[10, 10, 10, 10, 10]`. A future improvement should add an optional `chunks` parameter to `resize()` that controls how the new region is partitioned, with a sane default (e.g., repeating the last chunk size). This is safely deferrable because: +- `FixedDimension` already handles resize correctly (regular grids stay regular) +- The single-chunk default produces valid state, just suboptimal chunk layout +- Rectilinear arrays are behind an experimental feature flag +- Adding an optional parameter is backwards-compatible + +Open design questions for the `chunks` parameter: +- Does it describe the new region only, or the entire post-resize array? +- Must the overlapping portion agree with existing chunks (no rechunking)? +- What is the type? Same as `chunks` in `create_array`? + +#### from_array + +The `from_array()` function handles both regular and rectilinear source arrays: + +```python +src = zarr.create_array(store, shape=(60, 100), chunks=[[10, 20, 30], [50, 50]]) +new = zarr.from_array(data=src, store=new_store, chunks="keep") +# Preserves rectilinear structure: new.write_chunk_sizes == ((10, 20, 30), (50, 50)) +``` + +When `chunks="keep"`, the logic checks `data._chunk_grid.is_regular`: +- Regular: extracts `data.chunks` (flat tuple) and preserves shards +- Rectilinear: extracts `data.write_chunk_sizes` (nested tuples) and forces shards to None + +### Indexing + +The indexing pipeline is coupled to regular grid assumptions — every per-dimension indexer takes a scalar `dim_chunk_len: int` and uses `//` and `*`: + +```python +dim_chunk_ix = self.dim_sel // self.dim_chunk_len # IntDimIndexer +dim_offset = dim_chunk_ix * self.dim_chunk_len # SliceDimIndexer +``` + +Replace `dim_chunk_len: int` with the dimension object (`FixedDimension | VaryingDimension`). The shared interface means the indexer code structure stays the same — `dim_sel // dim_chunk_len` becomes `dim_grid.index_to_chunk(dim_sel)`. O(1) for regular, binary search for varying. + +### Codec pipeline + +Today, `get_chunk_spec()` returns the same `ArraySpec(shape=chunk_grid.chunk_shape)` for every chunk. For rectilinear grids, each chunk has a different codec shape: + +```python +def get_chunk_spec(self, chunk_coords, array_config, prototype) -> ArraySpec: + spec = self._chunk_grid[chunk_coords] + return ArraySpec(shape=spec.codec_shape, ...) +``` + +Note `spec.codec_shape`, not `spec.shape`. For regular grids, `codec_shape` is uniform (preserving current behavior). The boundary clipping flow is unchanged: + +``` +Write: user data → pad to codec_shape with fill_value → encode → store +Read: store → decode to codec_shape → slice via chunk_selection → user data +``` + +### Sharding + +The `ShardingCodec` constructs a `ChunkGrid` per shard using the shard shape as extent and the subchunk shape as `FixedDimension`. Each shard is self-contained — it doesn't need to know whether the outer grid is regular or rectilinear. Validation checks that every unique edge length per dimension is divisible by the inner chunk size, using `dim.unique_edge_lengths` for efficient polymorphic iteration (O(1) for fixed dimensions, lazy-deduplicated for varying). + +``` +Level 1 — Outer chunk grid (shard boundaries): regular or rectilinear +Level 2 — Inner subchunk grid (within each shard): always regular +Level 3 — Shard index: ceil(shard_dim / subchunk_dim) entries per dimension +``` + +[zarr-specs#370](https://github.com/zarr-developers/zarr-specs/pull/370) lifts the requirement that subchunk shapes evenly divide the shard shape. With the proposed `ChunkGrid`, this just means removing the `shard_shape % subchunk_shape == 0` validation — `FixedDimension` already handles boundary clipping via `data_size`. + +| Outer grid | Subchunk divisibility | Required change | +|---|---|---| +| Regular | Evenly divides (v1.0) | None | +| Regular | Non-divisible (v1.1) | Remove divisibility validation | +| Rectilinear | Evenly divides | Remove "sharding incompatible" guard | +| Rectilinear | Non-divisible | Both changes | + +### What this replaces + +| Current | Proposed | +|---|---| +| `ChunkGrid` ABC + `RegularChunkGrid` subclass | Single concrete `ChunkGrid` with `is_regular` | +| `RectilinearChunkGrid` (#3534) | Same `ChunkGrid` class | +| Chunk grid registry + entrypoints (#3735) | Direct name dispatch | +| `arr.chunks` | Retained for regular; `arr.read_chunk_sizes`/`arr.write_chunk_sizes` for general use | +| `get_chunk_shape(shape, coord)` | `grid[coord].codec_shape` or `grid[coord].shape` | + +## Design decisions + +### Why store the extent in ChunkGrid? + +The chunk grid is a concrete arrangement, not an abstract tiling pattern. A finite collection naturally has an extent. Storing it enables `__getitem__`, eliminates `dim_len` parameters from every method, and makes the grid self-describing. + +This does *not* mean `ArrayV3Metadata.shape` should delegate to the grid. The array shape remains an independent field in metadata. The extent is passed into the grid at construction time so it can answer boundary questions without external parameters. It is **not** serialized as part of the chunk grid JSON — it comes from the `shape` field in array metadata and is combined with the chunk grid configuration in `ChunkGrid.from_metadata()`. + +### Why distinguish chunk_size from data_size? + +A chunk in a regular grid has two sizes. `chunk_size` is the buffer size the codec processes — always `size` for `FixedDimension`, even at the boundary (padded with `fill_value`). `data_size` is the valid data region — clipped to `extent % size` at the boundary. The indexing layer uses `data_size` to generate `chunk_selection` slices. + +This matches current zarr-python behavior and matters for: +1. **Backward compatibility.** Existing stores have boundary chunks encoded at full `chunk_shape`. +2. **Codec simplicity.** Codecs assume uniform input shapes for regular grids. +3. **Shard index correctness.** The index assumes `subchunk_dim`-sized entries. + +For `VaryingDimension`, `chunk_size == data_size` when `extent == sum(edges)`. When `extent < sum(edges)` (e.g., after a resize that keeps the last chunk oversized), `data_size` clips the last chunk. This is the fundamental difference: `FixedDimension` has a declared size plus an extent that clips data; `VaryingDimension` has explicit sizes that normally *are* the extent but can also extend past it. + +### Why not a chunk grid registry? + +There is no known chunk grid outside the rectilinear family that retains the tessellation properties zarr-python assumes. A `match` on the grid name is sufficient. + +### Why a single ChunkGrid class instead of RegularChunkGrid + RectilinearChunkGrid? + +[Discussed in #3534.](https://github.com/zarr-developers/zarr-python/pull/3534) @d-v-b argued that `RegularChunkGrid` is unnecessary since rectilinear is more general; @dcherian argued that downstream libraries need a fast way to detect regular grids without inspecting potentially millions of chunk edges (see [xarray#9808](https://github.com/pydata/xarray/pull/9808)). + +The resolution: a single `ChunkGrid` class with an `is_regular` property (O(1), cached at construction). This gives downstream code the fast-path detection @dcherian needed without the class hierarchy complexity @d-v-b wanted to avoid. The metadata document's `name` field (`"regular"` vs `"rectilinear"`) is also available for clients who inspect JSON directly. + +A backwards-compatibility shim in `chunk_grids.py` preserves the old `RegularChunkGrid` / `RectilinearChunkGrid` import paths with deprecation warnings — see [Backwards compatibility](#backwards-compatibility). + +### Why is ChunkGrid a concrete class instead of a Protocol/ABC? + +The old design had `ChunkGrid` as an ABC with `RegularChunkGrid` as its only subclass. #3534 added `RectilinearChunkGrid` as a second subclass. This branch makes `ChunkGrid` a single concrete class instead, with separate metadata DTOs (`RegularChunkGridMetadata` and `RectilinearChunkGridMetadata` in `metadata/v3.py`) for serialization. + +All known grids are special cases of rectilinear, so there's no need for a class hierarchy at the grid level. A `ChunkGrid` Protocol/ABC would mean every caller programs against an abstract interface and adding a grid type requires implementing ~15 methods. A single class is simpler. + +Note: the *dimension* types (`FixedDimension`, `VaryingDimension`) do use a `DimensionGrid` Protocol — that's where the polymorphism lives. The grid-level class is concrete; the dimension-level types are polymorphic. If a genuinely novel grid type emerges that can't be expressed as a combination of per-dimension types, a grid-level Protocol can be extracted. + +### Why `.chunks` raises for rectilinear grids + +[Debated in #3534.](https://github.com/zarr-developers/zarr-python/pull/3534) @d-v-b suggested making `.chunks` return `tuple[tuple[int, ...], ...]` (dask-style) for all grids. @dcherian strongly objected: every downstream consumer expects `tuple[int, ...]`, and silently returning a different type would be worse than raising. Materializing O(10M) chunk edges into a Python tuple is also a real performance risk ([xarray#8902](https://github.com/pydata/xarray/issues/8902#issuecomment-2546127373)). + +The resolution: +- `.chunks` is retained for regular grids (returns `tuple[int, ...]` as before) +- `.chunks` raises `NotImplementedError` for rectilinear grids with a message pointing to `.read_chunk_sizes`/`.write_chunk_sizes` +- `.read_chunk_sizes` and `.write_chunk_sizes` return `tuple[tuple[int, ...], ...]` (dask convention) for all grids + +@maxrjones noted in review that deprecating `.chunks` for regular grids was not desirable. The current branch does not deprecate it. + +### User control over grid serialization format + +@d-v-b raised in #3534 that users need a way to say "these chunks are regular, but serialize as rectilinear" (e.g., to allow future append/extend workflows without format changes). @jhamman initially made nested-list input always produce `RectilinearChunkGridMetadata`. + +The current branch resolves this via the metadata-layer chunk grid classes. When metadata is deserialized, the original name (from `{"name": "regular"}` or `{"name": "rectilinear"}`) determines which metadata class is instantiated (`RegularChunkGridMetadata` or `RectilinearChunkGridMetadata`), and that class handles serialization via `to_dict()`. Current inference behavior for `create_array`: +- `chunks=(10, 20)` (flat tuple) → infers `"regular"` +- `chunks=[[10, 20], [5, 5]]` (nested lists with varying sizes) → infers `"rectilinear"` +- `chunks=[[10, 10], [20, 20]]` (nested lists with uniform sizes) → `from_sizes` collapses to `FixedDimension`, so `is_regular=True` and infers `"regular"` + +**Open question:** Should uniform nested lists preserve `"rectilinear"` to support future append workflows without a format change? This could be addressed by checking the input form before collapsing, or by allowing users to pass `chunk_grid_name` explicitly through the `create_array` API. + +### Deferred: Tiled/periodic chunk patterns + +[#3750 discussion](https://github.com/zarr-developers/zarr-python/issues/3750) identified periodic chunk patterns as a use case not efficiently served by RLE alone. RLE compresses runs of identical values (`np.repeat`), but periodic patterns like days-per-month (`[31, 28, 31, 30, ...]` repeated 30 years) need a tile encoding (`np.tile`). Real-world examples include: + +- **Oceanographic models** (ROMS): HPC boundary-padded chunks like `[10, 8, 8, 8, 10]` — handled by RLE +- **Temporal axes**: days-per-month, hours-per-day — need tile encoding for compact metadata +- **Temporal-aware grids**: date/time-aware chunk grids that layer over other axes (raised by @LDeakin) + +A `TiledDimension` prototype was built ([commit 9c0f582](https://github.com/maxrjones/zarr-python/commit/9c0f582f)) demonstrating that the per-dimension design supports this without changes to indexing or the codec pipeline. However, it was intentionally excluded from this release because: + +1. **Metadata format must come first.** Tile encoding requires a new `kind` value in the rectilinear spec (currently only `"inline"` is defined). This should go through [zarr-extensions#25](https://github.com/zarr-developers/zarr-extensions/pull/25), not zarr-python unilaterally. +2. **The per-dimension architecture doesn't preclude it.** A future `TiledDimension` can implement the `DimensionGrid` protocol alongside `FixedDimension` and `VaryingDimension` with no changes to indexing, codecs, or the `ChunkGrid` class. +3. **RLE covers the MVP.** Most real-world variable chunk patterns (HPC boundaries, irregular partitions) are efficiently encoded with RLE. Tile encoding is an optimization for a specific (temporal) subset. + +### Metadata / Array separation (partially implemented) + +An earlier design doc proposed decoupling `ChunkGrid` (runtime) from `ArrayV3Metadata` (serialization), so that metadata would store only a plain dict and the array layer would construct the `ChunkGrid`. + +The current implementation partially realizes this separation: + +- **Metadata DTOs** (`RegularChunkGridMetadata`, `RectilinearChunkGridMetadata` in `metadata/v3.py`): Pure data, frozen dataclasses, no array shape. These live on `ArrayV3Metadata.chunk_grid` and represent only what goes into `zarr.json`. +- **`ChunkGrid`** (`chunk_grids.py`): Shape-bound, supports indexing, iteration, and chunk specs. Lives on `AsyncArray._chunk_grid`, constructed from metadata + `shape` via `ChunkGrid.from_metadata()`. + +This means `ArrayV3Metadata.chunk_grid` is now a `ChunkGridMetadata` (the DTO union type), **not** the runtime `ChunkGrid`. Code that previously accessed runtime methods on `metadata.chunk_grid` (e.g., `all_chunk_coords()`, `__getitem__`) must now use the grid from the array layer instead. + +The name controls serialization format; each metadata DTO class provides its own `to_dict()` method for serialization. The `ChunkGrid` handles all runtime queries. + +## Prior art + +**zarrs (Rust):** Three independent grid types behind a `ChunkGridTraits` trait. Key patterns adopted: Fixed vs Varying per dimension, prefix sums + binary search, `Option` for out-of-bounds, `NonZeroU64` for chunk dimensions, separate subchunk grid per shard, array shape at construction. + +**TensorStore (C++):** Stores only `chunk_shape` — boundary clipping via `valid_data_bounds` at query time. Both `RegularGridRef` and `IrregularGrid` internally. No registry. + +## Migration + +### Public API compatibility + +The user-facing API is fully backward-compatible. Existing code that creates, opens, reads, and writes zarr arrays continues to work without changes: + +- `zarr.create_array`, `zarr.open`, `zarr.open_array`, `zarr.open_group` -- unchanged signatures. The `chunks` parameter type is *widened* (now also accepts nested sequences for rectilinear grids), but all existing call patterns still work. +- `arr.chunks` -- returns `tuple[int, ...]` for regular arrays, same as before. +- `arr.shape`, `arr.dtype`, `arr.ndim`, `arr.shards` -- unchanged. +- Top-level `zarr` exports -- unchanged. +- Rectilinear chunks are gated behind `zarr.config.set({'array.rectilinear_chunks': True})`, so they cannot be created accidentally. + +New additions (purely additive): `arr.read_chunk_sizes`, `arr.write_chunk_sizes`, `zarr.experimental.ChunkGrid`, `zarr.experimental.ChunkSpec`. + +The breaking changes discussed below are confined to **internal modules** (`zarr.core.chunk_grids`, `zarr.core.metadata.v3`, `zarr.core.indexing`) that downstream libraries like cubed and VirtualiZarr access directly. + +### Internal API compatibility trade-off analysis + +This section analyzes the internal breaking changes from the metadata/array separation and evaluates two strategies: (A) add backward-compatibility shims in zarr-python, vs. (B) require downstream packages to update. The baseline is **no shims at all**. + +#### What breaks without any shims + +Three API changes affect downstream code: + +1. **`RegularChunkGrid` class removed from `zarr.core.chunk_grids`.** On `main`, `RegularChunkGrid` is defined in `chunk_grids.py` as a `Metadata` subclass. This branch replaces it with `RegularChunkGridMetadata` in `metadata/v3.py`. Without a shim, `from zarr.core.chunk_grids import RegularChunkGrid` raises `ImportError`. + +2. **`RegularChunkGrid` no longer available from `zarr.core.metadata.v3`.** On `main`, `v3.py` imports `RegularChunkGrid` from `chunk_grids.py` for internal use. VirtualiZarr imports it from this location (`from zarr.core.metadata.v3 import RegularChunkGrid`). Without the internal import, this raises `ImportError`. + +3. **`OrthogonalIndexer` constructor expects `ChunkGrid`, not `RegularChunkGrid`/`RegularChunkGridMetadata`.** Even if the import shims above resolve to `RegularChunkGridMetadata`, the indexer constructors access `chunk_grid._dimensions`, which only exists on the runtime `ChunkGrid` class. Cubed constructs `OrthogonalIndexer(selection, shape, RegularChunkGrid(chunk_shape=chunks))` directly. + +#### Downstream impact without shims + +**VirtualiZarr** (5 line changes across 2 files): + +```python +# manifests/array.py (line 6): import +- from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGrid ++ from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGridMetadata + +# manifests/array.py (line 53): isinstance check +- if not isinstance(_metadata.chunk_grid, RegularChunkGrid): ++ if not isinstance(_metadata.chunk_grid, RegularChunkGridMetadata): + +# parsers/zarr.py (line 16): import +- from zarr.core.chunk_grids import RegularChunkGrid ++ from zarr.core.metadata.v3 import RegularChunkGridMetadata + +# parsers/zarr.py (line 270): isinstance check +- if not isinstance(array_v3_metadata.chunk_grid, RegularChunkGrid): ++ if not isinstance(array_v3_metadata.chunk_grid, RegularChunkGridMetadata): + +# parsers/zarr.py (line 390): cast +- cast(RegularChunkGrid, metadata.chunk_grid).chunk_shape ++ cast(RegularChunkGridMetadata, metadata.chunk_grid).chunk_shape +``` + +The `manifests/array.py` import is from `zarr.core.metadata.v3` (never a documented export; VirtualiZarr relied on a transitive import). The `parsers/zarr.py` import is from `zarr.core.chunk_grids` (the canonical location on `main`). Both are straightforward renames. The `.chunk_shape` attribute is unchanged on the new class. + +If VirtualiZarr needs to support both old and new zarr-python, a version-conditional import adds ~5 more lines. + +**Cubed** (3 line changes in 1 file): + +```python +# core/ops.py (lines 626-631) +def _create_zarr_indexer(selection, shape, chunks): + if zarr.__version__[0] == "3": +- from zarr.core.chunk_grids import RegularChunkGrid ++ from zarr.core.chunk_grids import ChunkGrid + from zarr.core.indexing import OrthogonalIndexer +- return OrthogonalIndexer(selection, shape, RegularChunkGrid(chunk_shape=chunks)) ++ return OrthogonalIndexer(selection, shape, ChunkGrid.from_sizes(shape, chunks)) +``` + +Note that `ChunkGrid` is *not* a renamed class. `RegularChunkGrid(chunk_shape=chunks)` took only chunk sizes; `ChunkGrid.from_sizes(shape, chunks)` also requires the array shape. The `shape` parameter is already available at this call site. + +If cubed needs to support both old and new zarr-python: + +```python +def _create_zarr_indexer(selection, shape, chunks): + if zarr.__version__[0] == "3": + from zarr.core.indexing import OrthogonalIndexer + + try: + from zarr.core.chunk_grids import ChunkGrid + + return OrthogonalIndexer(selection, shape, ChunkGrid.from_sizes(shape, chunks)) + except ImportError: + from zarr.core.chunk_grids import RegularChunkGrid + + return OrthogonalIndexer(selection, shape, RegularChunkGrid(chunk_shape=chunks)) + else: + from zarr.indexing import OrthogonalIndexer + + return OrthogonalIndexer(selection, ZarrArrayIndexingAdaptor(shape, chunks)) +``` + +#### What shims can cover + +**Shim 1: `__getattr__` in `chunk_grids.py`** (~15 lines) + +Maps `RegularChunkGrid` to `RegularChunkGridMetadata` with a deprecation warning. Covers: +- The `from zarr.core.chunk_grids import RegularChunkGrid` import pattern (used by cubed and VirtualiZarr's `parsers/zarr.py`) +- `isinstance(x, RegularChunkGrid)` checks (because the name resolves to the actual class) +- `RegularChunkGrid(chunk_shape=(...))` construction (because `RegularChunkGridMetadata` accepts the same arguments) + +Does **not** cover: passing the result to `OrthogonalIndexer`, because `RegularChunkGridMetadata` lacks `._dimensions`. + +**Shim 2: `__getattr__` in `metadata/v3.py`** (~12 lines) + +Same pattern, covers VirtualiZarr's import from `zarr.core.metadata.v3`. Mirrors Shim 1 for a different import path. + +**Shim 3: Auto-coerce `ChunkGridMetadata` in indexer constructors** (~30 lines) + +A helper function + 1-line insertion in each of `BasicIndexer`, `OrthogonalIndexer`, `CoordinateIndexer`, and `MaskIndexer`: + +```python +def _resolve_chunk_grid(chunk_grid, shape): + """Coerce ChunkGridMetadata to runtime ChunkGrid if needed.""" + from zarr.core.chunk_grids import ChunkGrid as _ChunkGrid + from zarr.core.metadata.v3 import ChunkGridMetadata + + if isinstance(chunk_grid, _ChunkGrid): + return chunk_grid + if isinstance(chunk_grid, ChunkGridMetadata): + warnings.warn( + "Passing ChunkGridMetadata to indexers is deprecated. " + "Use ChunkGrid.from_sizes() instead.", + DeprecationWarning, + stacklevel=2, + ) + if hasattr(chunk_grid, "chunk_shape"): + return _ChunkGrid.from_sizes(shape, tuple(chunk_grid.chunk_shape)) + return _ChunkGrid.from_sizes(shape, chunk_grid.chunk_shapes) + raise TypeError(f"Expected ChunkGrid or ChunkGridMetadata, got {type(chunk_grid)}") +``` + +This covers cubed's `OrthogonalIndexer(selection, shape, RegularChunkGrid(...))` pattern end-to-end (combined with Shim 1). + +#### Comparison + +| | No shims | Shims 1+2 only | Shims 1+2+3 | +|---|---|---|---| +| **zarr-python additions** | 0 lines | ~27 lines | ~57 lines | +| **VirtualiZarr changes** | 5 lines | 0 lines | 0 lines | +| **Cubed changes** | 3 lines | 3 lines | 0 lines | +| **Maintenance burden** | None | Low (deprecation shims are well-understood) | Medium (indexer coercion blurs metadata/runtime boundary) | +| **API clarity** | Clean (metadata DTOs and runtime types are distinct) | Good (old names redirect to new names) | Weaker (indexers implicitly accept two type families) | + +With Shims 1+2 only, VirtualiZarr's `manifests/array.py` import from `zarr.core.metadata.v3` is covered by Shim 2, and the `parsers/zarr.py` import from `zarr.core.chunk_grids` is covered by Shim 1. The `isinstance` checks work because both shims resolve to `RegularChunkGridMetadata`. The `cast` works because `.chunk_shape` is unchanged. So VirtualiZarr needs 0 changes with Shims 1+2. The 3 lines for cubed remain because Shim 1 resolves the import but `OrthogonalIndexer` still needs a runtime `ChunkGrid`. + +### Downstream migration + +Migration from `main` (where only `RegularChunkGrid` and the abstract `ChunkGrid` ABC exist): + +| Old pattern (on `main`) | New pattern | +|---|---| +| `from zarr.core.chunk_grids import RegularChunkGrid` | `from zarr.core.metadata.v3 import RegularChunkGridMetadata` | +| `from zarr.core.chunk_grids import ChunkGrid` (ABC) | `from zarr.core.chunk_grids import ChunkGrid` (concrete class, different API) | +| `isinstance(cg, RegularChunkGrid)` | `isinstance(cg, RegularChunkGridMetadata)` or `grid.is_regular` on the runtime `ChunkGrid` | +| `cg.chunk_shape` on `RegularChunkGrid` | `cg.chunk_shape` on `RegularChunkGridMetadata` (unchanged) | +| `ChunkGrid.from_dict(data)` | `parse_chunk_grid(data)` from `zarr.core.metadata.v3` | +| `chunk_grid.all_chunk_coords(array_shape)` | `chunk_grid.all_chunk_coords()` (shape now stored in grid) | +| `chunk_grid.get_nchunks(array_shape)` | `chunk_grid.get_nchunks()` (shape now stored in grid) | + +During the earlier [#3534](https://github.com/zarr-developers/zarr-python/pull/3534) effort (which used separate `RegularChunkGrid`/`RectilinearChunkGrid` classes), downstream PRs and issues were opened to explore compatibility: + +- xarray ([#10880](https://github.com/pydata/xarray/pull/10880)), VirtualiZarr ([#877](https://github.com/zarr-developers/VirtualiZarr/pull/877)), Icechunk ([#1338](https://github.com/earth-mover/icechunk/issues/1338)), cubed ([#876](https://github.com/cubed-dev/cubed/issues/876)) + +These target #3534's API, not this branch's unified `ChunkGrid` design. New downstream POC branches for this design are linked in [Proofs of concepts](#proofs-of-concepts). + +### Credits + +This implementation builds on prior work: + +- **[#3534](https://github.com/zarr-developers/zarr-python/pull/3534)** (@jhamman) — RLE helpers, validation logic, test cases, and the review discussion that shaped the architecture. +- **[#3737](https://github.com/zarr-developers/zarr-python/pull/3737)** — extent-in-grid idea (adopted per-dimension). +- **[#1483](https://github.com/zarr-developers/zarr-python/pull/1483)** — original variable chunking POC. +- **[#3736](https://github.com/zarr-developers/zarr-python/pull/3736)** — resolved by storing extent per-dimension. + + +## Open questions + +1. **Resize defaults (deferred):** When growing a rectilinear array, should `resize()` accept an optional `chunks` parameter? See the [Resize section](#resize) for details and open design questions. Regular arrays already stay regular on resize. +2. **`ChunkSpec` complexity:** `ChunkSpec` carries both `slices` and `codec_shape`. Should the grid expose separate methods for codec vs data queries instead? +3. **`__getitem__` with slices:** Should `grid[0, :]` or `grid[0:3, :]` return a sub-grid or an iterator of `ChunkSpec`s? +4. **Uniform nested lists:** Should `chunks=[[10, 10], [20, 20]]` serialize as `"rectilinear"` (preserving user intent for future append) or `"regular"` (current behavior, collapses uniform edges)? See [User control over grid serialization format](#user-control-over-grid-serialization-format). +5. **`zarr.open` with rectilinear:** @tomwhite noted in #3534 that `zarr.open(mode="w")` doesn't support rectilinear chunks directly. This could be addressed in a follow-up. + +## Proofs of concepts + +- Zarr-Python: + - branch - https://github.com/maxrjones/zarr-python/tree/poc/unified-chunk-grid + - diff - https://github.com/zarr-developers/zarr-python/compare/main...maxrjones:zarr-python:poc/unified-chunk-grid?expand=1 +- Xarray: + - branch - https://github.com/maxrjones/xarray/tree/poc/unified-zarr-chunk-grid + - diff - https://github.com/pydata/xarray/compare/main...maxrjones:xarray:poc/unified-zarr-chunk-grid?expand=1 +- VirtualiZarr: + - branch - https://github.com/maxrjones/VirtualiZarr/tree/poc/unified-chunk-grid + - diff - https://github.com/zarr-developers/VirtualiZarr/compare/main...maxrjones:VirtualiZarr:poc/unified-chunk-grid?expand=1 +- Virtual TIFF: + - branch - https://github.com/virtual-zarr/virtual-tiff/tree/poc/unified-chunk-grid + - diff - https://github.com/virtual-zarr/virtual-tiff/compare/main...poc/unified-chunk-grid?expand=1 +- Cubed: + - branch - https://github.com/maxrjones/cubed/tree/poc/unified-chunk-grid +- Microbenchmarks: + - https://github.com/maxrjones/zarr-chunk-grid-tests/tree/unified-chunk-grid diff --git a/docs/api/zarr/abc/index.md b/docs/api/zarr/abc/index.md index 7c2fb2ef13..7e15cb2a51 100644 --- a/docs/api/zarr/abc/index.md +++ b/docs/api/zarr/abc/index.md @@ -1,7 +1,13 @@ -## Abstract base classes +--- +title: zarr.abc +--- -- **[buffer](./buffer.md)** - Providing access to underlying memory via [buffers](https://docs.python.org/3/c-api/buffer.html) -- **[codec](./codec.md)** - Expressing [zarr codecs](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-encoding) -- **[metadata](./metadata.md)** - Creating metadata classes compatible with the Zarr API -- **[numcodec](./numcodec.md)** - Protocols and classes for modeling codec interface used by numcodecs -- **[store](./store.md)** - ABC for implementing Zarr stores and managing getting and setting bytes in a store \ No newline at end of file +# zarr.abc + +Abstract base classes for extending Zarr-Python. + +- **[zarr.abc.buffer](./buffer.md)** - Providing access to underlying memory via [buffers](https://docs.python.org/3/c-api/buffer.html) +- **[zarr.abc.codec](./codec.md)** - Expressing [zarr codecs](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-encoding) +- **[zarr.abc.metadata](./metadata.md)** - Creating metadata classes compatible with the Zarr API +- **[zarr.abc.numcodec](./numcodec.md)** - Protocols and classes for modeling codec interface used by numcodecs +- **[zarr.abc.store](./store.md)** - ABC for implementing Zarr stores and managing getting and setting bytes in a store diff --git a/docs/api/zarr/api/index.md b/docs/api/zarr/api/index.md index 75b4fff62b..7fac5e766a 100644 --- a/docs/api/zarr/api/index.md +++ b/docs/api/zarr/api/index.md @@ -1,5 +1,7 @@ --- -title: API +title: zarr.api --- +# zarr.api + Zarr provides both an [async](./asynchronous.md) and a [sync](./synchronous.md) API. See those pages for more details. diff --git a/docs/api/zarr/buffer/index.md b/docs/api/zarr/buffer/index.md index 0b303781e1..ebbb9e1c99 100644 --- a/docs/api/zarr/buffer/index.md +++ b/docs/api/zarr/buffer/index.md @@ -1,3 +1,7 @@ +--- +title: zarr.buffer +--- + Zarr provides buffer classes for both the [cpu](./cpu.md) and [gpu](./gpu.md). Generic buffer functionality is also detailed below. ::: zarr.buffer diff --git a/docs/api/zarr/convenience.md b/docs/api/zarr/convenience.md deleted file mode 100644 index f2614e3724..0000000000 --- a/docs/api/zarr/convenience.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: convenience ---- - -::: zarr.consolidate_metadata -::: zarr.copy -::: zarr.copy_all -::: zarr.copy_store -::: zarr.print_debug_info -::: zarr.tree diff --git a/docs/api/zarr/create.md b/docs/api/zarr/create.md deleted file mode 100644 index 971e9c293c..0000000000 --- a/docs/api/zarr/create.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: create ---- - -::: zarr.array -::: zarr.create -::: zarr.create_array -::: zarr.create_group -::: zarr.create_hierarchy -::: zarr.empty -::: zarr.empty_like -::: zarr.full -::: zarr.full_like -::: zarr.from_array -::: zarr.group -::: zarr.ones -::: zarr.ones_like -::: zarr.zeros -::: zarr.zeros_like diff --git a/docs/api/zarr/deprecated/convenience.md b/docs/api/zarr/deprecated/convenience.md deleted file mode 100644 index 91bcb15f71..0000000000 --- a/docs/api/zarr/deprecated/convenience.md +++ /dev/null @@ -1 +0,0 @@ -::: zarr.convenience \ No newline at end of file diff --git a/docs/api/zarr/deprecated/creation.md b/docs/api/zarr/deprecated/creation.md deleted file mode 100644 index 5d18a06a4a..0000000000 --- a/docs/api/zarr/deprecated/creation.md +++ /dev/null @@ -1 +0,0 @@ -::: zarr.creation diff --git a/docs/api/zarr/functions/array.md b/docs/api/zarr/functions/array.md new file mode 100644 index 0000000000..ff7242005c --- /dev/null +++ b/docs/api/zarr/functions/array.md @@ -0,0 +1,5 @@ +--- +title: zarr.array +--- + +::: zarr.array diff --git a/docs/api/zarr/functions/consolidate_metadata.md b/docs/api/zarr/functions/consolidate_metadata.md new file mode 100644 index 0000000000..946531f028 --- /dev/null +++ b/docs/api/zarr/functions/consolidate_metadata.md @@ -0,0 +1,5 @@ +--- +title: zarr.consolidate_metadata +--- + +::: zarr.consolidate_metadata diff --git a/docs/api/zarr/functions/create.md b/docs/api/zarr/functions/create.md new file mode 100644 index 0000000000..b43094eaba --- /dev/null +++ b/docs/api/zarr/functions/create.md @@ -0,0 +1,5 @@ +--- +title: zarr.create +--- + +::: zarr.create diff --git a/docs/api/zarr/functions/create_array.md b/docs/api/zarr/functions/create_array.md new file mode 100644 index 0000000000..a9f4a24bd0 --- /dev/null +++ b/docs/api/zarr/functions/create_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.create_array +--- + +::: zarr.create_array diff --git a/docs/api/zarr/functions/create_group.md b/docs/api/zarr/functions/create_group.md new file mode 100644 index 0000000000..50beb0674c --- /dev/null +++ b/docs/api/zarr/functions/create_group.md @@ -0,0 +1,5 @@ +--- +title: zarr.create_group +--- + +::: zarr.create_group diff --git a/docs/api/zarr/functions/create_hierarchy.md b/docs/api/zarr/functions/create_hierarchy.md new file mode 100644 index 0000000000..38938ffee2 --- /dev/null +++ b/docs/api/zarr/functions/create_hierarchy.md @@ -0,0 +1,5 @@ +--- +title: zarr.create_hierarchy +--- + +::: zarr.create_hierarchy diff --git a/docs/api/zarr/functions/empty.md b/docs/api/zarr/functions/empty.md new file mode 100644 index 0000000000..aff67bb9ed --- /dev/null +++ b/docs/api/zarr/functions/empty.md @@ -0,0 +1,5 @@ +--- +title: zarr.empty +--- + +::: zarr.empty diff --git a/docs/api/zarr/functions/empty_like.md b/docs/api/zarr/functions/empty_like.md new file mode 100644 index 0000000000..9e2fbd26a5 --- /dev/null +++ b/docs/api/zarr/functions/empty_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.empty_like +--- + +::: zarr.empty_like diff --git a/docs/api/zarr/functions/from_array.md b/docs/api/zarr/functions/from_array.md new file mode 100644 index 0000000000..7ab8179b05 --- /dev/null +++ b/docs/api/zarr/functions/from_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.from_array +--- + +::: zarr.from_array diff --git a/docs/api/zarr/functions/full.md b/docs/api/zarr/functions/full.md new file mode 100644 index 0000000000..d6c60de2d5 --- /dev/null +++ b/docs/api/zarr/functions/full.md @@ -0,0 +1,5 @@ +--- +title: zarr.full +--- + +::: zarr.full diff --git a/docs/api/zarr/functions/full_like.md b/docs/api/zarr/functions/full_like.md new file mode 100644 index 0000000000..eb5c162f76 --- /dev/null +++ b/docs/api/zarr/functions/full_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.full_like +--- + +::: zarr.full_like diff --git a/docs/api/zarr/functions/group.md b/docs/api/zarr/functions/group.md new file mode 100644 index 0000000000..3048218f6b --- /dev/null +++ b/docs/api/zarr/functions/group.md @@ -0,0 +1,5 @@ +--- +title: zarr.group +--- + +::: zarr.group diff --git a/docs/api/zarr/load.md b/docs/api/zarr/functions/load.md similarity index 57% rename from docs/api/zarr/load.md rename to docs/api/zarr/functions/load.md index d6463ca976..aa004076ab 100644 --- a/docs/api/zarr/load.md +++ b/docs/api/zarr/functions/load.md @@ -1,5 +1,5 @@ --- -title: load +title: zarr.load --- ::: zarr.load diff --git a/docs/api/zarr/functions/ones.md b/docs/api/zarr/functions/ones.md new file mode 100644 index 0000000000..b7757da1bc --- /dev/null +++ b/docs/api/zarr/functions/ones.md @@ -0,0 +1,5 @@ +--- +title: zarr.ones +--- + +::: zarr.ones diff --git a/docs/api/zarr/functions/ones_like.md b/docs/api/zarr/functions/ones_like.md new file mode 100644 index 0000000000..cffccb10ef --- /dev/null +++ b/docs/api/zarr/functions/ones_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.ones_like +--- + +::: zarr.ones_like diff --git a/docs/api/zarr/functions/open.md b/docs/api/zarr/functions/open.md new file mode 100644 index 0000000000..3d75977395 --- /dev/null +++ b/docs/api/zarr/functions/open.md @@ -0,0 +1,5 @@ +--- +title: zarr.open +--- + +::: zarr.open diff --git a/docs/api/zarr/functions/open_array.md b/docs/api/zarr/functions/open_array.md new file mode 100644 index 0000000000..f40da1bd5d --- /dev/null +++ b/docs/api/zarr/functions/open_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_array +--- + +::: zarr.open_array diff --git a/docs/api/zarr/functions/open_consolidated.md b/docs/api/zarr/functions/open_consolidated.md new file mode 100644 index 0000000000..de71cf7662 --- /dev/null +++ b/docs/api/zarr/functions/open_consolidated.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_consolidated +--- + +::: zarr.open_consolidated diff --git a/docs/api/zarr/functions/open_group.md b/docs/api/zarr/functions/open_group.md new file mode 100644 index 0000000000..4944e94e06 --- /dev/null +++ b/docs/api/zarr/functions/open_group.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_group +--- + +::: zarr.open_group diff --git a/docs/api/zarr/functions/open_like.md b/docs/api/zarr/functions/open_like.md new file mode 100644 index 0000000000..1aea075a81 --- /dev/null +++ b/docs/api/zarr/functions/open_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_like +--- + +::: zarr.open_like diff --git a/docs/api/zarr/functions/print_debug_info.md b/docs/api/zarr/functions/print_debug_info.md new file mode 100644 index 0000000000..c98329f893 --- /dev/null +++ b/docs/api/zarr/functions/print_debug_info.md @@ -0,0 +1,5 @@ +--- +title: zarr.print_debug_info +--- + +::: zarr.print_debug_info diff --git a/docs/api/zarr/functions/save.md b/docs/api/zarr/functions/save.md new file mode 100644 index 0000000000..6c8eae410f --- /dev/null +++ b/docs/api/zarr/functions/save.md @@ -0,0 +1,5 @@ +--- +title: zarr.save +--- + +::: zarr.save diff --git a/docs/api/zarr/functions/save_array.md b/docs/api/zarr/functions/save_array.md new file mode 100644 index 0000000000..58a6d5143d --- /dev/null +++ b/docs/api/zarr/functions/save_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.save_array +--- + +::: zarr.save_array diff --git a/docs/api/zarr/functions/save_group.md b/docs/api/zarr/functions/save_group.md new file mode 100644 index 0000000000..ba66a70563 --- /dev/null +++ b/docs/api/zarr/functions/save_group.md @@ -0,0 +1,5 @@ +--- +title: zarr.save_group +--- + +::: zarr.save_group diff --git a/docs/api/zarr/functions/zeros.md b/docs/api/zarr/functions/zeros.md new file mode 100644 index 0000000000..d43e8d913b --- /dev/null +++ b/docs/api/zarr/functions/zeros.md @@ -0,0 +1,5 @@ +--- +title: zarr.zeros +--- + +::: zarr.zeros diff --git a/docs/api/zarr/functions/zeros_like.md b/docs/api/zarr/functions/zeros_like.md new file mode 100644 index 0000000000..5adf1a23b3 --- /dev/null +++ b/docs/api/zarr/functions/zeros_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.zeros_like +--- + +::: zarr.zeros_like diff --git a/docs/api/zarr/index.md b/docs/api/zarr/index.md index f6ae2bda83..f691c4599a 100644 --- a/docs/api/zarr/index.md +++ b/docs/api/zarr/index.md @@ -14,14 +14,13 @@ Complete reference documentation for the Zarr-Python API. - **[Array](array.md)** - The main Zarr array class for N-dimensional data - **[Group](group.md)** - Hierarchical organization of arrays and subgroups -- **[Create](create.md)** - Functions for creating new arrays and groups -- **[Open](open.md)** - Opening existing Zarr stores and arrays +- **[create_array](functions/create_array.md)** and **[create_group](functions/create_group.md)** - Creating new arrays and groups +- **[open](functions/open.md)**, **[open_array](functions/open_array.md)**, and **[open_group](functions/open_group.md)** - Opening existing Zarr stores, arrays, and groups ### Data Operations -- **[Load](load.md)** - Loading data from Zarr stores -- **[Save](save.md)** - Saving data to Zarr format -- **[Convenience](convenience.md)** - High-level convenience functions +- **[load](functions/load.md)** - Loading data from Zarr stores +- **[save](functions/save.md)** - Saving data to Zarr format ### Data Types and Configuration @@ -55,13 +54,6 @@ The ABC module defines interfaces for extending Zarr: - **[Testing](testing/index.md)** - Utilities for testing Zarr-based code -## Migration and Compatibility - -- **[Deprecated Functions](deprecated/convenience.md)** - Legacy convenience functions -- **[Deprecated Creation](deprecated/creation.md)** - Legacy array creation functions - -These deprecated modules are maintained for backward compatibility but should be avoided in new code. - ## Getting Help - Check the [User Guide](../../user-guide/index.md) for tutorials and examples diff --git a/docs/api/zarr/open.md b/docs/api/zarr/open.md deleted file mode 100644 index c59f896129..0000000000 --- a/docs/api/zarr/open.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: open ---- - -::: zarr.open -::: zarr.open_array -::: zarr.open_consolidated -::: zarr.open_group -::: zarr.open_like diff --git a/docs/api/zarr/save.md b/docs/api/zarr/save.md deleted file mode 100644 index c611d10a4c..0000000000 --- a/docs/api/zarr/save.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: save ---- - -::: zarr.save -::: zarr.save_array -::: zarr.save_group diff --git a/docs/api/zarr/testing/conftest.md b/docs/api/zarr/testing/conftest.md deleted file mode 100644 index 67cecfd9b8..0000000000 --- a/docs/api/zarr/testing/conftest.md +++ /dev/null @@ -1,3 +0,0 @@ -## Conftest - -::: zarr.testing.conftest diff --git a/docs/api/zarr/testing/index.md b/docs/api/zarr/testing/index.md index 4ef56ec69c..2b48ad349f 100644 --- a/docs/api/zarr/testing/index.md +++ b/docs/api/zarr/testing/index.md @@ -1,12 +1,13 @@ --- -title: testing +title: zarr.testing --- +# zarr.testing + See the following sub-modules: -- [buffer](./buffer.md) -- [conftest](./conftest.md) -- [stateful](./stateful.md) -- [store](./store.md) -- [strategies](./strategies.md) -- [utils](./utils.md) +- [zarr.testing.buffer](./buffer.md) +- [zarr.testing.stateful](./stateful.md) +- [zarr.testing.store](./store.md) +- [zarr.testing.strategies](./strategies.md) +- [zarr.testing.utils](./utils.md) diff --git a/docs/blog/.authors.yml b/docs/blog/.authors.yml new file mode 100644 index 0000000000..10ce423cfc --- /dev/null +++ b/docs/blog/.authors.yml @@ -0,0 +1,6 @@ +authors: + d-v-b: + name: Davis Bennett + description: Core developer + avatar: https://github.com/d-v-b.png + url: https://github.com/d-v-b diff --git a/docs/blog/index.md b/docs/blog/index.md new file mode 100644 index 0000000000..fca29e2578 --- /dev/null +++ b/docs/blog/index.md @@ -0,0 +1,3 @@ +# Blog + +News, release highlights, and design notes from the Zarr-Python developers. diff --git a/docs/blog/posts/3.3.0-release.md b/docs/blog/posts/3.3.0-release.md new file mode 100644 index 0000000000..13368848ae --- /dev/null +++ b/docs/blog/posts/3.3.0-release.md @@ -0,0 +1,169 @@ +--- +date: 2026-07-30 +authors: + - d-v-b +categories: + - Release +--- + +# Zarr-Python 3.3.0 + +We're happy to announce the release of version 3.3.0 of Zarr-Python. It's been a while since our last release ([3.2.1](https://github.com/zarr-developers/zarr-python/releases/tag/v3.2.1) dropped in May of this year), +and we're bringing some exciting additions to the latest version. For the full release notes, see the [3.3.0 release notes](../../release-notes.md), otherwise stick around for an overview of two performance-centric highlights of this release. + + + +## Faster low-latency storage + +Relevant issues and pull requests: + +- [#3524](https://github.com/zarr-developers/zarr-python/issues/3524) -- the performance report that started this work +- [#3885](https://github.com/zarr-developers/zarr-python/pull/3885) -- synchronous codec APIs and the `FusedCodecPipeline` + +### The cost of async overhead + +Zarr-Python 3.x uses async routines for fetching data and decoding chunks. In terms of code, this means our store (data fetching) and codec (chunk decoding) APIs are both async. This makes +I/O against high-latency storage backends like cloud object storage efficient. But for *low-latency* storage, like in-process memory or the file system, async routines add measurable overhead and offer no benefit. Async only adds value when there's work to be done while waiting for I/O to complete, but when I/O latency is low, it completes too quickly to run anything while waiting, and we are left paying the performance bill for obligatory async task scheduling that offered no value. + +This performance problem became acute when Zarr-Python users reported that in-memory array indexing workloads ran *slower* in Zarr-Python 3.1.3 relative to Zarr-Python 2.18.7 ([#3524](https://github.com/zarr-developers/zarr-python/issues/3524)). Fortunately this performance regression had a straightforward fix (I don't say "easy" because it was a lot of work). + +### Synchronous execution restores performance + +If async overhead makes low-latency storage slow, does *removing* that overhead restore performance? Yes, it does! + +In [#3885](https://github.com/zarr-developers/zarr-python/pull/3885) we defined synchronous versions of our storage and codec APIs -- the `SyncByteGetter` and `SyncByteSetter` protocols, plus a `get_ranges_sync` method on the `Store` ABC -- and then combined them in a new codec orchestration class called `FusedCodecPipeline`. The `FusedCodecPipeline` is an opt-in alternative to the default (the `BatchedCodecPipeline`) that gives large speedups for low-latency storage. It is currently marked [experimental](../../user-guide/experimental.md), so we may change it as we learn more; the default pipeline is untouched, and existing code keeps working unless you opt in. + +The win here is *not* a faster compressor. It is the removal of async scheduling overhead (including some [nasty `asyncio.to_thread` overhead](https://github.com/python/cpython/issues/136084)), plus a few vectorized fast paths for dense, uncompressed shards. And we only expect this new pipeline to accelerate workloads targeting a subset of storage backends, namely any store with methods that advertise low latency. + +On this author's 10-core Apple M4 laptop, the `FusedCodecPipeline` delivers the following results against memory-backed arrays: + +- uncompressed writes are *~4 times faster* +- uncompressed reads are *~5 times faster* +- compressed writes are *~2 times faster* +- compressed reads are *~2 times faster* + +These numbers came from a [runnable example](../../user-guide/examples/codec_pipeline_performance.md) that ships with the documentation. Run it yourself to get a sense of how the `FusedCodecPipeline` behaves on your system -- when and how you use it depends on your hardware, your array layout, and how your chunks are compressed. What's certain is that for in-memory arrays, and arrays saved to the local file system, the `FusedCodecPipeline` is worth a try. + +Getting good numbers requires choosing the right level of thread-based parallelism for your workload, which is part of the configuration of the `FusedCodecPipeline`. For uncompressed chunks there's no CPU-bound work to do after fetching a chunk and so +thread-based parallelism is worse than useless and slows things down. But for compressed chunks, threading offers a substantial payoff. + +### How to use it + +Select the pipeline through the [runtime configuration](../../user-guide/config.md) by setting `codec_pipeline.path`. Set it globally to affect every array created or opened afterwards: + +```python exec="true" session="blog-330" source="above" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +) +``` + +Or scope it to a block of code by using `zarr.config.set` as a context manager, which is the safer choice if you only want the new pipeline for part of your program: + +```python exec="true" session="blog-330" source="above" result="ansi" +import numpy as np +import zarr +from zarr.storage import MemoryStore + +with zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +): + arr = zarr.create_array( + store=MemoryStore(), + shape=(1000, 1000), + chunks=(100, 100), + shards=(1000, 1000), + dtype="float32", + ) + arr[:] = np.random.random((1000, 1000)).astype("float32") + result = arr[:] + +print(result.shape) +``` + +Thread-based parallelism is configured separately, via `codec_pipeline.max_workers`. It defaults to `None`, meaning a pool sized to `os.cpu_count()`. Note that this setting is read *only* by the `FusedCodecPipeline` -- the default `BatchedCodecPipeline` ignores it, so tuning it without opting in above does nothing. + +As noted, memory-backed and uncompressed workloads often do better with a single worker, which runs everything inline on the calling thread: + +```python exec="true" session="blog-330" source="above" +import zarr + +# No thread pool: run codec compute inline. Often best for uncompressed, +# memory-backed arrays, where there's no CPU-bound work to overlap. +zarr.config.set({"codec_pipeline.max_workers": 1}) + +# A fixed-size thread pool, which pays off once compression is in play. +zarr.config.set({"codec_pipeline.max_workers": 8}) + +# Or back to the default, sized to the number of CPUs. +zarr.config.set({"codec_pipeline.max_workers": None}) +``` + +To return to the default pipeline, set `codec_pipeline.path` back to the batched implementation: + +```python exec="true" session="blog-330" source="above" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"} +) +``` + +## Faster sharded reads + +Relevant issues and pull requests: + +- [#3004](https://github.com/zarr-developers/zarr-python/pull/3004) -- optimize partial shard reads +- [#3925](https://github.com/zarr-developers/zarr-python/pull/3925) -- `Store.get_ranges` for concurrent, coalesced multi-range reads +- [#3987](https://github.com/zarr-developers/zarr-python/pull/3987) -- control coalescing through `ArrayConfig` and the runtime config + +### How sharding works + +Chunks encoded with the `sharding_indexed` codec contain a secondary level of chunking, called subchunks. For example, if the `chunk_grid` field of the array metadata declares an "outer chunk" size of, say `(10, 10)`, a `sharding_indexed` codec in the `codecs` field could declare an "inner chunk" size of `(5, 5)`. Readers accessing such a chunk will observe a stored object (a stream of bytes) that decodes to an array with size `(10, 10)` (the "outer chunk"), which is comprised of four separate, contiguous byte ranges that each decode to a `(5, 5)` inner chunk. Each inner chunk occupies its own byte range in the outer chunk. + +A reader can satisfy a request for all four inner chunks by issuing four separate byte-range requests, or by making a *single* request for a byte range that spans all four inner chunks. The latter option is nice because it cuts down on the number of requests we need. Historically Zarr-Python used this optimization when reading entire outer chunks; in 3.3.0, we use this optimization in more cases, resulting in more efficient I/O patterns for sharded reads. + +### Interval equivalence + +Byte ranges, being intervals, obey some combination rules: the values in two half-open intervals `[a, b), [b, c)` can be captured by the single interval `[a, c)`. That means a reader can get multiple inner chunks with *one* byte-range request by requesting a range of bytes starting with the first byte of the first subchunk and ending with the last byte of the last subchunk. When individual requests are expensive, this kind of optimization is worth a lot. + +The requested inner chunks are not necessarily contiguous -- there might be a byte range gap between them. As long as that gap is not too big, its often efficient to fetch the entire byte range, gap included, and pick out the inner chunk byte ranges after I/O is done. + +### Byte range coalescing + +We call this procedure -- merging adjacent byte ranges -- "byte range coalescing", and it's a new performance optimization shipping in Zarr-Python 3.3.0. Unlike the `FusedCodecPipeline`, this one is on by default with base settings we think are good, so most users won't need to tune anything. + +Two knobs control it, both documented in the [runtime configuration guide](../../user-guide/config.md). Nearby byte ranges in the same shard are merged into a single request when the gap between them is no larger than `array.sharding_coalesce_max_gap_bytes` (default 1 MiB) and the merged read stays within `array.sharding_coalesce_max_bytes` (default 16 MiB). The gap threshold is what trades wasted bytes against saved requests: raising it reads more data you didn't ask for, in exchange for fewer requests. + +For a runnable demonstration -- counting the store requests saved and timing them against a store with simulated latency -- see the [sharded read coalescing example](../../user-guide/examples/sharding_coalescing.md). + +You can set them globally, or per array by passing `config={...}` to [`zarr.create_array`][]: + +```python exec="true" session="blog-330" source="above" result="ansi" +import zarr +from zarr.storage import MemoryStore + +arr = zarr.create_array( + store=MemoryStore(), + shape=(1000, 1000), + chunks=(100, 100), + shards=(1000, 1000), + dtype="float32", + config={ + "sharding_coalesce_max_gap_bytes": 4 * 1024**2, # 4 MiB + "sharding_coalesce_max_bytes": 64 * 1024**2, # 64 MiB + }, +) +print(arr.shape) +``` + +## Tell us what you think + +We hope these new features are helpful, and we would appreciate any feedback that helps us improve them, or any other aspect of Zarr-Python. + +## Going faster + +The updates in this release are just the first step of a larger performance-oriented direction for Zarr-Python. Landing these two enhancements taught us a *lot* about the performance-sensitive areas of the library. We can and will invest more time in performance tuning, e.g. by adding or changing abstractions, writing code for special cases, etc. + +We plan to consider including compiled code that should enable significant performance improvements. The [`zarrs`](https://zarrs.dev/) project is an ecosystem of Zarr tools written in Rust, with [extremely high performance](https://book.zarrs.dev/#-zarrs-is-fast-). Is there a `zarrs` binding in Zarr-Python's future? I hope so! We are keenly observing development of [`zarrista`](https://developmentseed.org/zarrista/latest/) as a proof-of-concept for what a Python-`zarrs` binding layer might look like. Stay tuned! diff --git a/docs/contributing.md b/docs/contributing.md index b2c1ae635c..dea7256c36 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -12,23 +12,23 @@ If you find a bug, please raise a [GitHub issue](https://github.com/zarr-develop 1. A minimal, self-contained snippet of Python code reproducing the problem. You can format the code nicely using markdown, e.g.: -```python -import zarr -g = zarr.group() -# etc. -``` + ```python exec="false" reason="illustrative pseudocode with a '# etc.' placeholder, not runnable" + import zarr + g = zarr.group() + # etc. + ``` -2. An explanation of why the current behaviour is wrong/not desired, and what you expect instead. +2. An explanation of why the current behavior is wrong/not desired, and what you expect instead. -3. Information about the version of Zarr, along with versions of dependencies and the Python interpreter, and installation information. The version of Zarr can be obtained from the `zarr.__version__` property. Please also state how Zarr was installed, e.g., "installed via pip into a virtual environment", or "installed using conda". Information about other packages installed can be obtained by executing `pip freeze` (if using pip to install packages) or `conda env export` (if using conda to install packages) from the operating system command prompt. The version of the Python interpreter can be obtained by running a Python interactive session, e.g.: +3. Information about the version of Zarr, along with versions of dependencies and the Python interpreter, and installation information. The version of Zarr can be obtained from the `zarr.__version__` attribute. Please also state how Zarr was installed, e.g., "installed via pip into a virtual environment", or "installed using conda". Information about other packages installed can be obtained by executing `pip freeze` (if using pip to install packages) or `conda env export` (if using conda to install packages) from the operating system command prompt. The version of the Python interpreter can be obtained by running a Python interactive session, e.g.: -```console -python -``` + ```console + python + ``` -```ansi -Python 3.12.7 | packaged by conda-forge | (main, Oct 4 2024, 15:57:01) [Clang 17.0.6 ] on darwin -``` + ```ansi + Python 3.12.7 | packaged by conda-forge | (main, Oct 4 2024, 15:57:01) [Clang 17.0.6 ] on darwin + ``` ## Enhancement proposals @@ -133,8 +133,6 @@ hatch env run --env test.py3.12-optional run All tests are automatically run via GitHub Actions for every pull request and must pass before code can be accepted. Test coverage is also collected automatically via the Codecov service. -> **Note:** Previous versions of Zarr-Python made extensive use of doctests. These tests were not maintained during the 3.0 refactor but may be brought back in the future. See issue #2614 for more details. - ### Code standards - using prek All code must conform to the PEP8 standard. Regarding line length, lines up to 100 characters are allowed, although please try to keep under 90 wherever possible. @@ -205,7 +203,7 @@ When submitting a pull request, coverage will also be collected across all suppo ### Documentation -Docstrings for user-facing classes and functions should follow the [numpydoc](https://numpydoc.readthedocs.io/en/stable/format.html#docstring-standard) standard, including sections for Parameters and Examples. All examples should run and pass as doctests under Python 3.11. +Docstrings for user-facing classes and functions should follow the [numpydoc](https://numpydoc.readthedocs.io/en/stable/format.html#docstring-standard) standard, including sections for Parameters and Examples. All examples should run and pass as doctests under Python 3.12. Zarr uses mkdocs for documentation, hosted on readthedocs.org. Documentation is written in the Markdown markup language (.md files) in the `docs` folder. The documentation consists both of prose and API documentation. All user-facing classes and functions are included in the API documentation, under the `docs/api` folder using the [mkdocstrings](https://mkdocstrings.github.io/) extension. Add any new public functions or classes to the relevant markdown file in `docs/api/*.md`. Any new features or important usage information should be included in the user-guide (`docs/user-guide`). Any changes should also be included as a new file in the `changes` directory. @@ -215,9 +213,9 @@ The documentation can be built locally by running: hatch --env docs run build ``` -The resulting built documentation will be available in the `docs/_build/html` folder. +The resulting built documentation will be available in the `site` folder. -Hatch can also be used to serve continuously updating version of the documentation during development at [http://0.0.0.0:8000/](http://0.0.0.0:8000/). This can be done by running: +Hatch can also be used to serve continuously updating version of the documentation during development at [http://127.0.0.1:8000/](http://127.0.0.1:8000/). This can be done by running: ```bash hatch --env docs run serve @@ -225,10 +223,10 @@ hatch --env docs run serve #### Adding executable code blocks in the documentation -Zarr uses [Markdown Exec](https://pawamoy.github.io/markdown-exec/usage/) to execute code blocks in Markdown files. Add `exec="on"` to a code block header for it to be executed when the docs are built. For example: +Zarr uses [Markdown Exec](https://pawamoy.github.io/markdown-exec/usage/) to execute code blocks in Markdown files. Add `exec="true"` to a code block header for it to be executed when the docs are built. For example: ````md -```python exec="on" +```python exec="true" print("Hello world") ``` ```` @@ -253,9 +251,72 @@ renders as: print("Hello world") ``` +#### Validating code blocks: `exec` vs `test` + +Every Python code block in the documentation is checked by a test +(`tests/test_docs.py`) so that examples cannot quietly rot — the bug that motivated +this was an example calling `zarr.create_array(..., mode="w")`, an argument that does +not exist, which went unnoticed because nothing ran it. A block declares *how* it is +validated using one of two independent attributes: + + - **`exec="true"`** — Markdown Exec runs the block **at docs-build time to render its + output** into the page. This is the attribute described above; it is also what the + test suite executes. Use it for ordinary examples whose output should appear in the + docs. + - **`test="true"`** — the block is **run by the test suite only**, *not* at build time. + Use this for an example that should be validated but cannot run in the docs-build + environment — for example one that needs a GPU or a cloud backend. Markdown Exec + leaves a `test="true"` block as a static, syntax-highlighted snippet (it never + executes it), while the test suite still runs it (see the marker note below). + +A block may carry both (`exec="true" test="true"`), though in practice `exec="true"` +already implies it is tested, so you rarely need `test="true"` alongside it. + +The two attributes are kept separate on purpose: `exec=` controls *build-time rendering* +and `test=` controls *test-time validation*. Tagging a GPU/cloud example `exec="true"` +would make `mkdocs build` try to run it on a machine without that infrastructure and fail +the build; `test="true"` lets it be validated without being built. + +##### Opting a block out of validation + +A handful of blocks genuinely cannot run and are not executable Python — a REPL +transcript, a deliberately-incorrect "before" snippet, a `--8<--` file include. Mark +these explicitly by opening the fence with +`exec="false" reason="REPL output transcript, not executable source"` (supply a reason +that fits the block). + +`exec="false"` with a non-empty `reason` is an explicit, greppable opt-out. A test +(`test_no_unvalidated_blocks`) requires **every** Python block to be either `exec="true"`, +`test="true"`, or `exec="false"` with a reason — so a block can never silently skip +validation. A bare ` ```python ` fence, or a typo like `exec="on"`, fails that test. + +Markdown Exec only renders `exec="true"` fences; the `mkdocs_hooks.py` hook at the +repository root makes `test="true"` and `exec="false"` fences render as ordinary +highlighted code blocks. Without it, these fences would fail superfences parsing and +their contents would spill into the page as raw markdown. + +##### Marker-bound blocks (GPU, S3) + +A `test="true"` block that needs special infrastructure declares a pytest marker with +`markers="..."`, which binds it to that infrastructure in the test suite: + + - `markers="gpu"` — run only under `pytest -m gpu` (the GPU CI environment); skipped + elsewhere via `importorskip("cupy")`. + - `markers="s3"` — run against a mock S3 (moto) backend supplied by a test fixture, so + the example can use a bare `s3://…` URL with no test-only connection details on show. + +##### Placement of `test="true"` blocks + +Because Markdown Exec does not execute a `test="true"` (or `exec="false"`) block, placing +one *before* an `exec="true"` block on the same page can disrupt the build-time execution +of that later block. Put `test="true"` blocks **after** all `exec="true"` blocks on the +page (or on a page where they are the only Python block). The `test_test_only_blocks_come_last` +test enforces this, and the CI docs build runs with `--strict` so any such breakage fails +the build rather than passing as a warning. + #### Building documentation without executing code blocks -Sometimes, you may want the documentation to build quicker. You can disable code block execution by commenting out the [markdown-exec](https://github.com/zarr-developers/zarr-python/blob/884a8c91afcc3efe28b3da952be3b85125c453cb/mkdocs.yml#L132 plugin in the mkdocs configuration file). This will make code blocks and cross references render incorrectly (i.e., expect build warnings), but also reduces build time by ~3x. Be sure to undo the commenting out before opening your pull request. +Sometimes, you may want the documentation to build quicker. You can disable code block execution by commenting out the [markdown-exec plugin](https://github.com/zarr-developers/zarr-python/blob/884a8c91afcc3efe28b3da952be3b85125c453cb/mkdocs.yml#L132) in the mkdocs configuration file. This will make code blocks and cross references render incorrectly (i.e., expect build warnings), but also reduces build time by ~3x. Be sure to undo the commenting out before opening your pull request. ### Changelog @@ -269,7 +330,11 @@ Alternatively, you can manually create the files in the `changes` directory usin See the [towncrier](https://towncrier.readthedocs.io/en/stable/tutorial.html) docs for more. -## Merging pull requests +## Project governance + +This section documents the processes that core developers follow to maintain the project. The current core developers are listed in [`TEAM.md`](https://github.com/zarr-developers/zarr-python/blob/main/TEAM.md). + +### Merging pull requests Pull requests submitted by an external contributor should be reviewed and approved by at least one core developer before being merged. Ideally, pull requests submitted by a core developer should be reviewed and approved by at least one other core developer before being merged. @@ -277,6 +342,20 @@ Pull requests should not be merged until all CI checks have passed (GitHub Actio Before merging, the milestone must be set to decide whether a PR will be in the next patch, minor, or major release. The next section explains which types of changes go in each release. +### Self-merging pull requests + +The default is that a pull request opened by a core developer is reviewed and approved by at least one other core developer before it is merged. We trust core developers to use their judgment, though, and we would rather bias toward action than make routine changes wait on review they do not really need. + +So a core developer may merge their own pull request whenever they judge the change to be low-risk, provided the standard merge requirements are met — CI is green against code that has had the latest `main` merged in, a changelog fragment has been added, and the milestone is set — and other core developers have had a fair chance to weigh in. As a rule of thumb, leave the pull request open for a few days before self-merging, unless it is genuinely trivial or time-sensitive. If you are confident a change is fine, merge it; if you have real doubts, ask for a review. It is generally advisable to ping another developer in the PR description for awareness about the direction, even if you choose not to request a formal review. + +Some changes warrant more caution, and a second reviewer is usually worth seeking even when you could self-merge: changes to the public API, anything touching data-format or on-disk compatibility, and performance-sensitive code. These are the most expensive to get wrong and the hardest to reverse. Reverts, by contrast, are cheap — if a self-merged change turns out to be a mistake, reverting it is itself a low-risk change that any core developer can make, and the reworked version can go through normal review. When something recently merged is actively causing harm — a broken `main`, a release blocker, or data corruption — fix it fast and request review after the fact rather than waiting. + +This policy exists to lower the cost of routine work and to help newer core developers grow comfortable merging changes. It is not a license to merge past an unresolved objection: if another core developer asks to review a change, give them that chance. + +### Release procedure + +To give the release visibility and a single place to track progress, open an issue on GitHub announcing the release using the [release checklist template](https://github.com/zarr-developers/zarr-python/issues/new?template=release-checklist.md). The release checklist includes all steps necessary for the release. + ## Compatibility and versioning policies ### Versioning @@ -287,17 +366,17 @@ Releases are classified by the library changes contained in that release. This c * **major** releases (for example, `2.18.0` -> `3.0.0`) are for changes that will require extensive adaptation efforts from many users and downstream projects. For example, breaking changes to widely-used user-facing APIs should only be applied in a major release. - Users and downstream projects should carefully consider the impact of a major release before adopting it. In advance of a major release, developers should communicate the scope of the upcoming changes, and help users prepare for them. + Users and downstream projects should carefully consider the impact of a major release before adopting it. In advance of a major release, developers should communicate the scope of the upcoming changes, and help users prepare for them. * **minor** releases (for example, `3.0.0` -> `3.1.0`) are for changes that do not require significant effort from most users or downstream projects to respond to. API changes are possible in minor releases if the burden on users imposed by those changes is sufficiently small. - For example, a recently released API may need fixes or refinements that are breaking, but low impact due to the recency of the feature. Such API changes are permitted in a minor release. + For example, a recently released API may need fixes or refinements that are breaking, but low impact due to the recency of the feature. Such API changes are permitted in a minor release. - Minor releases are safe for most users and downstream projects to adopt. + Minor releases are safe for most users and downstream projects to adopt. -* **patch** releases (for example, `3.1.0` -> `3.1.1`) are for changes that contain no breaking or behaviour changes for downstream projects or users. Examples of changes suitable for a patch release are bugfixes and documentation improvements. +* **patch** releases (for example, `3.1.0` -> `3.1.1`) are for changes that contain no breaking or behavior changes for downstream projects or users. Examples of changes suitable for a patch release are bugfixes and documentation improvements. - Users should always feel safe upgrading to the latest patch release. + Users should always feel safe upgrading to the latest patch release. Note that this versioning scheme is not consistent with [Semantic Versioning](https://semver.org/). Contrary to SemVer, the Zarr library may release breaking changes in `minor` releases, or even `patch` releases under exceptional circumstances. But we should strive to avoid doing so. @@ -309,12 +388,29 @@ Zarr developers should make changes as smooth as possible for users. This means The Zarr library is an implementation of a file format standard defined externally -- see the [Zarr specifications website](https://zarr-specs.readthedocs.io) for the list of Zarr file format specifications. -If an existing Zarr format version changes, or a new version of the Zarr format is released, then the Zarr library will generally require changes. It is very likely that a new Zarr format will require extensive breaking changes to the Zarr library, and so support for a new Zarr format in the Zarr library will almost certainly come in new `major` release. When the Zarr library adds support for a new Zarr format, there may be a period of accelerated changes as developers refine newly added APIs and deprecate old APIs. In such a transitional phase breaking changes may be more frequent than usual. +If an existing Zarr format version changes, or a new version of the Zarr format is released, then the Zarr library will generally require changes. It is very likely that a new Zarr format will require extensive breaking changes to the Zarr library, and so support for a new Zarr format in the Zarr library will almost certainly come in a new `major` release. When the Zarr library adds support for a new Zarr format, there may be a period of accelerated changes as developers refine newly added APIs and deprecate old APIs. In such a transitional phase breaking changes may be more frequent than usual. + +## Experimental API policy + +The `zarr.experimental` namespace contains features that are under active development and may change without notice. When contributing to or depending on experimental features, please keep the following in mind: + +### For contributors + +When adding a new feature to `zarr.experimental`: + +1. Place the feature under `src/zarr/experimental/` and export it from `src/zarr/experimental/__init__.py`. +2. Document the feature in `docs/user-guide/experimental.md` and note clearly that it is experimental. +3. Add a changelog entry categorized as `feature`. + +We aim to either **promote** or **remove** experimental features within **6 months** of their addition. To promote a feature to stable: + +1. Move it from `zarr.experimental` to the appropriate stable module. +2. Keep a deprecated re-export in `zarr.experimental` for one minor release. +3. Update the documentation to reflect the stable location. -## Release procedure +### For users -Open an issue on GitHub announcing the release using the release checklist template: -[https://github.com/zarr-developers/zarr-python/issues/new?template=release-checklist.md](https://github.com/zarr-developers/zarr-python/issues/new?template=release-checklist.md). The release checklist includes all steps necessary for the release. +Features in `zarr.experimental` carry no stability guarantees. They may be changed or removed in any release, including patch releases. If you depend on an experimental feature, pin your `zarr-python` version accordingly. ## Benchmarks @@ -323,4 +419,4 @@ performance benchmarks as part of our test suite. The benchmarks are found in `t By default pytest is configured to run these benchmarks as plain tests (i.e., no benchmarking). To run a benchmark with timing measurements, use the `--benchmark-enable` when invoking `pytest`. -The benchmarks are run as part of the continuous integration suite through [codspeed](https://codspeed.io/zarr-developers/zarr-python). +The benchmarks are run as part of the continuous integration suite through [codspeed](https://app.codspeed.io/zarr-developers/zarr-python). diff --git a/docs/index.md b/docs/index.md index b61646d6a6..eb3b6a5000 100644 --- a/docs/index.md +++ b/docs/index.md @@ -6,7 +6,6 @@ [Developer Chat](https://ossci.zulipchat.com/) | [Zarr specifications](https://zarr-specs.readthedocs.io) - Zarr is a powerful library for storage of n-dimensional arrays, supporting chunking, compression, and various backends, making it a versatile choice for scientific and large-scale data. @@ -21,7 +20,7 @@ Zarr-Python is a Python library for reading and writing Zarr groups and arrays. ## Installation -Zarr requires Python 3.11 or higher. You can install it via `pip`: +Zarr requires Python 3.12 or higher. You can install it via `pip`: ```bash pip install zarr @@ -30,29 +29,27 @@ pip install zarr or `conda`: ```bash -conda install --channel conda-forge zarr +conda install -c conda-forge zarr ``` ## Navigating the documentation
-- [:material-clock-fast:{ .lg .middle } __Quick start__](quick-start.md) +- [:material-clock-fast:{ .lg .middle } __Quick start__](quick-start.md) --- New to Zarr? Check out the quick start guide. It contains a brief introduction to Zarr's main concepts and links to additional tutorials. - -- [:material-book-open:{ .lg .middle } __User guide__](user-guide/installation.md) +- [:material-book-open:{ .lg .middle } __User guide__](user-guide/index.md) --- A detailed guide for how to use Zarr-Python. - -- [:material-api:{ .lg .middle } __API Reference__](api/zarr/open.md) +- [:material-api:{ .lg .middle } __API Reference__](api/zarr/index.md) --- @@ -61,8 +58,15 @@ conda install --channel conda-forge zarr which parameters can be used. It assumes that you have an understanding of the key concepts. +- [:material-package-variant:{ .lg .middle } __Related projects__](subprojects.md) + + --- + + Companion packages developed in the zarr-python repository and released + independently, such as `zarr-metadata` and `zarr-indexing`, plus pointers to + the wider Zarr ecosystem. -- [:material-account-group:{ .lg .middle } __Contributor's Guide__](contributing.md) +- [:material-account-group:{ .lg .middle } __Contributor's Guide__](contributing.md) --- @@ -72,7 +76,6 @@ conda install --channel conda-forge zarr
- ## Project Status More information about the Zarr format can be found on the [main website](https://zarr.dev). @@ -80,6 +83,7 @@ More information about the Zarr format can be found on the [main website](https: If you are using Zarr-Python, we would [love to hear about it](https://github.com/zarr-developers/community/issues/19). ### Funding and Support + The project is fiscally sponsored by [NumFOCUS](https://numfocus.org/), a US 501(c)(3) public charity, and development has been supported by the [MRC Centre for Genomics and Global Health](https://github.com/cggh/) diff --git a/docs/quick-start.md b/docs/quick-start.md index bb7a556b96..123f05d5e9 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -1,7 +1,11 @@ -This section will help you get up and running with +# Quick start + +This page will help you get up and running with the Zarr library in Python to efficiently manage and analyze multi-dimensional arrays. +Zarr must be installed first -- see the [installation guide](user-guide/installation.md) +if you have not installed it yet. -### Creating an Array +## Creating an Array To get started, you can create a simple Zarr array: @@ -42,12 +46,11 @@ Here, we created a 2D array of shape `(100, 100)`, chunked into blocks of `(10, 10)`, and filled it with random floating-point data. This array was written to a `LocalStore` in the `data/example-1.zarr` directory. -#### Compression and Filters +### Compression and Filters Zarr supports data compression and filters. For example, to use Blosc compression: - -```python exec="true" session="quickstart" source="above" result="code" +```python exec="true" session="quickstart" source="above" result="ansi" # Create a 2D Zarr array with Blosc compression z = zarr.create_array( @@ -58,7 +61,7 @@ z = zarr.create_array( compressors=zarr.codecs.BloscCodec( cname="zstd", clevel=3, - shuffle=zarr.codecs.BloscShuffle.shuffle + shuffle="shuffle" ) ) @@ -69,8 +72,7 @@ print(z.info) This compresses the data using the Blosc codec with shuffle enabled for better compression. - -### Hierarchical Groups +## Hierarchical Groups Zarr allows you to create hierarchical groups, similar to directories: @@ -94,12 +96,12 @@ print(root.tree()) This creates a group hierarchy with a group (`foo`) and two arrays (`bar` and `spam`). -#### Batch Hierarchy Creation +### Batch Hierarchy Creation Zarr provides tools for creating a collection of arrays and groups with a single function call. Suppose we want to copy existing groups and arrays into a new storage backend: -```python exec="true" session="quickstart" source="above" result="html" +```python exec="true" session="quickstart" source="above" result="code" # Create nested groups and add arrays root = zarr.group("data/example-4.zarr", attributes={'name': 'root'}) @@ -122,23 +124,11 @@ assert new_root.attrs == root.attrs Note that [`zarr.create_hierarchy`][] will only initialize arrays and groups -- copying array data must be done in a separate step. -### Persistent Storage +## Persistent Storage Zarr supports persistent storage to disk or cloud-compatible backends. While examples above utilized a [`zarr.storage.LocalStore`][], a number of other storage options are available. -Zarr integrates seamlessly with cloud object storage such as Amazon S3 and Google Cloud Storage -using external libraries like [s3fs](https://s3fs.readthedocs.io) or -[gcsfs](https://gcsfs.readthedocs.io): - -```python - -import s3fs - -z = zarr.create_array("s3://example-bucket/foo", mode="w", shape=(100, 100), chunks=(10, 10), dtype="f4") -z[:, :] = np.random.random((100, 100)) -``` - A single-file store can also be created using the [`zarr.storage.ZipStore`][]: ```python exec="true" session="quickstart" source="above" @@ -162,7 +152,7 @@ store.close() To open an existing array from a ZIP file: -```python exec="true" session="quickstart" source="above" result="code" +```python exec="true" session="quickstart" source="above" result="ansi" # Open the ZipStore in read-only mode store = zarr.storage.ZipStore("data/example-5.zip", read_only=True) @@ -173,4 +163,29 @@ z = zarr.open_array(store, mode='r') print(z[:]) ``` -Read more about Zarr's storage options in the [User Guide](user-guide/index.md). +Zarr also integrates seamlessly with cloud object storage such as Amazon S3 and Google +Cloud Storage using external libraries like [s3fs](https://s3fs.readthedocs.io/en/latest/) or +[gcsfs](https://gcsfs.readthedocs.io/en/latest/). Remote storage support requires the `remote` +optional dependencies (`pip install "zarr[remote]"`) as well as a filesystem library +for your storage service, such as `s3fs` for S3: + +```python test="true" session="s3demo" markers="s3" source="above" +import zarr +import numpy as np + +z = zarr.create_array( + "s3://example-bucket/foo", shape=(100, 100), chunks=(10, 10), dtype="f4" +) +z[:, :] = np.random.random((100, 100)) +``` + +See the [Remote Store](user-guide/storage.md#remote-store) section of the storage guide +for more detail, including how to configure the underlying filesystem with `storage_options`. + +## Next steps + +This page only scratches the surface. Continue with the [User Guide](user-guide/index.md), in particular: + +- **[Arrays](user-guide/arrays.md)** - creating, reading, and writing arrays in depth +- **[Groups](user-guide/groups.md)** - organizing arrays into hierarchies +- **[Storage](user-guide/storage.md)** - the full range of local, remote, and in-memory storage options diff --git a/docs/release-notes.md b/docs/release-notes.md index 25ebdb8edf..3b54ea993a 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,12 +1,373 @@ # Release notes + + -## zarr 3.1.5 (2025-11-21) +## 3.3.0 (2026-07-30) + +### Features + +- Optimizes reading multiple chunks from a shard. Serial calls to `Store.get()` + in the sharding codec have been replaced with a single call to + `Store.get_ranges()`, which coalesces nearby byte ranges and fetches them + concurrently. ([#3004](https://github.com/zarr-developers/zarr-python/pull/3004)) +- Added a `subchunk_write_order` option to `ShardingCodec` to control the physical order of subchunks within a shard. Supported values are `morton`, `unordered`, `lexicographic`, and `colexicographic`. `unordered` makes no guarantee about subchunk layout. This setting affects only on-disk layout, not the data read back, and is not persisted in array metadata: it applies per codec instance and is not recovered when reopening a sharded array. ([#3826](https://github.com/zarr-developers/zarr-python/pull/3826)) +- Added `SyncByteGetter` and `SyncByteSetter` runtime-checkable protocols and a `get_ranges_sync` method on the `Store` ABC. These let custom byte getters/setters opt into the synchronous codec pipeline's fast path for in-memory IO, which the sharding codec uses for its inner chunks. ([#3885](https://github.com/zarr-developers/zarr-python/pull/3885)) +- Added `FusedCodecPipeline`, an opt-in codec pipeline that runs codec compute synchronously and in bulk (avoiding the per-chunk async scheduling overhead of the default `BatchedCodecPipeline`), giving large speedups for sharded arrays. The default `BatchedCodecPipeline` is unchanged for standard configurations, so existing code keeps working unless you opt in; enable the new pipeline with `zarr.config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"})`. ([#3885](https://github.com/zarr-developers/zarr-python/pull/3885)) +- Add `zarr.abc.store.Store.get_ranges` for concurrent, coalesced multi-range reads from a single key. The method is defined on the `Store` ABC with a default implementation built on `Store.get`, so every store inherits a working version; stores with native multi-range backends (e.g. `FsspecStore`) can override for efficiency. Coalescing knobs (`max_concurrency`, `max_gap_bytes`, `max_coalesced_bytes`) are passed as keyword arguments to `get_ranges`. Failures from underlying fetches surface as a `BaseExceptionGroup` (PEP 654); callers should use `except*` to filter for specific exception types such as `FileNotFoundError`. ([#3925](https://github.com/zarr-developers/zarr-python/pull/3925)) +- Two new fields on `ArrayConfig` control how the sharding codec coalesces partial-shard reads: `sharding_coalesce_max_gap_bytes` (default 1 MiB) and `sharding_coalesce_max_bytes` (default 16 MiB). When reading multiple chunks from the same shard, nearby byte ranges are merged into a single request to the store if separated by no more than `sharding_coalesce_max_gap_bytes` and the merged read stays within `sharding_coalesce_max_bytes`. Defaults are seeded from the matching `array.sharding_coalesce_max_gap_bytes` / `array.sharding_coalesce_max_bytes` keys in [`zarr.config`][] at array-creation time, and can be overridden per array by passing `config={...}` to [`zarr.create_array`][]. ([#3987](https://github.com/zarr-developers/zarr-python/pull/3987)) + +- Added `Group.get_array`, `Group.get_group`, `AsyncGroup.get_array`, and `AsyncGroup.get_group`: type-safe accessors that return the child array or group at a given path, raising `ArrayNotFoundError` / `GroupNotFoundError` if no node exists there, and `ContainsGroupError` / `ContainsArrayError` if the node is not of the requested kind. Unlike `Group.__getitem__`, which returns `Array | Group`, these methods have precise return types. Nested paths like `"subgroup/subarray"` are supported. ([#4128](https://github.com/zarr-developers/zarr-python/pull/4128)) +- `ZipStore` now accepts an open binary file-like object in place of a path, enabling + zip archives on remote storage (e.g. a file opened with `fsspec` or an + `obstore.ReadableFile`). Operations that require a filesystem location + (`clear`, `move`) raise `NotImplementedError` for file-object-backed stores. ([#4187](https://github.com/zarr-developers/zarr-python/pull/4187)) + +### Bugfixes + +- Stop emitting an `UnstableSpecificationWarning` when serializing the `struct` data type to Zarr V3 metadata. The `struct` data type now has a stable Zarr V3 specification. The legacy `structured` alias and the unspecified `null_terminated_bytes`, `raw_bytes`, and `variable_length_bytes` data types continue to warn. ([#4100](https://github.com/zarr-developers/zarr-python/pull/4100)) +- Fix equality comparison of `ArrayV2Metadata` and `ArrayV3Metadata` objects with a + `NaN` fill value. Such objects are now compared by their JSON-serialized form, so two + otherwise-identical metadata objects with a `NaN` (or infinite) fill value compare equal. ([#2929](https://github.com/zarr-developers/zarr-python/issues/2929)) +- Fixed `BytesCodec.from_dict` so that `BytesCodec` instances roundtrip to / from + their dict representation. `BytesCodec.from_dict` now interprets a missing + `endian` configuration as `endian=None` (matching what `BytesCodec.to_dict` + emits), instead of falling back to the system's native byte order. ([#3417](https://github.com/zarr-developers/zarr-python/pull/3417)) +- Fixed `save_array`, `Group.__setitem__`, and `load` for 0-dimensional arrays. ([#3469](https://github.com/zarr-developers/zarr-python/issues/3469)) +- Fixed inner-codec spec evolution for sharded arrays. The sharding codec now threads the array spec through its inner codec chain when evolving codecs, so a codec that changes the dtype upstream of `BytesCodec` no longer leaves the inner chain evolved against the wrong spec (which previously failed at decode time). This runs on the default `BatchedCodecPipeline` as well. Standard inner chains (`[BytesCodec]`, `[BytesCodec, ZstdCodec]`, transpose + bytes) are byte-identical to before. Restores the behavior of #2179. ([#3885](https://github.com/zarr-developers/zarr-python/pull/3885)) +- Make chunk normalization properly handle `-1` as a compact representation of the + length of an entire axis. Reject several previously-accepted but ill-defined + chunk specifications: `chunks=True` (previously silently produced size-1 chunks), + chunk tuples shorter than the array's number of dimensions (previously padded to + the array's shape), and `None` as a per-dimension chunk size. These all now + raise informative errors. Also fix chunk handling for 0-length array dimensions, + and add explicit rejection of 0-length chunks. ([#3899](https://github.com/zarr-developers/zarr-python/pull/3899)) +- Handle missing consolidated metadata in leaf Group nodes. ([#3954](https://github.com/zarr-developers/zarr-python/issues/3954)) +- Corrected the JSON type definitions for the `numpy.datetime64` and + `numpy.timedelta64` data types in Zarr V3 metadata: the `configuration` object + (holding `unit` and `scale_factor`) is now required, matching the published + specifications for these data types. Also updated the specification links in + the docstrings to point to the zarr-extensions repository. ([#3955](https://github.com/zarr-developers/zarr-python/pull/3955)) +- Fixed writing to 0-dimensional arrays that use the sharding codec. Previously + assigning to a 0-dimensional sharded array raised an error. ([#3966](https://github.com/zarr-developers/zarr-python/pull/3966)) +- Fix flaky stateful test bookkeeping when `delete_dir` matches string prefixes instead of true directory descendants. Previously a path such as `6/faNT…` could be incorrectly removed when deleting `6/f`. (See [issue #3977](https://github.com/zarr-developers/zarr-python/issues/3977).) ([#3977](https://github.com/zarr-developers/zarr-python/issues/3977)) +- `FsspecStore.close()` no longer closes the underlying fsspec filesystem or its + network session. fsspec caches and shares filesystem instances across callers, + so the store cannot know whether it is the only user, and closing a shared + session would break other stores; the filesystem's lifecycle belongs to + whoever created it. ([#4165](https://github.com/zarr-developers/zarr-python/pull/4165)) + +- Fixed an invalid `zarr.create_array` example in the quick-start documentation (it passed an unsupported `mode` argument) and made the cloud-storage example execute against a mock S3 backend in CI. Added a test ensuring every Python code block in the documentation is either executed or explicitly opted out with a documented reason, so an invalid example can no longer go untested. ([#4016](https://github.com/zarr-developers/zarr-python/issues/4016)) +- Fixed `ObjectStore.list_dir` for object-store listings that include a directory-marker object matching the requested non-root prefix. ([#4032](https://github.com/zarr-developers/zarr-python/issues/4032)) +- Prevents mutation of the attributes dict provided by the user by copying them instead of keeping the reference ([#4059](https://github.com/zarr-developers/zarr-python/issues/4059)) +- Fixed several storage and codec bugs: + + - Reading a value with a `SuffixByteRequest` larger than the value now correctly returns the whole value (matching HTTP `bytes=-N` suffix-range semantics), instead of silently returning incorrect data for `MemoryStore`. + - `LoggingStore.get_partial_values` and `FsspecStore.get_partial_values` no longer return empty results when `key_ranges` is passed as a one-shot iterable (e.g. a generator). + - `Store.getsize_prefix` no longer over-counts sibling keys that merely share a string prefix (e.g. `getsize_prefix("foo")` no longer includes keys under `foobar/`). + - `ZipStore.close()` no longer raises `AttributeError` when the store was created but never opened (including when used as a context manager without any I/O). + - `codecs_from_list` now raises a descriptive `TypeError` when a `BytesBytesCodec` immediately follows an `ArrayArrayCodec`, instead of a misleading "Required ArrayBytesCodec was not found" `ValueError`. + + ([#4074](https://github.com/zarr-developers/zarr-python/pull/4074)) + +- Fixed writing Fortran-ordered (F-contiguous) arrays through the variable-length string and bytes codecs and through numcodecs array-array filters such as `Delta`, `FixedScaleOffset` and `PackBits`. Chunks are now passed to numcodecs as C-contiguous arrays, so elements are no longer stored in transposed order. ([#4116](https://github.com/zarr-developers/zarr-python/pull/4116)) +- Fix silent byte-order corruption for structured dtypes with the `bytes` codec: multi-byte fields are now byte-swapped to the codec's configured `endian` on write and decoded honoring it on read, so non-native-endian structured data (e.g. big-endian fields, as produced by virtual references to external data) round-trips correctly. ([#4141](https://github.com/zarr-developers/zarr-python/issues/4141)) + +- Fix `zarr.api.asynchronous.open_like` so it can create a new array by default when the + target path does not already exist. It now defaults to `mode="a"`; when using a read-only + store to open an existing array, pass `mode="r"` explicitly. ([#3352](https://github.com/zarr-developers/zarr-python/pull/3352)) +- `MemoryStore` now copies buffers as they are written, so it never retains the + caller's memory. Previously an uncompressed write handed the store a zero-copy + view of the user's array, and mutating that array afterwards would silently + rewrite chunks already committed to the store. + + Only `MemoryStore` is affected: stores that serialize on write, such as + `LocalStore` and `ZipStore`, never aliased the caller's memory. Uncompressed + writes to a `MemoryStore` are correspondingly slower, since the copy that makes + the stored data independent is now actually performed; compressed writes are + unchanged. Buffers supplied through the `store_dict` argument remain the + caller's responsibility and are stored as-is. ([#4157](https://github.com/zarr-developers/zarr-python/pull/4157)) + +- Fixed the opt-in `FusedCodecPipeline` for sharded arrays whose inner or index codec chain contains a codec implementing only the async codec interface (no `SupportsSyncCodec`). Such arrays previously raised `TypeError: All codecs must implement SupportsSyncCodec` on both read and write; the pipeline now declines its synchronous fast path for them and falls back to the async path, matching the behavior of the default `BatchedCodecPipeline`. Fully sync-capable codec chains keep the fast path unchanged. ([#4179](https://github.com/zarr-developers/zarr-python/pull/4179)) +- Fixed `TypeError: unhashable type: 'writeable void-scalar'` when writing to sharded arrays whose fill value is a `np.void` scalar, e.g. arrays with a structured dtype. + + `ArraySpec` equality and hashing now compare the fill value by its byte representation rather than numeric equality. As a result, two specs with a `NaN` (or `NaT`) fill value now compare equal, while fill values of `-0.0` and `0.0` now compare unequal. This also restores the sharding codec's per-chunk spec cache, which had been disabled because of this bug. ([#4183](https://github.com/zarr-developers/zarr-python/pull/4183)) + +- `FusedCodecPipeline` no longer runs chunk IO and codec compute on the thread + driving zarr's internal event loop. Previously each read/write executed its + synchronous fast path inline on that loop thread, and because every sync-API + call from every user thread is serviced by the same loop, concurrent + operations serialized behind each other's codec work — reported as the fused + pipeline being slower than `BatchedCodecPipeline` for zstd-compressed data + under multi-threaded (e.g. dask) access. The synchronous batch now runs on a + worker thread (one hop per batch, not per chunk), keeping the loop free. + Multi-threaded single-chunk reads of compressed data now scale with reader + threads; single-threaded performance is unchanged. ([#4194](https://github.com/zarr-developers/zarr-python/pull/4194)) +- The end-to-end benchmarks no longer invoke `sudo` to drop the OS page cache during a regular `pytest` run. Cache clearing is now opt-in via the `ZARR_BENCHMARK_CLEAR_CACHE` environment variable, which the benchmark CI jobs set. ([#4199](https://github.com/zarr-developers/zarr-python/pull/4199)) +- Fixed the opt-in `FusedCodecPipeline` for serializers that advertise the partial-decode/encode mixins with only the documented async partial methods: the partial dispatch previously asserted on the private `_decode_partial_sync`/`_encode_partial_sync` hooks (an `AssertionError`, or an `AttributeError` mid-IO under `python -O`); such codecs now take the full-chunk sync path. ([#4201](https://github.com/zarr-developers/zarr-python/pull/4201)) +- Fixed `FusedCodecPipeline` (the opt-in synchronous pipeline) silently skipping + array-array/bytes-bytes codecs placed outside a sharding serializer on its + partial-decode/partial-encode fast paths. With an outer compressor (e.g. + `compressors=[GzipCodec()]` around a `ShardingCodec` serializer), the fused + pipeline wrote non-conforming stored bytes that `BatchedCodecPipeline` (and any + other conforming reader) could not read, and could fail to read data that + `BatchedCodecPipeline` had written. With an outer array-array codec (e.g. + `TransposeCodec`), it silently returned wrong data in both directions with no + error. Only the opt-in `FusedCodecPipeline` was affected; the default + `BatchedCodecPipeline` was never impacted. ([#4202](https://github.com/zarr-developers/zarr-python/pull/4202)) +- Fixed silent data corruption in the experimental `FusedCodecPipeline`: reordering or duplicating fancy-index reads (e.g. `arr[perm, :]`, `arr.oindex[[0, 0, 1], :]`) on uncompressed, crc-free sharded arrays could return the shard in natural order because the vectorized whole-shard decode accepted any selection whose output shape matched the shard shape. The bulk decode now fires only for identity full-shard reads, declines structured dtypes (whose byte-order handling it lacks), and requires shard-index offsets to exactly tile the data section, so corrupt indexes with overlapping or out-of-range offsets can no longer be served as array data. ([#4203](https://github.com/zarr-developers/zarr-python/pull/4203)) +- `ManagedMemoryStore.get_sync`/`set_sync`/`delete_sync` now apply the store's + `path` prefix, matching the async `get`/`set`/`delete` methods. Previously the + sync methods were inherited unchanged from `MemoryStore` and used the raw key, + so code that takes the sync fast path (e.g. `FusedCodecPipeline`) would read + and write chunks outside the store's `path` prefix, silently returning fill + values when the data was re-read through a fresh handle. `GpuMemoryStore.set_sync` + now converts its value to a `gpu.Buffer`, matching `set`, so writes through the + sync API keep the store's all-values-are-GPU invariant. Also fixed + `ManagedMemoryStore.get_partial_values` applying its `path` prefix twice + whenever `path` is non-empty, which made it always return `None` for every + requested key. + + The shared store test suite (`zarr.testing.store.StoreTests`) gained + sync/async parity checks — comparing sync and async observations of the same + key on the same store instance, including with a `byte_range` — so every + store subclass now exercises this invariant. The suite's former + `test_get_bytes`/`test_get_json` methods (and their `_sync` variants) were + folded into these parity tests and no longer exist as separate methods. ([#4204](https://github.com/zarr-developers/zarr-python/pull/4204)) + +- Fixed several small correctness issues from the codec-pipeline performance work: construction-time + codec warnings (e.g. sharding's "disables partial reads" warning) no longer fire twice per array + open — including for `FusedCodecPipeline`, which previously re-warned via its own codec-chain + reconstruction and, on the async fallback path, on every decode/encode call; `concurrent_iter` now + schedules its tasks eagerly, matching its documented contract; an invalid + `codec_pipeline.max_workers` config/environment value now warns and falls back to the default + instead of raising mid-read; and `FusedCodecPipeline`'s async fallback helpers now cancel + already-spawned fetch/decode/write tasks instead of abandoning them in the background when one + fails. ([#4205](https://github.com/zarr-developers/zarr-python/pull/4205)) +- Fixed `FusedCodecPipeline`'s gating of its synchronous fast paths: stores exposing only part of the sync surface (e.g. `set_sync` without `get_sync`) now fall back cleanly to the async path instead of failing mid-write, and `WrapperStore` now forwards `get_sync`/`set_sync`/`delete_sync` to the wrapped store so wrapped sync-capable stores keep the fast path. The capability decision uses a private, interim convention (`zarr.abc.store._store_supports_sync_io`) rather than new public API, pending a formal sync/async store architecture. Also fixed `LatencyStore`: synchronous reads and writes now pay the configured latency, `get_ranges`/`get_partial_values` no longer bypass latency injection, and derived stores (e.g. from `with_read_only`) keep a stochastic `(loc, scale)` latency configuration instead of freezing a single sample. ([#4206](https://github.com/zarr-developers/zarr-python/pull/4206)) +- `DefaultChunkKeyEncoding.decode_chunk_key` now validates that a chunk key + starts with the configured `c` prefix and raises `ValueError` for + malformed keys, instead of silently decoding them incorrectly. ([#4219](https://github.com/zarr-developers/zarr-python/pull/4219)) + +### Improved Documentation + +- Document the changes to `zarr.errors` in the 3.0 migration guide, including the removal of v2 exception classes and the introduction of `NodeNotFoundError`. ([#3009](https://github.com/zarr-developers/zarr-python/issues/3009)) +- Clarify the difference between `zarr.load` and `zarr.open` in their docstrings. + `load` eagerly reads data into an in-memory array, while `open` returns a + lazy `Array` or `Group` backed by the store, with `See Also` cross-references + linking the two. ([#3984](https://github.com/zarr-developers/zarr-python/pull/3984)) +- Updated the custom dtype example in `examples/custom_dtype/custom_dtype.py` to + use only the public API, eliminating all non-public imports, illustrating what + users should do. + + To better support this, the following types and functions were made available + from public modules: + + | Type/Function | Non-public module | Public module | + | ------------------------- | ------------------------ | ------------- | + | `DataTypeValidationError` | `zarr.core.dtype.common` | `zarr.errors` | + | `JSON` | `zarr.core.common` | `zarr.types` | + | `ZarrFormat` | `zarr.core.common` | `zarr.types` | + | `DTypeConfig_V2` | `zarr.core.dtype.common` | `zarr.types` | + | `DTypeJSON` | `zarr.core.dtype.common` | `zarr.types` | + | `DTypeSpec_V2` | `zarr.core.dtype.common` | `zarr.dtype` | + | `check_dtype_spec_v2` | `zarr.core.dtype.common` | `zarr.dtype` | + + `DataTypeValidationError` was *moved* to `zarr.errors`. Importing it from + `zarr.core.dtype.common` (its original location), `zarr.core.dtype`, or + `zarr.dtype` still works but now raises a `ZarrDeprecationWarning`. The remaining + types and functions are simply re-exported from the listed public module. ([#4052](https://github.com/zarr-developers/zarr-python/pull/4052)) + +- Document a self-merge policy in the contributor guide, describing when a core developer may merge their own pull request without a second reviewer and which changes warrant more caution. ([#4053](https://github.com/zarr-developers/zarr-python/pull/4053)) +- Fixed many documentation errors found in a full review of the user guide, including + prose contradicted by rendered example output on the performance page, invisible + code blocks, an incorrect S3 example, stale "not yet implemented" claims in the + v3 migration guide, and undocumented optional dependency groups. Also improved + navigation order, cross-linking between pages, and coverage of group member + enumeration, bulk attribute updates, and the `use_consolidated` keyword. ([#4132](https://github.com/zarr-developers/zarr-python/pull/4132)) +- Fixed the documented default of ``max_age_seconds`` in the ``CacheStore`` docstring: the default is ``"infinity"`` (no expiration), not ``None``, which is rejected. Also noted that ``cache_store`` must support deletes. ([#4133](https://github.com/zarr-developers/zarr-python/pull/4133)) + +- Added a blog section to the documentation, with a post covering two performance + highlights of the 3.3.0 release: the opt-in `FusedCodecPipeline` and byte-range + coalescing for partial reads of sharded arrays. + + Added two runnable examples that accompany the post: + `examples/codec_pipeline_performance` compares the `BatchedCodecPipeline` and + `FusedCodecPipeline` on a sharded array across two stores and two codec + regimes, showing when the fused pipeline's thread pool helps and when it does + not, and `examples/sharding_coalescing` demonstrates how read coalescing + reduces the number of store requests when reading subregions of a sharded + array. + + Also removed the hardware-specific speedup figures from the `FusedCodecPipeline` + release note, since they depend on the array layout, codec, and machine. ([#4191](https://github.com/zarr-developers/zarr-python/pull/4191)) + +### Deprecations and Removals + +- The ``BloscShuffle`` and ``BloscCname`` enums (``zarr.codecs.BloscShuffle``, + ``zarr.codecs.BloscCname``) are now deprecated. Pass the equivalent literal + string (e.g. ``"zstd"``, ``"bitshuffle"``) when constructing a ``BloscCodec``. + The enum classes remain importable but emit ``DeprecationWarning`` on member + access, and will be removed in a future release. They are no longer ``Enum`` + subclasses: constructor calls (e.g. ``BloscCname("zstd")``), iteration, and + ``.value`` access no longer work. ``BloscCodec.cname`` and + ``BloscCodec.shuffle`` are now plain strings rather than enum members. + + Additional renames in ``zarr.codecs.blosc`` from the same change: the type + aliases ``Shuffle`` and ``CName`` are now ``BloscShuffleLiteral`` and + ``BloscCnameLiteral``, the constant ``SHUFFLE`` is now ``BLOSC_SHUFFLE`` + (with a new ``BLOSC_CNAME`` alongside it), and ``BloscShuffle.from_int`` + now returns a literal string rather than an enum member. ([#3963](https://github.com/zarr-developers/zarr-python/pull/3963)) + +- The ``Endian`` (``zarr.codecs.bytes.Endian``) and ``ShardingCodecIndexLocation`` + (``zarr.codecs.ShardingCodecIndexLocation``) enums are now deprecated. Pass the + equivalent literal string instead (e.g. ``"little"`` / ``"big"``, ``"start"`` / + ``"end"``). The enum classes remain importable but emit ``DeprecationWarning`` + on member access, and will be removed in a future release. ``BytesCodec.endian`` + and ``ShardingCodec.index_location`` are now plain strings rather than enum + members. + + Two follow-on changes from this deprecation: + + - ``NDBuffer.byteorder`` now returns a literal string (``"little"`` or + ``"big"``) rather than an ``Endian`` member. Subclasses overriding this + property should update their return type. + - The module-level binding ``zarr.codecs.bytes.default_system_endian`` was + removed. ``BytesCodec()`` continues to default to ``sys.byteorder``; + external callers that imported ``default_system_endian`` should use + ``sys.byteorder`` directly. + + Additionally, the module-level function ``zarr.codecs.sharding.parse_index_location`` + was made private as part of this change. + + ([#3968](https://github.com/zarr-developers/zarr-python/pull/3968)) + +- Removed the NumPy 1.x implementation of the `VariableLengthUTF8` data type because NumPy 1.x is no longer supported under [SPEC0](https://scientific-python.org/specs/spec-0000/). ([#3973](https://github.com/zarr-developers/zarr-python/pull/3973)) + +### Misc + +- [#4139](https://github.com/zarr-developers/zarr-python/pull/4139), [#4140](https://github.com/zarr-developers/zarr-python/pull/4140), [#3908](https://github.com/zarr-developers/zarr-python/pull/3908), [#3972](https://github.com/zarr-developers/zarr-python/pull/3972), [#3975](https://github.com/zarr-developers/zarr-python/pull/3975), [#3979](https://github.com/zarr-developers/zarr-python/pull/3979), [#3990](https://github.com/zarr-developers/zarr-python/pull/3990), [#3998](https://github.com/zarr-developers/zarr-python/pull/3998), [#4000](https://github.com/zarr-developers/zarr-python/pull/4000), [#4001](https://github.com/zarr-developers/zarr-python/pull/4001), [#4012](https://github.com/zarr-developers/zarr-python/pull/4012), [#4046](https://github.com/zarr-developers/zarr-python/pull/4046), [#4054](https://github.com/zarr-developers/zarr-python/pull/4054), [#4073](https://github.com/zarr-developers/zarr-python/issues/4073), [#4086](https://github.com/zarr-developers/zarr-python/issues/4086), [#4138](https://github.com/zarr-developers/zarr-python/pull/4138) + +- [#4172](https://github.com/zarr-developers/zarr-python/pull/4172) + +## 3.2.1 (2026-05-05) + +### Bugfixes + +- Fixed a `CastValue` validation bug where the "can we use an out-of-range mode" check + inspected the source dtype instead of the target dtype. This meant arrays with a + float source dtype and an integer target dtype incorrectly raised a `ValueError` + when configured with a `wrap` out-of-range mode. ([#3938](https://github.com/zarr-developers/zarr-python/pull/3938)) +- Fixed a bug where the codec pipeline evolved each codec against the original + array spec instead of the spec produced by upstream array-to-array codecs. This + caused failures whenever an upstream codec changed the dtype between codec + boundaries — e.g. arrays using `CastValue` to convert a single-byte source dtype + (`int8`) to a multi-byte target dtype (`int16`) raised a `ValueError` from + `BytesCodec` about a missing `endian` configuration. ([#3941](https://github.com/zarr-developers/zarr-python/pull/3941)) +- Fixed breakage in existing fsspec-dependent workflows caused by associating the "memory" URL scheme with +instances of `ManagedMemoryStore` instead of fsspec's memory-backed store. After this change, store URLs with a "memory" scheme are handled differently when `fsspec` is installed: +with `fsspec`, a `FsspecStore` backed by a `MemoryFileSystem` is used. Without `fsspec`, +a `ManagedMemoryStore` is used. ([#3944](https://github.com/zarr-developers/zarr-python/pull/3944)) + +## 3.2.0 (2026-04-30) + +### Features + +- Adds a new in-memory storage backend called `ManagedMemoryStore`. Instances of `ManagedMemoryStore` + function similarly to `MemoryStore`, but instances of `ManagedMemoryStore` can be constructed from + a URL like `memory://store`. ([#3679](https://github.com/zarr-developers/zarr-python/pull/3679)) +- Added `array.read_missing_chunks` configuration option. When set to `False`, reading missing chunks raises a `ChunkNotFoundError` instead of filling them with the array's fill value. ([#3748](https://github.com/zarr-developers/zarr-python/pull/3748)) +- Added `Struct` class (subclass of `Structured`) implementing the zarr-extensions `struct` dtype spec. Uses object-style field format and dict fill values. Legacy `Structured` remains available for backward compatibility. ([#3781](https://github.com/zarr-developers/zarr-python/pull/3781)) +- Add support for rectilinear (variable-sized) chunk grids. This feature is experimental and + must be explicitly enabled via `zarr.config.set({'array.rectilinear_chunks': True})`. + + Rectilinear chunks can be used through: + + - **Creating arrays**: Pass nested sequences (e.g., `[[10, 20, 30], [50, 50]]`) to `chunks` + in `zarr.create_array`, `zarr.from_array`, `zarr.zeros`, `zarr.ones`, `zarr.full`, + `zarr.open`, and related functions, or to `chunk_shape` in `zarr.create`. + - **Opening existing arrays**: Arrays stored with the `rectilinear` chunk grid are read + transparently via `zarr.open` and `zarr.open_array`. + - **Rectilinear sharding**: Shard boundaries can be rectilinear while inner chunks remain regular. + + **Breaking change**: The `validate` method on `BaseCodec` and `CodecPipeline` now receives + a `ChunkGridMetadata` instance instead of a `ChunkGrid` instance for the `chunk_grid` + parameter. Third-party codecs that override `validate` and inspect the chunk grid will need to + update their type annotations. No known downstream packages were using this parameter. ([#3802](https://github.com/zarr-developers/zarr-python/pull/3802)) + +- Add `cast_value` and `scale_offset` codecs. ([#3874](https://github.com/zarr-developers/zarr-python/pull/3874)) + +### Bugfixes + +- Fix `SyncError` raised when assigning a `zarr.Array` as the value in a `__setitem__` call (e.g. `dst[:] = src` where `src` is a zarr array). The source array is now converted to a NumPy array before entering the async codec pipeline. ([#3611](https://github.com/zarr-developers/zarr-python/issues/3611)) +- Fix an issue that prevents the correct parsing of special NumPy `uint32` dtypes resulting e.g. + from bit wise operations on `uint32` arrays on Windows. ([#3797](https://github.com/zarr-developers/zarr-python/pull/3797)) +- Fix `ZipStore.list()`, `list_dir()`, and `exists()` to auto-open the zip file when called before `open()`, consistent with the existing behavior of `get()` and `set()`. ([#3846](https://github.com/zarr-developers/zarr-python/issues/3846)) +- Fix handling of `NaT` default fill values for `datetime64` and `timedelta64` data types. Equality checks now use `numpy.isnat` so that the default fill value compares correctly against `NaT`. ([#3863](https://github.com/zarr-developers/zarr-python/pull/3863)) +- Use the unit associated with the `Datetime64` data type when creating the default `Nat` scalar value. ([#3920](https://github.com/zarr-developers/zarr-python/pull/3920)) + +### Improved Documentation -## Bugfixes +- Document removal of `zarr.storage.init_group` in v3 migration guide, with replacement using `zarr.open_group`/`zarr.create_group`. ([#2720](https://github.com/zarr-developers/zarr-python/issues/2720)) +- Document the `threading.max_workers` configuration option in the performance guide. ([#3492](https://github.com/zarr-developers/zarr-python/issues/3492)) +- Corrects the type annotation reported for the `batch_info` parameter in the `CodecPipeline.write` + method docstring. ([#3836](https://github.com/zarr-developers/zarr-python/pull/3836)) +- Remove result="ansi" from code blocks in the user guide that were causing empty output cells in the rendered documentation. ([#3845](https://github.com/zarr-developers/zarr-python/pull/3845)) -- Fix formatting errors in the release notes section of the docs. ([#3594](https://github.com/zarr-developers/zarr-python/issues/3594)) +### Deprecations and Removals + +- Remove deprecated `zarr.convenience` and `zarr.creation` modules. ([#3900](https://github.com/zarr-developers/zarr-python/pull/3900)) +- Remove the deprecated `zarr_version` parameter from several functions and methods. That parameter is replaced with `zarr_format`. ([#3901](https://github.com/zarr-developers/zarr-python/pull/3901)) +- Remove deprecated `Group` methods `array`, `require_dataset`, and `create_dataset`. ([#3902](https://github.com/zarr-developers/zarr-python/pull/3902)) +- Remove deprecated `AsyncArray.create` and `Array.create` methods. ([#3903](https://github.com/zarr-developers/zarr-python/pull/3903)) + +### Misc + +- [#3546](https://github.com/zarr-developers/zarr-python/issues/3546), [#3793](https://github.com/zarr-developers/zarr-python/pull/3793), [#3800](https://github.com/zarr-developers/zarr-python/pull/3800), [#3828](https://github.com/zarr-developers/zarr-python/pull/3828), [#3830](https://github.com/zarr-developers/zarr-python/pull/3830), [#3833](https://github.com/zarr-developers/zarr-python/pull/3833), [#3837](https://github.com/zarr-developers/zarr-python/pull/3837), [#3897](https://github.com/zarr-developers/zarr-python/pull/3897) + + +## 3.1.6 (2026-03-19) + +### Features + +- Exposes the array runtime configuration as an attribute called `config` on the `Array` and + `AsyncArray` classes. The previous `AsyncArray._config` attribute is now a deprecated alias for `AsyncArray.config`. ([#3668](https://github.com/zarr-developers/zarr-python/pull/3668)) +- Adds a method for creating a new `Array` / `AsyncArray` instance with a new runtime configuration, and fixes inaccurate documentation about the `write_empty_chunks` configuration parameter. ([#3668](https://github.com/zarr-developers/zarr-python/pull/3668)) +- Adds synchronous methods to stores that do not benefit from an async event loop. The shape of these methods is defined by protocol classes to support structural subtyping. ([#3725](https://github.com/zarr-developers/zarr-python/pull/3725)) +- Fix near-miss penalty in `_morton_order` with hybrid ceiling+argsort strategy. ([#3718](https://github.com/zarr-developers/zarr-python/pull/3718)) + +### Bugfixes + +- Correct the target bytes number for auto-chunking when auto-sharding. ([#3603](https://github.com/zarr-developers/zarr-python/pull/3603)) +- Fixed a bug in the sharding codec that prevented nested shard reads in certain cases. ([#3655](https://github.com/zarr-developers/zarr-python/pull/3655)) +- Fix obstore `_transform_list_dir` implementation to correctly relativize paths (removing `lstrip` usage). ([#3657](https://github.com/zarr-developers/zarr-python/pull/3657)) +- Raise error when trying to encode `numpy.dtypes.StringDType` with `na_object` set. ([#3695](https://github.com/zarr-developers/zarr-python/pull/3695)) +- `CacheStore`, `LoggingStore` and `LatencyStore` now support with_read_only. ([#3700](https://github.com/zarr-developers/zarr-python/pull/3700)) +- Skip chunk coordinate enumeration in resize when the array is only growing, avoiding unbounded memory usage for large arrays. ([#3702](https://github.com/zarr-developers/zarr-python/pull/3702)) +- Fix a performance bug in morton curve generation. ([#3705](https://github.com/zarr-developers/zarr-python/pull/3705)) +- Add a dedicated in-memory cache for byte-range requests to the experimental `CacheStore`. ([#3710](https://github.com/zarr-developers/zarr-python/pull/3710)) +- `BaseFloat._check_scalar` rejects invalid string values. ([#3586](https://github.com/zarr-developers/zarr-python/issues/3586)) +- Apply drop_axes squeeze in partial decode path for sharding. ([#3763](https://github.com/zarr-developers/zarr-python/pull/3763)) +- Set `copy=False` in reshape operation. ([#3649](https://github.com/zarr-developers/zarr-python/pull/3649)) +- Validate that dask-style chunks have regular shapes. ([#3779](https://github.com/zarr-developers/zarr-python/pull/3779)) + +### Improved Documentation + +- Add documentation example for creating uncompressed arrays in the Compression section of the user guide. ([#3464](https://github.com/zarr-developers/zarr-python/issues/3464)) +- Add AI-assisted code policy to the contributing guide. ([#3769](https://github.com/zarr-developers/zarr-python/pull/3769)) +- Added a glossary. ([#3767](https://github.com/zarr-developers/zarr-python/pull/3767)) + +### Misc + +- [#3562](https://github.com/zarr-developers/zarr-python/pull/3562), [#3605](https://github.com/zarr-developers/zarr-python/pull/3605), [#3619](https://github.com/zarr-developers/zarr-python/pull/3619), [#3623](https://github.com/zarr-developers/zarr-python/pull/3623), [#3636](https://github.com/zarr-developers/zarr-python/pull/3636), [#3648](https://github.com/zarr-developers/zarr-python/pull/3648), [#3656](https://github.com/zarr-developers/zarr-python/pull/3656), [#3658](https://github.com/zarr-developers/zarr-python/pull/3658), [#3673](https://github.com/zarr-developers/zarr-python/pull/3673), [#3704](https://github.com/zarr-developers/zarr-python/pull/3704), [#3706](https://github.com/zarr-developers/zarr-python/pull/3706), [#3708](https://github.com/zarr-developers/zarr-python/pull/3708), [#3712](https://github.com/zarr-developers/zarr-python/pull/3712), [#3713](https://github.com/zarr-developers/zarr-python/pull/3713), [#3717](https://github.com/zarr-developers/zarr-python/pull/3717), [#3721](https://github.com/zarr-developers/zarr-python/pull/3721), [#3728](https://github.com/zarr-developers/zarr-python/pull/3728), [#3778](https://github.com/zarr-developers/zarr-python/pull/3778) + + +## 3.1.5 (2025-11-21) + +### Bugfixes + +- Fix formatting errors in the release notes section of the docs. ([#3594](https://github.com/zarr-developers/zarr-python/pull/3594)) ## 3.1.4 (2025-11-20) @@ -14,52 +375,52 @@ ### Features - The `Array` class can now also be parametrized in the same manner as the `AsyncArray` class, allowing Zarr format v2 and v3 `Array`s to be distinguished. - New types have been added to `zarr.types` to help with this. ([#3304](https://github.com/zarr-developers/zarr-python/issues/3304)) -- Adds `zarr.experimental.cache_store.CacheStore`, a `Store` that implements caching by combining two other `Store` instances. See the [docs page](https://zarr.readthedocs.io/en/latest/user-guide/experimental#cachestore) for more information about this feature. ([#3366](https://github.com/zarr-developers/zarr-python/issues/3366)) -- Adds a `zarr.experimental` module for unstable user-facing features. ([#3490](https://github.com/zarr-developers/zarr-python/issues/3490)) -- Add a `array.target_shard_size_bytes` to [`zarr.config`][] to allow users to set a maximum number of bytes per-shard when `shards="auto"` in, for example, [`zarr.create_array`][]. ([#3547](https://github.com/zarr-developers/zarr-python/issues/3547)) -- Make `async_array` on the [`zarr.Array`][] class public (`_async_array` will remain untouched, but its stability is not guaranteed). ([#3556](https://github.com/zarr-developers/zarr-python/issues/3556)) + New types have been added to `zarr.types` to help with this. ([#3304](https://github.com/zarr-developers/zarr-python/pull/3304)) +- Adds `zarr.experimental.cache_store.CacheStore`, a `Store` that implements caching by combining two other `Store` instances. See the [docs page](https://zarr.readthedocs.io/en/latest/user-guide/experimental#cachestore) for more information about this feature. ([#3366](https://github.com/zarr-developers/zarr-python/pull/3366)) +- Adds a `zarr.experimental` module for unstable user-facing features. ([#3490](https://github.com/zarr-developers/zarr-python/pull/3490)) +- Add a `array.target_shard_size_bytes` to [`zarr.config`][] to allow users to set a maximum number of bytes per-shard when `shards="auto"` in, for example, [`zarr.create_array`][]. ([#3547](https://github.com/zarr-developers/zarr-python/pull/3547)) +- Make `async_array` on the [`zarr.Array`][] class public (`_async_array` will remain untouched, but its stability is not guaranteed). ([#3556](https://github.com/zarr-developers/zarr-python/pull/3556)) ### Bugfixes -- Fix a bug that prevented `PCodec` from being properly resolved when loading arrays using that compressor. ([#3483](https://github.com/zarr-developers/zarr-python/issues/3483)) +- Fix a bug that prevented `PCodec` from being properly resolved when loading arrays using that compressor. ([#3483](https://github.com/zarr-developers/zarr-python/pull/3483)) - Fixed a bug that prevented Zarr Python from opening Zarr V3 array metadata documents that contained - extra keys with permissible values (dicts with a `"must_understand"` key set to `"false"`). ([#3530](https://github.com/zarr-developers/zarr-python/issues/3530)) + extra keys with permissible values (dicts with a `"must_understand"` key set to `"false"`). ([#3530](https://github.com/zarr-developers/zarr-python/pull/3530)) - Fixed a bug where the `"consolidated_metadata"` key was written to metadata documents even when - consolidated metadata was not used, resulting in invalid metadata documents. ([#3535](https://github.com/zarr-developers/zarr-python/issues/3535)) + consolidated metadata was not used, resulting in invalid metadata documents. ([#3535](https://github.com/zarr-developers/zarr-python/pull/3535)) - Improve write performance to large shards by up to 10x. ([#3560](https://github.com/zarr-developers/zarr-python/issues/3560)) ### Improved Documentation -- Use mkdocs-material for Zarr-Python documentation ([#3118](https://github.com/zarr-developers/zarr-python/issues/3118)) +- Use mkdocs-material for Zarr-Python documentation ([#3118](https://github.com/zarr-developers/zarr-python/pull/3118)) - Document different values of StoreLike with examples in the user guide. ([#3303](https://github.com/zarr-developers/zarr-python/issues/3303)) -- Reorganize the top-level `examples` directory to give each example its own sub-directory. Adds content to the docs for each example. ([#3502](https://github.com/zarr-developers/zarr-python/issues/3502)) +- Reorganize the top-level `examples` directory to give each example its own sub-directory. Adds content to the docs for each example. ([#3502](https://github.com/zarr-developers/zarr-python/pull/3502)) - Updated 3.0 Migration Guide to include function signature change to zarr.Array.resize function. ([#3536](https://github.com/zarr-developers/zarr-python/issues/3536)) ### Misc -- [#3515](https://github.com/zarr-developers/zarr-python/issues/3515), [#3532](https://github.com/zarr-developers/zarr-python/issues/3532), [#3533](https://github.com/zarr-developers/zarr-python/issues/3533), [#3553](https://github.com/zarr-developers/zarr-python/issues/3553) +- [#3515](https://github.com/zarr-developers/zarr-python/pull/3515), [#3532](https://github.com/zarr-developers/zarr-python/pull/3532), [#3533](https://github.com/zarr-developers/zarr-python/pull/3533), [#3553](https://github.com/zarr-developers/zarr-python/pull/3553) -## zarr 3.1.3 (2025-09-18) +## 3.1.3 (2025-09-18) ### Features - Add a command-line interface to migrate v2 Zarr metadata to v3. Corresponding functions are also provided under zarr.metadata. ([#1798](https://github.com/zarr-developers/zarr-python/issues/1798)) -- Add obstore implementation of delete_dir. ([#3310](https://github.com/zarr-developers/zarr-python/issues/3310)) -- Adds a registry for chunk key encodings for extensibility. This allows users to implement a custom `ChunkKeyEncoding`, which can be registered via `register_chunk_key_encoding` or as an entry point under `zarr.chunk_key_encoding`. ([#3436](https://github.com/zarr-developers/zarr-python/issues/3436)) -- Trying to open a group at a path where an array already exists now raises a helpful error. ([#3444](https://github.com/zarr-developers/zarr-python/issues/3444)) +- Add obstore implementation of delete_dir. ([#3310](https://github.com/zarr-developers/zarr-python/pull/3310)) +- Adds a registry for chunk key encodings for extensibility. This allows users to implement a custom `ChunkKeyEncoding`, which can be registered via `register_chunk_key_encoding` or as an entry point under `zarr.chunk_key_encoding`. ([#3436](https://github.com/zarr-developers/zarr-python/pull/3436)) +- Trying to open a group at a path where an array already exists now raises a helpful error. ([#3444](https://github.com/zarr-developers/zarr-python/pull/3444)) ### Bugfixes - Prevents creation of groups (.create_group) or arrays (.create_array) as children of an existing array. ([#2582](https://github.com/zarr-developers/zarr-python/issues/2582)) -- Fix a bug preventing `ones_like`, `full_like`, `empty_like`, `zeros_like` and `open_like` functions from accepting an explicit specification of array attributes like shape, dtype, chunks etc. The functions `full_like`, `empty_like`, and `open_like` now also more consistently infer a `fill_value` parameter from the provided array. ([#2992](https://github.com/zarr-developers/zarr-python/issues/2992)) +- Fix a bug preventing `ones_like`, `full_like`, `empty_like`, `zeros_like` and `open_like` functions from accepting an explicit specification of array attributes like shape, dtype, chunks etc. The functions `full_like`, `empty_like`, and `open_like` now also more consistently infer a `fill_value` parameter from the provided array. ([#2992](https://github.com/zarr-developers/zarr-python/pull/2992)) - LocalStore now uses atomic writes, which should prevent some cases of corrupted data. ([#3411](https://github.com/zarr-developers/zarr-python/issues/3411)) -- Fix a potential race condition when using `zarr.create_array` with the `data` parameter set to a NumPy array. Previously Zarr was iterating over the newly created array with a granularity that was too low. Now Zarr chooses a granularity that matches the size of the stored objects for that array. ([#3422](https://github.com/zarr-developers/zarr-python/issues/3422)) -- Fix ChunkGrid definition (broken in 3.1.2) ([#3425](https://github.com/zarr-developers/zarr-python/issues/3425)) -- Ensure syntax like `root['/subgroup']` works equivalently to `root['subgroup']` when using consolidated metadata. ([#3428](https://github.com/zarr-developers/zarr-python/issues/3428)) -- Creating a new group with `zarr.group` no longer errors. This fixes a regression introduced in version 3.1.2. ([#3431](https://github.com/zarr-developers/zarr-python/issues/3431)) -- Setting `fill_value` to a float like `0.0` when the data type of the array is an integer is a common mistake. This change lets Zarr Python read arrays with this erroneous metadata, although Zarr Python will not create such arrays. ([#3448](https://github.com/zarr-developers/zarr-python/issues/3448)) +- Fix a potential race condition when using `zarr.create_array` with the `data` parameter set to a NumPy array. Previously Zarr was iterating over the newly created array with a granularity that was too low. Now Zarr chooses a granularity that matches the size of the stored objects for that array. ([#3422](https://github.com/zarr-developers/zarr-python/pull/3422)) +- Fix ChunkGrid definition (broken in 3.1.2) ([#3425](https://github.com/zarr-developers/zarr-python/pull/3425)) +- Ensure syntax like `root['/subgroup']` works equivalently to `root['subgroup']` when using consolidated metadata. ([#3428](https://github.com/zarr-developers/zarr-python/pull/3428)) +- Creating a new group with `zarr.group` no longer errors. This fixes a regression introduced in version 3.1.2. ([#3431](https://github.com/zarr-developers/zarr-python/pull/3431)) +- Setting `fill_value` to a float like `0.0` when the data type of the array is an integer is a common mistake. This change lets Zarr Python read arrays with this erroneous metadata, although Zarr Python will not create such arrays. ([#3448](https://github.com/zarr-developers/zarr-python/pull/3448)) ### Deprecations and Removals @@ -67,56 +428,56 @@ ### Misc -- [#3376](https://github.com/zarr-developers/zarr-python/issues/3376), [#3390](https://github.com/zarr-developers/zarr-python/issues/3390), [#3403](https://github.com/zarr-developers/zarr-python/issues/3403), [#3449](https://github.com/zarr-developers/zarr-python/issues/3449) +- [#3376](https://github.com/zarr-developers/zarr-python/pull/3376), [#3390](https://github.com/zarr-developers/zarr-python/pull/3390), [#3403](https://github.com/zarr-developers/zarr-python/pull/3403), [#3449](https://github.com/zarr-developers/zarr-python/pull/3449) ## 3.1.2 (2025-08-25) ### Features -- Added support for async vectorized and orthogonal indexing. ([#3083](https://github.com/zarr-developers/zarr-python/issues/3083)) -- Make config param optional in init_array ([#3391](https://github.com/zarr-developers/zarr-python/issues/3391)) +- Added support for async vectorized and orthogonal indexing. ([#3083](https://github.com/zarr-developers/zarr-python/pull/3083)) +- Make config param optional in init_array ([#3391](https://github.com/zarr-developers/zarr-python/pull/3391)) ### Bugfixes - Ensure that -0.0 is not considered equal to 0.0 when checking if all the values in a chunk are equal to an array's fill value. ([#3144](https://github.com/zarr-developers/zarr-python/issues/3144)) -- Fix a bug in `create_array` caused by iterating over chunk-aligned regions instead of shard-aligned regions when writing data. Additionally, the behavior of `nchunks_initialized` has been adjusted. This function consistently reports the number of chunks present in stored objects, even when the array uses the sharding codec. ([#3299](https://github.com/zarr-developers/zarr-python/issues/3299)) -- Opening an array or group with `mode="r+"` will no longer create new arrays or groups. ([#3307](https://github.com/zarr-developers/zarr-python/issues/3307)) -- Added `zarr.errors.ArrayNotFoundError`, which is raised when attempting to open a zarr array that does not exist, and `zarr.errors.NodeNotFoundError`, which is raised when failing to open an array or a group in a context where either an array or a group was expected. ([#3367](https://github.com/zarr-developers/zarr-python/issues/3367)) -- Ensure passing `config` is handled properly when `open`ing an existing array. ([#3378](https://github.com/zarr-developers/zarr-python/issues/3378)) -- Raise a Zarr-specific error class when a codec can't be found by name when deserializing the given codecs. This avoids hiding this error behind a "not part of a zarr hierarchy" warning. ([#3395](https://github.com/zarr-developers/zarr-python/issues/3395)) +- Fix a bug in `create_array` caused by iterating over chunk-aligned regions instead of shard-aligned regions when writing data. Additionally, the behavior of `nchunks_initialized` has been adjusted. This function consistently reports the number of chunks present in stored objects, even when the array uses the sharding codec. ([#3299](https://github.com/zarr-developers/zarr-python/pull/3299)) +- Opening an array or group with `mode="r+"` will no longer create new arrays or groups. ([#3307](https://github.com/zarr-developers/zarr-python/pull/3307)) +- Added `zarr.errors.ArrayNotFoundError`, which is raised when attempting to open a zarr array that does not exist, and `zarr.errors.NodeNotFoundError`, which is raised when failing to open an array or a group in a context where either an array or a group was expected. ([#3367](https://github.com/zarr-developers/zarr-python/pull/3367)) +- Ensure passing `config` is handled properly when `open`ing an existing array. ([#3378](https://github.com/zarr-developers/zarr-python/pull/3378)) +- Raise a Zarr-specific error class when a codec can't be found by name when deserializing the given codecs. This avoids hiding this error behind a "not part of a zarr hierarchy" warning. ([#3395](https://github.com/zarr-developers/zarr-python/pull/3395)) ### Misc -- [#3098](https://github.com/zarr-developers/zarr-python/issues/3098), [#3288](https://github.com/zarr-developers/zarr-python/issues/3288), [#3318](https://github.com/zarr-developers/zarr-python/issues/3318), [#3368](https://github.com/zarr-developers/zarr-python/issues/3368), [#3371](https://github.com/zarr-developers/zarr-python/issues/3371), [#3372](https://github.com/zarr-developers/zarr-python/issues/3372), [#3374](https://github.com/zarr-developers/zarr-python/issues/3374) +- [#3098](https://github.com/zarr-developers/zarr-python/pull/3098), [#3288](https://github.com/zarr-developers/zarr-python/pull/3288), [#3318](https://github.com/zarr-developers/zarr-python/pull/3318), [#3368](https://github.com/zarr-developers/zarr-python/issues/3368), [#3371](https://github.com/zarr-developers/zarr-python/pull/3371), [#3372](https://github.com/zarr-developers/zarr-python/pull/3372), [#3374](https://github.com/zarr-developers/zarr-python/pull/3374) ## 3.1.1 (2025-07-28) ### Features -- Add lightweight implementations of `.getsize()` and `.getsize_prefix()` for ObjectStore. ([#3227](https://github.com/zarr-developers/zarr-python/issues/3227)) +- Add lightweight implementations of `.getsize()` and `.getsize_prefix()` for ObjectStore. ([#3227](https://github.com/zarr-developers/zarr-python/pull/3227)) ### Bugfixes -- Creating a Zarr format 2 array with the `order` keyword argument no longer raises a warning. ([#3112](https://github.com/zarr-developers/zarr-python/issues/3112)) -- Fixed the error message when passing both `config` and `write_empty_chunks` arguments to reflect the current behaviour (`write_empty_chunks` takes precedence). ([#3112](https://github.com/zarr-developers/zarr-python/issues/3112)) -- Creating a Zarr format 3 array with the `order` argument now consistently ignores this argument and raises a warning. ([#3112](https://github.com/zarr-developers/zarr-python/issues/3112)) -- When using [`from_array`][zarr.api.asynchronous.from_array] to copy a Zarr format 2 array to a Zarr format 3 array, if the memory order of the input array is `"F"` a warning is raised and the order ignored. This is because Zarr format 3 arrays are always stored in "C" order. ([#3112](https://github.com/zarr-developers/zarr-python/issues/3112)) -- The `config` argument to [`zarr.create`][zarr.create] (and functions that create arrays) is now used - previously it had no effect. ([#3112](https://github.com/zarr-developers/zarr-python/issues/3112)) -- Ensure that all abstract methods of [`ZDType`][zarr.core.dtype.ZDType] raise a `NotImplementedError` when invoked. ([#3251](https://github.com/zarr-developers/zarr-python/issues/3251)) -- Register 'gpu' marker with pytest for downstream StoreTests. ([#3258](https://github.com/zarr-developers/zarr-python/issues/3258)) +- Creating a Zarr format 2 array with the `order` keyword argument no longer raises a warning. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- Fixed the error message when passing both `config` and `write_empty_chunks` arguments to reflect the current behaviour (`write_empty_chunks` takes precedence). ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- Creating a Zarr format 3 array with the `order` argument now consistently ignores this argument and raises a warning. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- When using [`from_array`][zarr.api.asynchronous.from_array] to copy a Zarr format 2 array to a Zarr format 3 array, if the memory order of the input array is `"F"` a warning is raised and the order ignored. This is because Zarr format 3 arrays are always stored in "C" order. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- The `config` argument to [`zarr.create`][zarr.create] (and functions that create arrays) is now used - previously it had no effect. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- Ensure that all abstract methods of [`ZDType`][zarr.core.dtype.ZDType] raise a `NotImplementedError` when invoked. ([#3251](https://github.com/zarr-developers/zarr-python/pull/3251)) +- Register 'gpu' marker with pytest for downstream StoreTests. ([#3258](https://github.com/zarr-developers/zarr-python/pull/3258)) - Expand the range of types accepted by `parse_data_type` to include strings and Sequences. -- Move the functionality of `zarr.core.dtype.parse_data_type` to a new function called `zarr.dtype.parse_dtype`. This change ensures that nomenclature is consistent across the codebase. `zarr.core.dtype.parse_data_type` remains, so this change is not breaking. ([#3264](https://github.com/zarr-developers/zarr-python/issues/3264)) -- Fix a regression introduced in 3.1.0 that prevented `inf`, `-inf`, and `nan` values from being stored in `attributes`. ([#3280](https://github.com/zarr-developers/zarr-python/issues/3280)) -- Fixes [`Group.nmembers()`][zarr.Group.nmembers] ignoring depth when using consolidated metadata. ([#3287](https://github.com/zarr-developers/zarr-python/issues/3287)) +- Move the functionality of `zarr.core.dtype.parse_data_type` to a new function called `zarr.dtype.parse_dtype`. This change ensures that nomenclature is consistent across the codebase. `zarr.core.dtype.parse_data_type` remains, so this change is not breaking. ([#3264](https://github.com/zarr-developers/zarr-python/pull/3264)) +- Fix a regression introduced in 3.1.0 that prevented `inf`, `-inf`, and `nan` values from being stored in `attributes`. ([#3280](https://github.com/zarr-developers/zarr-python/pull/3280)) +- Fixes [`Group.nmembers()`][zarr.Group.nmembers] ignoring depth when using consolidated metadata. ([#3287](https://github.com/zarr-developers/zarr-python/pull/3287)) ### Improved Documentation -- Expand the data type docs to include a demonstration of the `parse_data_type` function. Expand the docstring for the `parse_data_type` function. ([#3249](https://github.com/zarr-developers/zarr-python/issues/3249)) -- Add a section on codecs to the migration guide. ([#3273](https://github.com/zarr-developers/zarr-python/issues/3273)) +- Expand the data type docs to include a demonstration of the `parse_data_type` function. Expand the docstring for the `parse_data_type` function. ([#3249](https://github.com/zarr-developers/zarr-python/pull/3249)) +- Add a section on codecs to the migration guide. ([#3273](https://github.com/zarr-developers/zarr-python/pull/3273)) ### Misc -- Remove warnings about vlen-utf8 and vlen-bytes codecs ([#3268](https://github.com/zarr-developers/zarr-python/issues/3268)) +- Remove warnings about vlen-utf8 and vlen-bytes codecs ([#3268](https://github.com/zarr-developers/zarr-python/pull/3268)) ## 3.1.0 (2025-07-14) @@ -124,107 +485,107 @@ - Ensure that invocations of `create_array` use consistent keyword arguments, with consistent defaults. - [`zarr.api.synchronous.create_array`][] now takes a `write_data` keyword argument - The `Group.create_array` method takes `data` and `write_data` keyword arguments. - The functions [`zarr.api.asynchronous.create`][], [`zarr.api.asynchronous.create_array`] - and the methods `Group.create_array`, `Group.array`, had the default - `fill_value` changed from `0` to the `DEFAULT_FILL_VALUE` value, which instructs Zarr to - use the default scalar value associated with the array's data type as the fill value. These are - all functions or methods for array creation that mirror, wrap or are wrapped by, another function - that already has a default `fill_value` set to `DEFAULT_FILL_VALUE`. This change is necessary - to make these functions consistent across the entire codebase, but as this changes default values, - new data might have a different fill value than expected after this change. - - For data types where 0 is meaningful, like integers or floats, the default scalar is 0, so this - change should not be noticeable. For data types where 0 is ambiguous, like fixed-length unicode - strings, the default fill value might be different after this change. Users who were relying on how - Zarr interpreted `0` as a non-numeric scalar value should set their desired fill value explicitly - after this change. + [`zarr.api.synchronous.create_array`][] now takes a `write_data` keyword argument + The `Group.create_array` method takes `data` and `write_data` keyword arguments. + The functions [`zarr.api.asynchronous.create`][], [`zarr.api.asynchronous.create_array`] + and the methods `Group.create_array`, `Group.array`, had the default + `fill_value` changed from `0` to the `DEFAULT_FILL_VALUE` value, which instructs Zarr to + use the default scalar value associated with the array's data type as the fill value. These are + all functions or methods for array creation that mirror, wrap or are wrapped by, another function + that already has a default `fill_value` set to `DEFAULT_FILL_VALUE`. This change is necessary + to make these functions consistent across the entire codebase, but as this changes default values, + new data might have a different fill value than expected after this change. + + For data types where 0 is meaningful, like integers or floats, the default scalar is 0, so this + change should not be noticeable. For data types where 0 is ambiguous, like fixed-length unicode + strings, the default fill value might be different after this change. Users who were relying on how + Zarr interpreted `0` as a non-numeric scalar value should set their desired fill value explicitly + after this change. - Added public API for Buffer ABCs and implementations. - Use `zarr.buffer` to access buffer implementations, and - `zarr.abc.buffer` for the interface to implement new buffer types. + Use `zarr.buffer` to access buffer implementations, and + `zarr.abc.buffer` for the interface to implement new buffer types. - Users previously importing buffer from `zarr.core.buffer` should update their - imports to use `zarr.buffer`. As a reminder, all of `zarr.core` is - considered a private API that's not covered by zarr-python's versioning policy. ([#2871](https://github.com/zarr-developers/zarr-python/issues/2871)) + Users previously importing buffer from `zarr.core.buffer` should update their + imports to use `zarr.buffer`. As a reminder, all of `zarr.core` is + considered a private API that's not covered by zarr-python's versioning policy. ([#2871](https://github.com/zarr-developers/zarr-python/issues/2871)) - Adds zarr-specific data type classes. - This change adds a `ZDType` base class for Zarr V2 and Zarr V3 data types. Child classes are - defined for each NumPy data type. Each child class defines routines for `JSON` serialization. - New data types can be created and registered dynamically. + This change adds a `ZDType` base class for Zarr V2 and Zarr V3 data types. Child classes are + defined for each NumPy data type. Each child class defines routines for `JSON` serialization. + New data types can be created and registered dynamically. - Prior to this change, Zarr Python had two streams for handling data types. For Zarr V2 arrays, - we used NumPy data type identifiers. For Zarr V3 arrays, we used a fixed set of string enums. Both - of these systems proved hard to extend. + Prior to this change, Zarr Python had two streams for handling data types. For Zarr V2 arrays, + we used NumPy data type identifiers. For Zarr V3 arrays, we used a fixed set of string enums. Both + of these systems proved hard to extend. - This change is largely internal, but it does change the type of the `dtype` and `data_type` - fields on the `ArrayV2Metadata` and `ArrayV3Metadata` classes. Previously, `ArrayV2Metadata.dtype` - was a NumPy `dtype` object, and `ArrayV3Metadata.data_type` was an internally-defined `enum`. - After this change, both `ArrayV2Metadata.dtype` and `ArrayV3Metadata.data_type` are instances of - `ZDType`. A NumPy data type can be generated from a `ZDType` via the `ZDType.to_native_dtype()` - method. The internally-defined Zarr V3 `enum` class is gone entirely, but the `ZDType.to_json(zarr_format=3)` - method can be used to generate either a string, or dictionary that has a string `name` field, that - represents the string value previously associated with that `enum`. + This change is largely internal, but it does change the type of the `dtype` and `data_type` + fields on the `ArrayV2Metadata` and `ArrayV3Metadata` classes. Previously, `ArrayV2Metadata.dtype` + was a NumPy `dtype` object, and `ArrayV3Metadata.data_type` was an internally-defined `enum`. + After this change, both `ArrayV2Metadata.dtype` and `ArrayV3Metadata.data_type` are instances of + `ZDType`. A NumPy data type can be generated from a `ZDType` via the `ZDType.to_native_dtype()` + method. The internally-defined Zarr V3 `enum` class is gone entirely, but the `ZDType.to_json(zarr_format=3)` + method can be used to generate either a string, or dictionary that has a string `name` field, that + represents the string value previously associated with that `enum`. - For more on this new feature, see the [documentation](user-guide/data_types.md) ([#2874](https://github.com/zarr-developers/zarr-python/issues/2874)) + For more on this new feature, see the [documentation](user-guide/data_types.md) ([#2874](https://github.com/zarr-developers/zarr-python/pull/2874)) -- Added `NDBuffer.empty` method for faster ndbuffer initialization. ([#3191](https://github.com/zarr-developers/zarr-python/issues/3191)) +- Added `NDBuffer.empty` method for faster ndbuffer initialization. ([#3191](https://github.com/zarr-developers/zarr-python/pull/3191)) -- The minimum version of NumPy has increased to 1.26. ([#3226](https://github.com/zarr-developers/zarr-python/issues/3226)) +- The minimum version of NumPy has increased to 1.26. ([#3226](https://github.com/zarr-developers/zarr-python/pull/3226)) -- Add an alternate `from_array_metadata_and_store` constructor to `CodecPipeline`. ([#3233](https://github.com/zarr-developers/zarr-python/issues/3233)) +- Add an alternate `from_array_metadata_and_store` constructor to `CodecPipeline`. ([#3233](https://github.com/zarr-developers/zarr-python/pull/3233)) ### Bugfixes - Fixes a variety of issues related to string data types. - - Brings the `VariableLengthUTF8` data type Zarr V3 identifier in alignment with Zarr Python 3.0.8 - - Disallows creation of 0-length fixed-length data types - - Adds a regression test for the `VariableLengthUTF8` data type that checks against version 3.0.8 - - Allows users to request the `VariableLengthUTF8` data type with `str`, `"str"`, or `"string"`. ([#3170](https://github.com/zarr-developers/zarr-python/issues/3170)) + - Brings the `VariableLengthUTF8` data type Zarr V3 identifier in alignment with Zarr Python 3.0.8 + - Disallows creation of 0-length fixed-length data types + - Adds a regression test for the `VariableLengthUTF8` data type that checks against version 3.0.8 + - Allows users to request the `VariableLengthUTF8` data type with `str`, `"str"`, or `"string"`. ([#3170](https://github.com/zarr-developers/zarr-python/pull/3170)) -- Add human readable size for No. bytes stored to `info_complete` ([#3190](https://github.com/zarr-developers/zarr-python/issues/3190)) +- Add human readable size for No. bytes stored to `info_complete` ([#3190](https://github.com/zarr-developers/zarr-python/pull/3190)) - Restores the ability to create a Zarr V2 array with a `null` fill value by introducing a new class `DefaultFillValue`, and setting the default value of the `fill_value` parameter in array creation routines to an instance of `DefaultFillValue`. For Zarr V3 arrays, `None` will act as an - alias for a `DefaultFillValue` instance, thus preserving compatibility with existing code. ([#3198](https://github.com/zarr-developers/zarr-python/issues/3198)) + alias for a `DefaultFillValue` instance, thus preserving compatibility with existing code. ([#3198](https://github.com/zarr-developers/zarr-python/pull/3198)) - Fix the type of `ArrayV2Metadata.codec` to constrain it to `numcodecs.abc.Codec | None`. Previously the type was more permissive, allowing objects that can be parsed into Codecs (e.g., the codec name). - The constructor of `ArrayV2Metadata` still allows the permissive input when creating new objects. ([#3232](https://github.com/zarr-developers/zarr-python/issues/3232)) + The constructor of `ArrayV2Metadata` still allows the permissive input when creating new objects. ([#3232](https://github.com/zarr-developers/zarr-python/pull/3232)) ### Improved Documentation - Add a self-contained example of data type extension to the `examples` directory, and expanded - the documentation for data types. ([#3157](https://github.com/zarr-developers/zarr-python/issues/3157)) + the documentation for data types. ([#3157](https://github.com/zarr-developers/zarr-python/pull/3157)) - Add a description on how to create a RemoteStore of a specific filesystem to the `Remote Store` section in `docs/user-guide/storage.md`. State in the docstring of `FsspecStore.from_url` that the filesystem type is inferred from the URL scheme. - It should help a user handling the case when the type of FsspecStore doesn't match the URL scheme. ([#3212](https://github.com/zarr-developers/zarr-python/issues/3212)) + It should help a user handling the case when the type of FsspecStore doesn't match the URL scheme. ([#3212](https://github.com/zarr-developers/zarr-python/pull/3212)) ### Deprecations and Removals - Removes default chunk encoding settings (filters, serializer, compressors) from the global configuration object. - This removal is justified on the basis that storing chunk encoding settings in the config required - a brittle, confusing, and inaccurate categorization of array data types, which was particularly - unsuitable after the recent addition of new data types that didn't fit naturally into the - pre-existing categories. + This removal is justified on the basis that storing chunk encoding settings in the config required + a brittle, confusing, and inaccurate categorization of array data types, which was particularly + unsuitable after the recent addition of new data types that didn't fit naturally into the + pre-existing categories. - The default chunk encoding is the same (Zstandard compression, and the required object codecs for - variable length data types), but the chunk encoding is now generated by functions that cannot be - reconfigured at runtime. Users who relied on setting the default chunk encoding via the global configuration object should - instead specify the desired chunk encoding explicitly when creating an array. + The default chunk encoding is the same (Zstandard compression, and the required object codecs for + variable length data types), but the chunk encoding is now generated by functions that cannot be + reconfigured at runtime. Users who relied on setting the default chunk encoding via the global configuration object should + instead specify the desired chunk encoding explicitly when creating an array. - This change also adds an extra validation step to the creation of Zarr V2 arrays, which ensures that - arrays with a `VariableLengthUTF8` or `VariableLengthBytes` data type cannot be created without the - correct "object codec". ([#3228](https://github.com/zarr-developers/zarr-python/issues/3228)) + This change also adds an extra validation step to the creation of Zarr V2 arrays, which ensures that + arrays with a `VariableLengthUTF8` or `VariableLengthBytes` data type cannot be created without the + correct "object codec". ([#3228](https://github.com/zarr-developers/zarr-python/pull/3228)) - Removes support for passing keyword-only arguments positionally to the following functions and methods: `save_array`, `open`, `group`, `open_group`, `create`, `get_basic_selection`, `set_basic_selection`, @@ -241,27 +602,27 @@ ### Bugfixes - Removed an unnecessary check from `_fsspec._make_async` that would raise an exception when - creating a read-only store backed by a local file system with `auto_mkdir` set to `False`. ([#3193](https://github.com/zarr-developers/zarr-python/issues/3193)) + creating a read-only store backed by a local file system with `auto_mkdir` set to `False`. ([#3193](https://github.com/zarr-developers/zarr-python/pull/3193)) -- Add missing import for AsyncFileSystemWrapper for _make_async in _fsspec.py ([#3195](https://github.com/zarr-developers/zarr-python/issues/3195)) +- Add missing import for AsyncFileSystemWrapper for _make_async in _fsspec.py ([#3195](https://github.com/zarr-developers/zarr-python/pull/3195)) ## 3.0.9 (2025-06-30) ### Features -- Add `zarr.storage.FsspecStore.from_mapper()` so that `zarr.open()` supports stores of type `fsspec.mapping.FSMap`. ([#2774](https://github.com/zarr-developers/zarr-python/issues/2774)) +- Add `zarr.storage.FsspecStore.from_mapper()` so that `zarr.open()` supports stores of type `fsspec.mapping.FSMap`. ([#2774](https://github.com/zarr-developers/zarr-python/pull/2774)) -- Implemented `move` for `LocalStore` and `ZipStore`. This allows users to move the store to a different root path. ([#3021](https://github.com/zarr-developers/zarr-python/issues/3021)) +- Implemented `move` for `LocalStore` and `ZipStore`. This allows users to move the store to a different root path. ([#3021](https://github.com/zarr-developers/zarr-python/pull/3021)) -- Added `zarr.errors.GroupNotFoundError`, which is raised when attempting to open a group that does not exist. ([#3066](https://github.com/zarr-developers/zarr-python/issues/3066)) +- Added `zarr.errors.GroupNotFoundError`, which is raised when attempting to open a group that does not exist. ([#3066](https://github.com/zarr-developers/zarr-python/pull/3066)) -- Adds `fill_value` to the list of attributes displayed in the output of the `AsyncArray.info()` method. ([#3081](https://github.com/zarr-developers/zarr-python/issues/3081)) +- Adds `fill_value` to the list of attributes displayed in the output of the `AsyncArray.info()` method. ([#3081](https://github.com/zarr-developers/zarr-python/pull/3081)) -- Use `numpy.zeros` instead of `np.full` for a performance speedup when creating a `zarr.core.buffer.NDBuffer` with `fill_value=0`. ([#3082](https://github.com/zarr-developers/zarr-python/issues/3082)) +- Use `numpy.zeros` instead of `np.full` for a performance speedup when creating a `zarr.core.buffer.NDBuffer` with `fill_value=0`. ([#3082](https://github.com/zarr-developers/zarr-python/pull/3082)) -- Port more stateful testing actions from [Icechunk](https://icechunk.io). ([#3130](https://github.com/zarr-developers/zarr-python/issues/3130)) +- Port more stateful testing actions from [Icechunk](https://icechunk.io/en/stable/). ([#3130](https://github.com/zarr-developers/zarr-python/pull/3130)) -- Adds a `with_read_only` convenience method to the `Store` abstract base class (raises `NotImplementedError`) and implementations to the `MemoryStore`, `ObjectStore`, `LocalStore`, and `FsspecStore` classes. ([#3138](https://github.com/zarr-developers/zarr-python/issues/3138)) +- Adds a `with_read_only` convenience method to the `Store` abstract base class (raises `NotImplementedError`) and implementations to the `MemoryStore`, `ObjectStore`, `LocalStore`, and `FsspecStore` classes. ([#3138](https://github.com/zarr-developers/zarr-python/pull/3138)) ### Bugfixes @@ -269,31 +630,31 @@ - For Zarr format 2, allow fixed-length string arrays to be created without automatically inserting a `Vlen-UT8` codec in the array of filters. Fixed-length string arrays do not need this codec. This - change fixes a regression where fixed-length string arrays created with Zarr Python 3 could not be read with Zarr Python 2.18. ([#3100](https://github.com/zarr-developers/zarr-python/issues/3100)) + change fixes a regression where fixed-length string arrays created with Zarr Python 3 could not be read with Zarr Python 2.18. ([#3100](https://github.com/zarr-developers/zarr-python/pull/3100)) - When creating arrays without explicitly specifying a chunk size using `zarr.create` and other array creation routines, the chunk size will now set automatically instead of defaulting to the data shape. For large arrays this will result in smaller default chunk sizes. To retain previous behaviour, explicitly set the chunk shape to the data shape. - This fix matches the existing chunking behaviour of - `zarr.save_array` and `zarr.api.asynchronous.AsyncArray.create`. ([#3103](https://github.com/zarr-developers/zarr-python/issues/3103)) + This fix matches the existing chunking behaviour of + `zarr.save_array` and `zarr.api.asynchronous.AsyncArray.create`. ([#3103](https://github.com/zarr-developers/zarr-python/pull/3103)) - When `zarr.save` has an argument `path=some/path/` and multiple arrays in `args`, the path resulted in `some/path/some/path` due to using the `path` - argument twice while building the array path. This is now fixed. ([#3127](https://github.com/zarr-developers/zarr-python/issues/3127)) + argument twice while building the array path. This is now fixed. ([#3127](https://github.com/zarr-developers/zarr-python/pull/3127)) -- Fix `zarr.open` default for argument `mode` when `store` is `read_only` ([#3128](https://github.com/zarr-developers/zarr-python/issues/3128)) +- Fix `zarr.open` default for argument `mode` when `store` is `read_only` ([#3128](https://github.com/zarr-developers/zarr-python/pull/3128)) - Suppress `FileNotFoundError` when deleting non-existent keys in the `obstore` adapter. - When writing empty chunks (i.e. chunks where all values are equal to the array's fill value) to a zarr array, zarr - will delete those chunks from the underlying store. For zarr arrays backed by the `obstore` adapter, this will potentially - raise a `FileNotFoundError` if the chunk doesn't already exist. - Since whether or not a delete of a non-existing object raises an error depends on the behavior of the underlying store, - suppressing the error in all cases results in consistent behavior across stores, and is also what `zarr` seems to expect - from the store. ([#3140](https://github.com/zarr-developers/zarr-python/issues/3140)) + When writing empty chunks (i.e. chunks where all values are equal to the array's fill value) to a zarr array, zarr + will delete those chunks from the underlying store. For zarr arrays backed by the `obstore` adapter, this will potentially + raise a `FileNotFoundError` if the chunk doesn't already exist. + Since whether or not a delete of a non-existing object raises an error depends on the behavior of the underlying store, + suppressing the error in all cases results in consistent behavior across stores, and is also what `zarr` seems to expect + from the store. ([#3140](https://github.com/zarr-developers/zarr-python/pull/3140)) -- Trying to open a StorePath/Array with `mode='r'` when the store is not read-only creates a read-only copy of the store. ([#3156](https://github.com/zarr-developers/zarr-python/issues/3156)) +- Trying to open a StorePath/Array with `mode='r'` when the store is not read-only creates a read-only copy of the store. ([#3156](https://github.com/zarr-developers/zarr-python/pull/3156)) ## 3.0.8 (2025-05-19) @@ -303,196 +664,197 @@ ### Features -- Added a `print_debug_info` function for bug reports. ([#2913](https://github.com/zarr-developers/zarr-python/issues/2913)) +- Added a `print_debug_info` function for bug reports. ([#2913](https://github.com/zarr-developers/zarr-python/pull/2913)) ### Bugfixes -- Fix a bug that prevented the number of initialized chunks being counted properly. ([#2862](https://github.com/zarr-developers/zarr-python/issues/2862)) -- Fixed sharding with GPU buffers. ([#2978](https://github.com/zarr-developers/zarr-python/issues/2978)) +- Fix a bug that prevented the number of initialized chunks being counted properly. ([#2862](https://github.com/zarr-developers/zarr-python/pull/2862)) +- Fixed sharding with GPU buffers. ([#2978](https://github.com/zarr-developers/zarr-python/pull/2978)) - Fix structured `dtype` fill value serialization for consolidated metadata ([#2998](https://github.com/zarr-developers/zarr-python/issues/2998)) - It is now possible to specify no compressor when creating a zarr format 2 array. This can be done by passing `compressor=None` to the various array creation routines. - The default behaviour of automatically choosing a suitable default compressor remains if the compressor argument is not given. - To reproduce the behaviour in previous zarr-python versions when `compressor=None` was passed, pass `compressor='auto'` instead. ([#3039](https://github.com/zarr-developers/zarr-python/issues/3039)) -- Fixed the typing of `dimension_names` arguments throughout so that it now accepts iterables that contain `None` alongside `str`. ([#3045](https://github.com/zarr-developers/zarr-python/issues/3045)) -- Using various functions to open data with `mode='a'` no longer deletes existing data in the store. ([#3062](https://github.com/zarr-developers/zarr-python/issues/3062)) -- Internally use `typesize` constructor parameter for `numcodecs.blosc.Blosc` to improve compression ratios back to the v2-package levels. ([#2962](https://github.com/zarr-developers/zarr-python/issues/2962)) + The default behaviour of automatically choosing a suitable default compressor remains if the compressor argument is not given. + To reproduce the behaviour in previous zarr-python versions when `compressor=None` was passed, pass `compressor='auto'` instead. ([#3039](https://github.com/zarr-developers/zarr-python/pull/3039)) + +- Fixed the typing of `dimension_names` arguments throughout so that it now accepts iterables that contain `None` alongside `str`. ([#3045](https://github.com/zarr-developers/zarr-python/pull/3045)) +- Using various functions to open data with `mode='a'` no longer deletes existing data in the store. ([#3062](https://github.com/zarr-developers/zarr-python/pull/3062)) +- Internally use `typesize` constructor parameter for `numcodecs.blosc.Blosc` to improve compression ratios back to the v2-package levels. ([#2962](https://github.com/zarr-developers/zarr-python/pull/2962)) - Specifying the memory order of Zarr format 2 arrays using the `order` keyword argument has been fixed. ([#2950](https://github.com/zarr-developers/zarr-python/issues/2950)) ### Misc -- [#2972](https://github.com/zarr-developers/zarr-python/issues/2972), [#3027](https://github.com/zarr-developers/zarr-python/issues/3027), [#3049](https://github.com/zarr-developers/zarr-python/issues/3049) +- [#2972](https://github.com/zarr-developers/zarr-python/pull/2972), [#3027](https://github.com/zarr-developers/zarr-python/pull/3027), [#3049](https://github.com/zarr-developers/zarr-python/pull/3049) ## 3.0.7 (2025-04-22) ### Features -- Add experimental ObjectStore storage class based on obstore. ([#1661](https://github.com/zarr-developers/zarr-python/issues/1661)) -- Add `zarr.from_array` using concurrent streaming of source data ([#2622](https://github.com/zarr-developers/zarr-python/issues/2622)) +- Add experimental ObjectStore storage class based on obstore. ([#1661](https://github.com/zarr-developers/zarr-python/pull/1661)) +- Add `zarr.from_array` using concurrent streaming of source data ([#2622](https://github.com/zarr-developers/zarr-python/pull/2622)) ### Bugfixes - 0-dimensional arrays are now returning a scalar. Therefore, the return type of `__getitem__` changed to NDArrayLikeOrScalar. This change is to make the behavior of 0-dimensional arrays consistent with - `numpy` scalars. ([#2718](https://github.com/zarr-developers/zarr-python/issues/2718)) -- Fix `fill_value` serialization for `NaN` in `ArrayV2Metadata` and add property-based testing of round-trip serialization ([#2802](https://github.com/zarr-developers/zarr-python/issues/2802)) + `numpy` scalars. ([#2718](https://github.com/zarr-developers/zarr-python/pull/2718)) +- Fix `fill_value` serialization for `NaN` in `ArrayV2Metadata` and add property-based testing of round-trip serialization ([#2802](https://github.com/zarr-developers/zarr-python/pull/2802)) - Fixes `ConsolidatedMetadata` serialization of `nan`, `inf`, and `-inf` to be - consistent with the behavior of `ArrayMetadata`. ([#2996](https://github.com/zarr-developers/zarr-python/issues/2996)) + consistent with the behavior of `ArrayMetadata`. ([#2996](https://github.com/zarr-developers/zarr-python/pull/2996)) ### Improved Documentation -- Updated the 3.0 migration guide to include the removal of "." syntax for getting group members. ([#2991](https://github.com/zarr-developers/zarr-python/issues/2991), [#2997](https://github.com/zarr-developers/zarr-python/issues/2997)) +- Updated the 3.0 migration guide to include the removal of "." syntax for getting group members. ([#2991](https://github.com/zarr-developers/zarr-python/issues/2991), [#2997](https://github.com/zarr-developers/zarr-python/pull/2997)) ### Misc - Define a new versioning policy based on Effective Effort Versioning. This replaces the old Semantic - Versioning-based policy. ([#2924](https://github.com/zarr-developers/zarr-python/issues/2924), [#2910](https://github.com/zarr-developers/zarr-python/issues/2910)) + Versioning-based policy. ([#2924](https://github.com/zarr-developers/zarr-python/issues/2924), [#2910](https://github.com/zarr-developers/zarr-python/pull/2910)) - Make warning filters in the tests more specific, so warnings emitted by tests added in the future - are more likely to be caught instead of ignored. ([#2714](https://github.com/zarr-developers/zarr-python/issues/2714)) -- Avoid an unnecessary memory copy when writing Zarr to a local file ([#2944](https://github.com/zarr-developers/zarr-python/issues/2944)) + are more likely to be caught instead of ignored. ([#2714](https://github.com/zarr-developers/zarr-python/pull/2714)) +- Avoid an unnecessary memory copy when writing Zarr to a local file ([#2944](https://github.com/zarr-developers/zarr-python/pull/2944)) ## 3.0.6 (2025-03-20) ### Bugfixes -- Restore functionality of `del z.attrs['key']` to actually delete the key. ([#2908](https://github.com/zarr-developers/zarr-python/issues/2908)) +- Restore functionality of `del z.attrs['key']` to actually delete the key. ([#2908](https://github.com/zarr-developers/zarr-python/pull/2908)) ## 3.0.5 (2025-03-07) ### Bugfixes - Fixed a bug where `StorePath` creation would not apply standard path normalization to the `path` parameter, - which led to the creation of arrays and groups with invalid keys. ([#2850](https://github.com/zarr-developers/zarr-python/issues/2850)) -- Prevent update_attributes calls from deleting old attributes ([#2870](https://github.com/zarr-developers/zarr-python/issues/2870)) + which led to the creation of arrays and groups with invalid keys. ([#2850](https://github.com/zarr-developers/zarr-python/pull/2850)) +- Prevent update_attributes calls from deleting old attributes ([#2870](https://github.com/zarr-developers/zarr-python/pull/2870)) ### Misc -- [#2796](https://github.com/zarr-developers/zarr-python/issues/2796) +- [#2796](https://github.com/zarr-developers/zarr-python/pull/2796) ## 3.0.4 (2025-02-23) ### Features -- Adds functions for concurrently creating multiple arrays and groups. ([#2665](https://github.com/zarr-developers/zarr-python/issues/2665)) +- Adds functions for concurrently creating multiple arrays and groups. ([#2665](https://github.com/zarr-developers/zarr-python/pull/2665)) ### Bugfixes -- Fixed a bug where `ArrayV2Metadata` could save `filters` as an empty array. ([#2847](https://github.com/zarr-developers/zarr-python/issues/2847)) -- Fix a bug when setting values of a smaller last chunk. ([#2851](https://github.com/zarr-developers/zarr-python/issues/2851)) +- Fixed a bug where `ArrayV2Metadata` could save `filters` as an empty array. ([#2847](https://github.com/zarr-developers/zarr-python/pull/2847)) +- Fix a bug when setting values of a smaller last chunk. ([#2851](https://github.com/zarr-developers/zarr-python/pull/2851)) ### Misc -- [#2828](https://github.com/zarr-developers/zarr-python/issues/2828) +- [#2828](https://github.com/zarr-developers/zarr-python/pull/2828) ## 3.0.3 (2025-02-14) ### Features -- Improves performance of FsspecStore.delete_dir for remote filesystems supporting concurrent/batched deletes, e.g., s3fs. ([#2661](https://github.com/zarr-developers/zarr-python/issues/2661)) -- Added `zarr.config.enable_gpu` to update Zarr's configuration to use GPUs. ([#2751](https://github.com/zarr-developers/zarr-python/issues/2751)) -- Avoid reading chunks during writes where possible. [#757](https://github.com/zarr-developers/zarr-python/issues/757) ([#2784](https://github.com/zarr-developers/zarr-python/issues/2784)) -- `LocalStore` learned to `delete_dir`. This makes array and group deletes more efficient. ([#2804](https://github.com/zarr-developers/zarr-python/issues/2804)) -- Add `zarr.testing.strategies.array_metadata` to generate ArrayV2Metadata and ArrayV3Metadata instances. ([#2813](https://github.com/zarr-developers/zarr-python/issues/2813)) -- Add arbitrary `shards` to Hypothesis strategy for generating arrays. ([#2822](https://github.com/zarr-developers/zarr-python/issues/2822)) +- Improves performance of FsspecStore.delete_dir for remote filesystems supporting concurrent/batched deletes, e.g., s3fs. ([#2661](https://github.com/zarr-developers/zarr-python/pull/2661)) +- Added `zarr.config.enable_gpu` to update Zarr's configuration to use GPUs. ([#2751](https://github.com/zarr-developers/zarr-python/pull/2751)) +- Avoid reading chunks during writes where possible. [#757](https://github.com/zarr-developers/zarr-python/issues/757) ([#2784](https://github.com/zarr-developers/zarr-python/pull/2784)) +- `LocalStore` learned to `delete_dir`. This makes array and group deletes more efficient. ([#2804](https://github.com/zarr-developers/zarr-python/pull/2804)) +- Add `zarr.testing.strategies.array_metadata` to generate ArrayV2Metadata and ArrayV3Metadata instances. ([#2813](https://github.com/zarr-developers/zarr-python/pull/2813)) +- Add arbitrary `shards` to Hypothesis strategy for generating arrays. ([#2822](https://github.com/zarr-developers/zarr-python/pull/2822)) ### Bugfixes -- Fixed bug with Zarr using device memory, instead of host memory, for storing metadata when using GPUs. ([#2751](https://github.com/zarr-developers/zarr-python/issues/2751)) +- Fixed bug with Zarr using device memory, instead of host memory, for storing metadata when using GPUs. ([#2751](https://github.com/zarr-developers/zarr-python/pull/2751)) - The array returned by `zarr.empty` and an empty `zarr.core.buffer.cpu.NDBuffer` will now be filled with the specified fill value, or with zeros if no fill value is provided. - This fixes a bug where Zarr format 2 data with no fill value was written with un-predictable chunk sizes. ([#2755](https://github.com/zarr-developers/zarr-python/issues/2755)) -- Fix zip-store path checking for stores with directories listed as files. ([#2758](https://github.com/zarr-developers/zarr-python/issues/2758)) -- Use removeprefix rather than replace when removing filename prefixes in `FsspecStore.list` ([#2778](https://github.com/zarr-developers/zarr-python/issues/2778)) -- Enable automatic removal of `needs release notes` with labeler action ([#2781](https://github.com/zarr-developers/zarr-python/issues/2781)) -- Use the proper label config ([#2785](https://github.com/zarr-developers/zarr-python/issues/2785)) -- Alters the behavior of `create_array` to ensure that any groups implied by the array's name are created if they do not already exist. Also simplifies the type signature for any function that takes an ArrayConfig-like object. ([#2795](https://github.com/zarr-developers/zarr-python/issues/2795)) -- Enitialise empty chunks to the default fill value during writing and add default fill values for datetime, timedelta, structured, and other (void* fixed size) data types ([#2799](https://github.com/zarr-developers/zarr-python/issues/2799)) -- Ensure utf8 compliant strings are used to construct numpy arrays in property-based tests ([#2801](https://github.com/zarr-developers/zarr-python/issues/2801)) -- Fix pickling for ZipStore ([#2807](https://github.com/zarr-developers/zarr-python/issues/2807)) -- Update numcodecs to not overwrite codec configuration ever. Closes [#2800](https://github.com/zarr-developers/zarr-python/issues/2800). ([#2811](https://github.com/zarr-developers/zarr-python/issues/2811)) -- Fix fancy indexing (e.g. arr[5, [0, 1]]) with the sharding codec ([#2817](https://github.com/zarr-developers/zarr-python/issues/2817)) + This fixes a bug where Zarr format 2 data with no fill value was written with un-predictable chunk sizes. ([#2755](https://github.com/zarr-developers/zarr-python/pull/2755)) +- Fix zip-store path checking for stores with directories listed as files. ([#2758](https://github.com/zarr-developers/zarr-python/pull/2758)) +- Use removeprefix rather than replace when removing filename prefixes in `FsspecStore.list` ([#2778](https://github.com/zarr-developers/zarr-python/pull/2778)) +- Enable automatic removal of `needs release notes` with labeler action ([#2781](https://github.com/zarr-developers/zarr-python/pull/2781)) +- Use the proper label config ([#2785](https://github.com/zarr-developers/zarr-python/pull/2785)) +- Alters the behavior of `create_array` to ensure that any groups implied by the array's name are created if they do not already exist. Also simplifies the type signature for any function that takes an ArrayConfig-like object. ([#2795](https://github.com/zarr-developers/zarr-python/pull/2795)) +- Enitialise empty chunks to the default fill value during writing and add default fill values for datetime, timedelta, structured, and other (void* fixed size) data types ([#2799](https://github.com/zarr-developers/zarr-python/pull/2799)) +- Ensure utf8 compliant strings are used to construct numpy arrays in property-based tests ([#2801](https://github.com/zarr-developers/zarr-python/pull/2801)) +- Fix pickling for ZipStore ([#2807](https://github.com/zarr-developers/zarr-python/pull/2807)) +- Update numcodecs to not overwrite codec configuration ever. Closes [#2800](https://github.com/zarr-developers/zarr-python/issues/2800). ([#2811](https://github.com/zarr-developers/zarr-python/pull/2811)) +- Fix fancy indexing (e.g. arr[5, [0, 1]]) with the sharding codec ([#2817](https://github.com/zarr-developers/zarr-python/pull/2817)) ### Improved Documentation -- Added new user guide on GPU. ([#2751](https://github.com/zarr-developers/zarr-python/issues/2751)) +- Added new user guide on GPU. ([#2751](https://github.com/zarr-developers/zarr-python/pull/2751)) ## 3.0.2 (2025-01-31) ### Features -- Test `getsize()` and `getsize_prefix()` in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Test that a `ValueError` is raised for invalid byte range syntax in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Separate instantiating and opening a store in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Add a test for using Stores as a context managers in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Implemented `LogingStore.open()`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- `LoggingStore` is now a generic class. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) +- Test `getsize()` and `getsize_prefix()` in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Test that a `ValueError` is raised for invalid byte range syntax in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Separate instantiating and opening a store in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Add a test for using Stores as context managers in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Implemented `LoggingStore.open()`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- `LoggingStore` is now a generic class. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) - Change StoreTest's `test_store_repr`, `test_store_supports_writes`, `test_store_supports_partial_writes`, and `test_store_supports_listing` - to to be implemented using `@abstractmethod`, rather raising `NotImplementedError`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Test the error raised for invalid buffer arguments in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Test that data can be written to a store that's not yet open using the store.set method in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) + to be implemented using `@abstractmethod`, rather than raising `NotImplementedError`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Test the error raised for invalid buffer arguments in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Test that data can be written to a store that's not yet open using the store.set method in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) - Adds a new function `init_array` for initializing an array in storage, and refactors `create_array` to use `init_array`. `create_array` takes two new parameters: `data`, an optional array-like object, and `write_data`, a bool which defaults to `True`. If `data` is given to `create_array`, then the `dtype` and `shape` attributes of `data` are used to define the - corresponding attributes of the resulting Zarr array. Additionally, if `data` given and `write_data` is `True`, - then the values in `data` will be written to the newly created array. ([#2761](https://github.com/zarr-developers/zarr-python/issues/2761)) + corresponding attributes of the resulting Zarr array. Additionally, if `data` is given and `write_data` is `True`, + then the values in `data` will be written to the newly created array. ([#2761](https://github.com/zarr-developers/zarr-python/pull/2761)) ### Bugfixes -- Wrap sync fsspec filesystems with `AsyncFileSystemWrapper`. ([#2533](https://github.com/zarr-developers/zarr-python/issues/2533)) -- Added backwards compatibility for Zarr format 2 structured arrays. ([#2681](https://github.com/zarr-developers/zarr-python/issues/2681)) -- Update equality for `LoggingStore` and `WrapperStore` such that 'other' must also be a `LoggingStore` or `WrapperStore` respectively, rather than only checking the types of the stores they wrap. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Ensure that `ZipStore` is open before getting or setting any values. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Use stdout rather than stderr as the default stream for `LoggingStore`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) -- Match the errors raised by read only stores in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/issues/2693)) +- Wrap sync fsspec filesystems with `AsyncFileSystemWrapper`. ([#2533](https://github.com/zarr-developers/zarr-python/pull/2533)) +- Added backwards compatibility for Zarr format 2 structured arrays. ([#2681](https://github.com/zarr-developers/zarr-python/pull/2681)) +- Update equality for `LoggingStore` and `WrapperStore` such that 'other' must also be a `LoggingStore` or `WrapperStore` respectively, rather than only checking the types of the stores they wrap. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Ensure that `ZipStore` is open before getting or setting any values. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Use stdout rather than stderr as the default stream for `LoggingStore`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Match the errors raised by read only stores in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) - Fixed `ZipStore` to make sure the correct attributes are saved when instances are pickled. - This fixes a previous bug that prevent using `ZipStore` with a `ProcessPoolExecutor`. ([#2762](https://github.com/zarr-developers/zarr-python/issues/2762)) -- Updated the optional test dependencies to include `botocore` and `fsspec`. ([#2768](https://github.com/zarr-developers/zarr-python/issues/2768)) + This fixes a previous bug that prevented using `ZipStore` with a `ProcessPoolExecutor`. ([#2762](https://github.com/zarr-developers/zarr-python/pull/2762)) +- Updated the optional test dependencies to include `botocore` and `fsspec`. ([#2768](https://github.com/zarr-developers/zarr-python/pull/2768)) - Fixed the fsspec tests to skip if `botocore` is not installed. - Previously they would have failed with an import error. ([#2768](https://github.com/zarr-developers/zarr-python/issues/2768)) -- Optimize full chunk writes. ([#2782](https://github.com/zarr-developers/zarr-python/issues/2782)) + Previously they would have failed with an import error. ([#2768](https://github.com/zarr-developers/zarr-python/pull/2768)) +- Optimize full chunk writes. ([#2782](https://github.com/zarr-developers/zarr-python/pull/2782)) ### Improved Documentation - Changed the machinery for creating changelog entries. - Now individual entries should be added as files to the `changes` directory in the `zarr-python` repository, instead of directly to the changelog file. ([#2736](https://github.com/zarr-developers/zarr-python/issues/2736)) + Now individual entries should be added as files to the `changes` directory in the `zarr-python` repository, instead of directly to the changelog file. ([#2736](https://github.com/zarr-developers/zarr-python/pull/2736)) ### Other - Created a type alias `ChunkKeyEncodingLike` to model the union of `ChunkKeyEncoding` instances and the dict form of the parameters of those instances. `ChunkKeyEncodingLike` should be used by high-level functions to provide a convenient - way for creating `ChunkKeyEncoding` objects. ([#2763](https://github.com/zarr-developers/zarr-python/issues/2763)) + way for creating `ChunkKeyEncoding` objects. ([#2763](https://github.com/zarr-developers/zarr-python/pull/2763)) -## 3.0.1 (Jan. 17, 2025) +## 3.0.1 (2025-01-17) -* Implement `zarr.from_array` using concurrent streaming ([#2622](https://github.com/zarr-developers/zarr-python/issues/2622)). +* Implement `zarr.from_array` using concurrent streaming ([#2622](https://github.com/zarr-developers/zarr-python/pull/2622)). ### Bug fixes -* Fixes `order` argument for Zarr format 2 arrays ([#2679](https://github.com/zarr-developers/zarr-python/issues/2679)). +* Fixes `order` argument for Zarr format 2 arrays ([#2679](https://github.com/zarr-developers/zarr-python/pull/2679)). * Fixes a bug that prevented reading Zarr format 2 data with consolidated metadata written using `zarr-python` version 2 ([#2694](https://github.com/zarr-developers/zarr-python/issues/2694)). * Ensure that compressor=None results in no compression when writing Zarr format 2 data ([#2708](https://github.com/zarr-developers/zarr-python/issues/2708)). * Fix for empty consolidated metadata dataset: backwards compatibility with - Zarr-Python 2 ([#2695](https://github.com/zarr-developers/zarr-python/issues/2695)). + Zarr-Python 2 ([#2695](https://github.com/zarr-developers/zarr-python/pull/2695)). ### Documentation -* Add v3.0.0 release announcement banner ([#2677](https://github.com/zarr-developers/zarr-python/issues/2677)). -* Quickstart guide alignment with V3 API ([#2697](https://github.com/zarr-developers/zarr-python/issues/2697)). -* Fix doctest failures related to numcodecs 0.15 ([#2727](https://github.com/zarr-developers/zarr-python/issues/2727)). +* Add v3.0.0 release announcement banner ([#2677](https://github.com/zarr-developers/zarr-python/pull/2677)). +* Quickstart guide alignment with V3 API ([#2697](https://github.com/zarr-developers/zarr-python/pull/2697)). +* Fix doctest failures related to numcodecs 0.15 ([#2727](https://github.com/zarr-developers/zarr-python/pull/2727)). ### Other * Removed some unnecessary files from the source distribution - to reduce its size. ([#2686](https://github.com/zarr-developers/zarr-python/issues/2686)). -* Enable codecov in GitHub actions ([#2682](https://github.com/zarr-developers/zarr-python/issues/2682)). -* Speed up hypothesis tests ([#2650](https://github.com/zarr-developers/zarr-python/issues/2650)). -* Remove multiple imports for an import name ([#2723](https://github.com/zarr-developers/zarr-python/issues/2723)). + to reduce its size. ([#2686](https://github.com/zarr-developers/zarr-python/pull/2686)). +* Enable codecov in GitHub actions ([#2682](https://github.com/zarr-developers/zarr-python/pull/2682)). +* Speed up hypothesis tests ([#2650](https://github.com/zarr-developers/zarr-python/pull/2650)). +* Remove multiple imports for an import name ([#2723](https://github.com/zarr-developers/zarr-python/pull/2723)). -## 3.0.0 (Jan. 9, 2025) +## 3.0.0 (2025-01-09) 3.0.0 is a new major release of Zarr-Python, with many breaking changes. See the [v3 migration guide](user-guide/v3_migration.md) for a listing of what's changed. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000000..4b5dbc4599 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,189 @@ +# Roadmap + +This page describes where Zarr-Python is headed: the goals for the next major +cycle of work, the changes we intend to make, and how those changes will be +released. It is a living document; discussion and counter-proposals are welcome +on the +[Zarr-Python issue tracker](https://github.com/zarr-developers/zarr-python/issues). + +*The history of this roadmap, including the detailed technical proposals it +was distilled from, can be traced in the +[zarr-python-planning](https://github.com/zarr-developers/zarr-python-planning) +repository.* + +!!! note + + This roadmap reflects the current thinking of the core developers. It is a + statement of direction, not a schedule. We don't know how long these changes + will take, only that we are committed to moving the project in the direction outlined + here. + +## Where we are + +The [3.0 release](https://github.com/zarr-developers/zarr-python/releases/tag/v3.0.0) +was a total redesign of the library's internals, with three goals: full support +for the Zarr V2 and V3 storage formats, storage APIs that are ergonomic for high-latency +storage (such as cloud storage), and backwards compatibility with Zarr-Python 2.x where +possible. Those goals were largely achieved! Going by the content of issues and pull requests +submitted to the library, few users are grappling with 2.x → 3.x migration issues. Instead, we see +users asking for things like better APIs, where "better" usually means faster. + +The 3.x redesign was carried out under hard backwards-compatibility +constraints, and it inherited many structural patterns from the 2.x +implementation it replaced. The library has never had a release cycle whose +primary goal was the *shape* of the internals. The next body of work — which we +call **"v4"** — is that overdue investment. We think iterating on the internals of +the library will make it *much* easier to bring faster, more expressive APIs to Zarr-Python +users. + +## Goals + +If the 3.0 goals could be sloganized as "migrate to Zarr V3, and improve cloud +storage support", the slogan for the v4 goals is: +**"a frictionless Zarr-based Python ecosystem for chunked arrays"**. Zarr-Python +should be *foundational* for the growing number of Python packages that work +with data in the Zarr format. Concretely, that means pushing in these +directions: + +- Deliver excellent performance, out of the box, while retaining maintainability. +- Make Zarr-Python APIs ergonomic and useful for developers. +- Expand our scope to cover vital quality-of-life routines like data copying, + rechunking, and the like. +- Ease the growth of Python tools across all levels of the Zarr stack. +- Accelerate the implementation of new codecs, chunk grids, chunk key + encodings, etc. + +An important design input: [`zarrs`](https://github.com/zarrs/zarrs) (Rust) and +[TensorStore](https://github.com/google/tensorstore) (C++) are two independent +Zarr implementations that use architectural patterns we want to learn from. +We see them as complementary rather than competitive. + +!!! note + + Many of the features in this roadmap will not require breaking public 3.x APIs. We can and will + ship those features in 3.x releases; at the same time, we consider it clarifying to frame the + coherent development direction as vectored at a 4.0 milestone. + +## The Zarr stack + +Different applications need different levels of Zarr support: a convention +validator only needs to read metadata documents; a visualization tool may only +need read-only array access; other tools need everything. We think of this as a +"Zarr stack", from most abstract to most concrete: + +1. **Conventions** — application and/or domain-specific schemas built on top of Zarr (OME-NGFF, + GeoZarr, anndata-zarr, multiscales). +2. **Groups** — Zarr hierarchies, traversal, group-level attributes. +3. **Arrays** — the user-facing array object, plus indexing and slicing. +4. **Chunk decoding** — the codec pipeline. +5. **Chunk addressing** — chunk grids and key encodings that map array + coordinates to store keys. +6. **Stores** — the key-value layer. +7. **Metadata** — pure data documents describing arrays and groups. + +Today, Zarr-Python is a monolith that serves every level: a consumer who only +needs metadata handling has to install the full dependency footprint of the +whole library, and a faster chunk-decoding implementation cannot plug in +without re-implementing the layers above it. The v4 direction is to re-shape +Zarr-Python around the stack, so that each level is something you can depend +on, conform to, or replace, without buying every other level. + +We plan to "stackify" Zarr-Python by spinning core functionality out into separate Python packages, e.g. `zarr-metadata`, `zarr-indexing`, `zarr-storage`, +`zarr-codec`, `zarr-dtype`, each with narrow scope, all composed in the `zarr` package. The Rust `zarrs` library +successfully uses a structure like this, and we are keen to share the benefits of a more modular, maintainable codebase. Two of these subpackages, +[`zarr-metadata`](https://zarr.readthedocs.io/projects/zarr-metadata/en/latest/) and [`zarr-indexing`](https://zarr.readthedocs.io/projects/zarr-indexing/en/latest/), are already +published. + +## What we intend to change + +The following section details how we want to evolve the internal logic that drives Zarr-Python. + +### Foundation: swappable backends + +We propose to refactor Zarr-Python internals around a *swappable engine* — a protocol, or protocols, +that define the core routines a Zarr implementation must support. Zarr-Python becomes one user-facing +API that can be driven by multiple backends, including externally defined backends. We think this will allow users on many different platforms to get the best performance for their particular environment while retaining a familiar API. + +#### Rust bindings + +We want a Python backend (i.e., the status quo), but also a Rust-based backend, via bindings to the +[`zarrs`](https://docs.rs/zarrs/latest/zarrs/) crate. The [zarrs-python](https://zarrs-python.readthedocs.io/en/latest/) project demonstrates that +bridging `zarrs` and Zarr-Python buys a *lot* of performance in the specific case of chunk encoding. But zarrs-python is constrained today by limited +modularity in Zarr-Python internals. Refactoring our internals around swappable backends should address this limitation. + +Any Python package that interfaces with `zarrs` will need Pythonic bindings to the Rust library. So we are *very* excited about the [zarrista](https://developmentseed.org/zarrista/latest/) package, which aims to provide complete Python bindings for `zarrs`. + +#### Sync / Async partitioning + +Internally we will branch over two kinds of backends: synchronous and asynchronous. The synchronous backend is suitable for arrays and groups persisted to low-latency storage like in-memory stores or local file systems, where async scheduling is pure friction. The asynchronous backend will use Python's `async` support and will provide concurrent APIs where it helps: for arrays and groups persisted to high-latency storage. + +### Lazy indexing + +The Zarr-Python Array API was initially designed to mirror NumPy, with eager +array indexing syntax. `Array.__getitem__` performs IO eagerly and returns a NumPy array. +That was helpful to the dominant use-case at the time of its creation, but it +means deferred IO and computation currently require an external library +such as Dask. It means there is no built-in support for representing multi-step +reads as a single deferred plan. Further, it means that every chained +selection round-trips to storage independently. + +We can fix this by introducing an API for lazy indexing. Under this model, an array indexing operation +like `array[::2]` desugars to a declarative state like `(array, selection)`. Chained selections like +`array[10:100][::2]` are fused immediately, and we defer actual IO for the time when the result of +indexing is needed. [TensorStore](https://google.github.io/tensorstore/) is an excellent role model +for Zarr-Python here, and we can deliver this functionality without breaking ordinary indexing behavior. +See this [discussion](https://github.com/zarr-developers/zarr-python/discussions/1603) for more +background. + +### Data types + +First-class support for ML-specific dtypes — `bfloat16`, the `float8` +variants, packed `int4`/`uint4` — via +[`ml_dtypes`](https://github.com/jax-ml/ml_dtypes). These data types have specifications written up in `zarr-extensions`, but there's no simple to get them integrated in Zarr-Python today. + +### Device-agnostic IO + +Make Zarr-Python's IO surfaces device-agnostic rather than adding GPU support +as a bolted-on feature: stores and codecs grow APIs for writing into a +caller-provided buffer (`read_into`, `decode_into`), and the `Array` facade +returns array-like objects in the user's chosen Array API namespace. GPU +support falls out once the assumption of CPU destinations is removed, and CPU +paths get faster too, because pre-allocated output buffers eliminate per-chunk +allocation. + +### Configuration, registries, and plugins + +Move configuration from "global mutable state read implicitly" to "typed data +passed explicitly": a typed config object replacing the untyped global `donfig` +dict, array-scoped runtime config passed at open time, a registry redesign that +addresses implementations by stable identity and resolves plugin name-conflicts +deliberately, and named profiles replacing global mutators. + +### Coordinated and distributed writes + +This area is actually an unfinished aspect of the 2.x → 3.0 migration: Zarr-Python 2.x supported +synchronization logic via file-based locks, and we have not implemented equivalent functionality in +3.x. We don't have *concrete* plans for closing this gap. Re-implementing simple object-based locking, for +backends that support it, is a direct solution we should consider. But a transactional storage model, +where a sequence of basic storage operations like reading and writing could be submitted in a batch and +executed serially, with rollbacks under failure, is also quite appealing. +As with array indexing, TensorStore is the trailblazer here, and we can learn from its example. + +We can also avoid the need for synchronization mechanisms entirely with better planning. +Many users of the 2.x synchronization tooling needed to simply write values from one chunked source +to another, without worrying about chunk alignment. This can be addressed e.g. by creating a write +plan that partitions the input chunks into batches within which writes cannot race. + +## How to get involved + +- **Discuss the plans.** Comments and counter-proposals on any of the themes + above are welcome on the + [issue tracker](https://github.com/zarr-developers/zarr-python/issues) and in + the [developer chat](https://ossci.zulipchat.com/). +- **Review in-flight work.** The `IndexTransform` algebra that lazy indexing is + built on is in review at + [#3906](https://github.com/zarr-developers/zarr-python/pull/3906). +- **Weigh in as a downstream maintainer.** If your project's use of + Zarr-Python would be affected by the codec API rewrite, the stores rewrite, + or the lazy-indexing work, the planning phase is the time to surface + workloads or patterns that don't fit. diff --git a/docs/subprojects.md b/docs/subprojects.md new file mode 100644 index 0000000000..9f7951e836 --- /dev/null +++ b/docs/subprojects.md @@ -0,0 +1,45 @@ +# Subprojects + +Alongside `zarr` itself, the +[zarr-python repository](https://github.com/zarr-developers/zarr-python) hosts a +small number of companion packages. Each one is developed in the same repository +but versioned, released, and documented independently, so you can depend on it +without taking on `zarr` as a dependency. + +
+ +- [:material-code-json:{ .lg .middle } __zarr-metadata__](https://zarr.readthedocs.io/projects/zarr-metadata/) + + --- + + Spec-defined metadata types, models, and validators for Zarr v2 and v3, with + minimal dependencies. Useful if your software reads or writes Zarr metadata + documents but does not need a full Zarr implementation. + + ```bash + pip install zarr-metadata + ``` + +- [:material-vector-polyline:{ .lg .middle } __zarr-indexing__](https://zarr.readthedocs.io/projects/zarr-indexing/) + + --- + + Composable, lazy coordinate transforms for Zarr array indexing. Makes the + mapping from requested coordinates to stored coordinates a first-class, + composable value, and resolves which chunks a selection touches. + + ```bash + pip install zarr-indexing + ``` + +- [:material-server:{ .lg .middle } __zarr-http-server__](https://zarr.readthedocs.io/projects/zarr-http-server/) + + --- + + HTTP server for Zarr stores, arrays, and groups. + + ```bash + pip install zarr-http-server + ``` + +
diff --git a/docs/user-guide/arrays.md b/docs/user-guide/arrays.md index a44c096b73..a192845f9e 100644 --- a/docs/user-guide/arrays.md +++ b/docs/user-guide/arrays.md @@ -8,26 +8,27 @@ Zarr has several functions for creating arrays. For example: import shutil shutil.rmtree('data', ignore_errors=True) import numpy as np - -np.random.seed(0) ``` ```python exec="true" session="arrays" source="above" result="ansi" import zarr -store = zarr.storage.MemoryStore() -z = zarr.create_array(store=store, shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +z = zarr.create_array(store="memory://arrays-demo", shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') print(z) ``` The code above creates a 2-dimensional array of 32-bit integers with 10000 rows and 10000 columns, divided into chunks where each chunk has 1000 rows and 1000 -columns (and so there will be 100 chunks in total). The data is written to a -[`zarr.storage.MemoryStore`][] (e.g. an in-memory dict). See -[Persistent arrays](#persistent-arrays) for details on storing arrays in other stores, -and see [Data types](data_types.md) for an in-depth look at the data types supported -by Zarr. - -See the [creation API documentation](../api/zarr/create.md) for more detailed information about +columns (and so there will be 100 chunks in total). The data is written to an +in-memory store: when `fsspec` is installed, a `memory://` URL resolves to a +[`zarr.storage.FsspecStore`][] backed by fsspec's in-memory filesystem; otherwise a +[`zarr.storage.ManagedMemoryStore`][] is used. See the [Storage guide](storage.md) +for more details on stores, and +[Persistent arrays](#persistent-arrays) for details on storing arrays in other stores. +See [Data types](data_types.md) for an in-depth look at the data types supported +by Zarr, and [Chunk size and shape](performance.md#chunk-size-and-shape) in the +performance guide for guidance on choosing chunk shapes. + +See the [`zarr.create_array`][] API documentation for more detailed information about creating arrays. ## Reading and writing data @@ -129,7 +130,7 @@ A Zarr array can be resized, which means that any of its dimensions can be increased or decreased in length. For example: ```python exec="true" session="arrays" source="above" result="ansi" -z = zarr.create_array(store='data/example-3.zarr', shape=(10000, 10000), dtype='int32',chunks=(1000, 1000)) +z = zarr.create_array(store='data/example-3.zarr', shape=(10000, 10000), dtype='int32', chunks=(1000, 1000)) z[:] = 42 print(f"Original shape: {z.shape}") z.resize((20000, 10000)) @@ -158,12 +159,26 @@ print(f"Shape after second append: {z.shape}") Zarr arrays are parametrized with a configuration that determines certain aspects of array behavior. -We currently support two configuration options for arrays: `write_empty_chunks` and `order`. +We currently support five configuration options for arrays: `order`, `write_empty_chunks`, `read_missing_chunks`, `sharding_coalesce_max_gap_bytes`, and `sharding_coalesce_max_bytes`. | field | type | default | description | | - | - | - | - | -| `write_empty_chunks` | `bool` | `False` | Controls whether empty chunks are written to storage. See [Empty chunks](performance.md#empty-chunks). | `order` | `Literal["C", "F"]` | `"C"` | The memory layout of arrays returned when reading data from the store. +| `write_empty_chunks` | `bool` | `False` | Controls whether empty chunks are written to storage. See [Empty chunks](performance.md#empty-chunks). +| `read_missing_chunks` | `bool` | `True` | Controls whether missing chunks are filled with the array's fill value on read. If `False`, reading missing chunks raises a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError]. +| `sharding_coalesce_max_gap_bytes` | `int` | `1048576` (1 MiB) | When reading multiple chunks from the same shard, nearby byte ranges separated by no more than this many bytes are coalesced into a single request to the store. +| `sharding_coalesce_max_bytes` | `int` | `16777216` (16 MiB) | Requests will not be coalesced if doing so would exceed this byte size. + +!!! info + The Zarr V3 spec states that readers should interpret an uninitialized chunk as containing the + array's `fill_value`. By default, Zarr-Python follows this behavior: a missing chunk is treated + as uninitialized and filled with the array's `fill_value`. However, if you know that all chunks + have been written (i.e., are initialized), you may want to treat a missing chunk as an error. Set + `read_missing_chunks=False` to raise a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError] instead. + +!!! note + `write_empty_chunks=False` skips writing chunks that are entirely the array's fill value. + If `read_missing_chunks=False`, attempting to read these missing chunks will raise a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError]. You can specify the configuration when you create an array with the `config` keyword argument. `config` can be passed as either a `dict` or an `ArrayConfig` object. @@ -184,13 +199,13 @@ print(arr_f.config) A number of different compressors can be used with Zarr. Zarr includes Blosc, Zstandard and Gzip compressors. Additional compressors are available through -a separate package called [NumCodecs](https://numcodecs.readthedocs.io/) which provides various +a separate package called [NumCodecs](https://numcodecs.readthedocs.io/en/stable/) which provides various compressor libraries including LZ4, Zlib, BZ2 and LZMA. Different compressors can be provided via the `compressors` keyword argument accepted by all array creation functions. For example: ```python exec="true" session="arrays" source="above" result="ansi" -compressors = zarr.codecs.BloscCodec(cname='zstd', clevel=3, shuffle=zarr.codecs.BloscShuffle.bitshuffle) +compressors = zarr.codecs.BloscCodec(cname='zstd', clevel=3, shuffle='bitshuffle') data = np.arange(100000000, dtype='int32').reshape(10000, 10000) z = zarr.create_array(store='data/example-5.zarr', shape=data.shape, dtype=data.dtype, chunks=(1000, 1000), compressors=compressors) z[:] = data @@ -241,7 +256,7 @@ z[:] = data print(f"Compressors: {z.compressors}") ``` -Here is an example using LZMA from [NumCodecs](https://numcodecs.readthedocs.io/) with a custom filter pipeline including LZMA's +Here is an example using LZMA from [NumCodecs](https://numcodecs.readthedocs.io/en/stable/) with a custom filter pipeline including LZMA's built-in delta filter: ```python exec="true" session="arrays" source="above" result="ansi" @@ -255,19 +270,6 @@ z = zarr.create_array(store='data/example-7.zarr', shape=data.shape, dtype=data. print(f"Compressors: {z.compressors}") ``` -To disable compression, set `compressors=None` when creating an array, e.g.: - -```python exec="true" session="arrays" source="above" result="ansi" -z = zarr.create_array( - store='data/example-8.zarr', - shape=(100000000,), - chunks=(1000000,), - dtype='int32', - compressors=None -) -print(f"Compressors: {z.compressors}") -``` - ## Filters In some cases, compression can be improved by transforming the data in some @@ -287,13 +289,13 @@ Here is an example using a delta filter with the Blosc compressor: from zarr.codecs.numcodecs import Delta filters = [Delta(dtype='int32')] -compressors = zarr.codecs.BloscCodec(cname='zstd', clevel=1, shuffle=zarr.codecs.BloscShuffle.shuffle) +compressors = zarr.codecs.BloscCodec(cname='zstd', clevel=1, shuffle='shuffle') data = np.arange(100000000, dtype='int32').reshape(10000, 10000) z = zarr.create_array(store='data/example-9.zarr', shape=data.shape, dtype=data.dtype, chunks=(1000, 1000), filters=filters, compressors=compressors) print(z.info_complete()) ``` -For more information about available filter codecs, see the [Numcodecs](https://numcodecs.readthedocs.io/) documentation. +For more information about available filter codecs, see the [Numcodecs](https://numcodecs.readthedocs.io/en/stable/) documentation. ## Advanced indexing @@ -450,11 +452,11 @@ print(z.get_orthogonal_selection(([0, 2], slice(None)))) # select first and thi ``` ```python exec="true" session="arrays" source="above" result="ansi" -print(z.get_orthogonal_selection((slice(None), [1, 3]))) # select second and fourth columns) +print(z.get_orthogonal_selection((slice(None), [1, 3]))) # select second and fourth columns ``` ```python exec="true" session="arrays" source="above" result="ansi" -print(z.get_orthogonal_selection(([0, 2], [1, 3]))) # select rows [0, 2] and columns [1, 4] +print(z.get_orthogonal_selection(([0, 2], [1, 3]))) # select rows [0, 2] and columns [1, 3] ``` Data can also be modified, e.g.: @@ -478,7 +480,7 @@ print(z.oindex[:, [1, 3]]) # select second and fourth columns ``` ```python exec="true" session="arrays" source="above" result="ansi" -print(z.oindex[[0, 2], [1, 3]]) # select rows [0, 2] and columns [1, 4] +print(z.oindex[[0, 2], [1, 3]]) # select rows [0, 2] and columns [1, 3] ``` ```python exec="true" session="arrays" source="above" result="ansi" @@ -499,9 +501,9 @@ z[:] = data print(np.all(z.oindex[[0, 2], :] == z[[0, 2], :])) ``` -### Block Indexing +### Block indexing -Zarr also support block indexing, which allows selections of whole chunks based on their +Zarr also supports block indexing, which allows selections of whole chunks based on their logical indices along each dimension of an array. For example, this allows selecting a subset of chunk aligned rows and/or columns from a 2-dimensional array. E.g.: @@ -564,15 +566,6 @@ Any combination of integer and slice can be used for block indexing: print(z.blocks[2, 1:3]) ``` -```python exec="true" session="arrays" source="above" result="ansi" -root = zarr.create_group('data/example-19.zarr') -foo = root.create_array(name='foo', shape=(1000, 100), chunks=(10, 10), dtype='float32') -bar = root.create_array(name='bar', shape=(100,), dtype='int32') -foo[:, :] = np.random.random((1000, 100)) -bar[:] = np.arange(100) -print(root.tree()) -``` - ## Sharding Using small chunk shapes in very large arrays can lead to a very large number of chunks. @@ -585,7 +578,9 @@ This allows individual chunks to be read independently. However, when writing data, a full shard must be written in one go for optimal performance and to avoid concurrency issues. That means that shards are the units of writing and chunks are the units of reading. -Users need to configure the chunk and shard shapes accordingly. +Users need to configure the chunk and shard shapes accordingly. For guidance on +choosing chunk and shard shapes, see [Sharding](performance.md#sharding) in the +performance guide. Sharded arrays can be created by providing the `shards` parameter to [`zarr.create_array`][]. @@ -599,9 +594,173 @@ In this example a shard shape of (1000, 1000) and a chunk shape of (100, 100) is This means that `10*10` chunks are stored in each shard, and there are `10*10` shards in total. Without the `shards` argument, there would be 10,000 chunks stored as individual files. -## Missing features in 3.0 +## Rectilinear (variable) chunk grids + +!!! warning "Experimental" + Rectilinear chunk grids are an experimental feature and may change in + future releases. This feature is expected to stabilize in Zarr version 3.3. + + Because the feature is still stabilizing, it is disabled by default and + must be explicitly enabled: + + ```python exec="true" session="arrays" source="above" + import zarr + zarr.config.set({"array.rectilinear_chunks": True}) + ``` + + Or via the environment variable `ZARR_ARRAY__RECTILINEAR_CHUNKS=True`. + + The examples below assume this config has been set. + +By default, Zarr arrays use a regular chunk grid where every chunk along a +given dimension has the same size (except possibly the final boundary chunk). +Rectilinear chunk grids allow each chunk along a dimension to have a different +size. This is useful when the natural partitioning of the data is not uniform — +for example, satellite swaths of varying width, time series with irregular +intervals, or spatial tiles of different extents. + +### Creating arrays with rectilinear chunks + +To create an array with rectilinear chunks, pass a nested list to the `chunks` +parameter where each inner list gives the chunk sizes along one dimension: + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(60, 100), + chunks=[[10, 20, 30], [50, 50]], + dtype='int32', +) +print(z.info) +``` + +In this example the first dimension is split into three chunks of sizes 10, 20, +and 30, while the second dimension is split into two equal chunks of size 50. + +### Reading and writing data + +Rectilinear arrays support the same indexing interface as regular arrays. +Reads and writes that cross chunk boundaries of different sizes are handled +automatically: + +```python exec="true" session="arrays" source="above" result="ansi" +import numpy as np +data = np.arange(60 * 100, dtype='int32').reshape(60, 100) +z[:] = data +# Read a slice that spans the first two chunks (sizes 10 and 20) along axis 0 +print(z[5:25, 0:5]) +``` + +### Inspecting chunk sizes + +The `.write_chunk_sizes` property returns the actual data size of each storage +chunk along every dimension. It works for both regular and rectilinear arrays +and returns a tuple of tuples (matching the dask `Array.chunks` convention). +When sharding is used, `.read_chunk_sizes` returns the inner chunk sizes instead: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.write_chunk_sizes) +``` + +For regular arrays, this includes the boundary chunk: + +```python exec="true" session="arrays" source="above" result="ansi" +z_regular = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(100, 80), + chunks=(30, 40), + dtype='int32', +) +print(z_regular.write_chunk_sizes) +``` + +Note that the `.chunks` property is only available for regular chunk grids. For +rectilinear arrays, use `.write_chunk_sizes` (or `.read_chunk_sizes`) instead. + +### Resizing and appending + +Rectilinear arrays can be resized. When growing past the current edge sum, a +new chunk is appended covering the additional extent. When shrinking, the chunk +edges are preserved and the extent is re-bound (chunks beyond the new extent +simply become inactive): + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(30,), + chunks=[[10, 20]], + dtype='float64', +) +z[:] = np.arange(30, dtype='float64') +print(f"Before resize: chunk_sizes={z.write_chunk_sizes}") +z.resize((50,)) +print(f"After resize: chunk_sizes={z.write_chunk_sizes}") +``` + +The `append` method also works with rectilinear arrays: + +```python exec="true" session="arrays" source="above" result="ansi" +z.append(np.arange(10, dtype='float64')) +print(f"After append: shape={z.shape}, chunk_sizes={z.write_chunk_sizes}") +``` + +### Compressors and filters + +Rectilinear arrays work with all codecs — compressors, filters, and checksums. +Since each chunk may have a different size, the codec pipeline processes each +chunk independently: + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(60, 100), + chunks=[[10, 20, 30], [50, 50]], + dtype='float64', + filters=[zarr.codecs.TransposeCodec(order=(1, 0))], + compressors=[zarr.codecs.BloscCodec(cname='zstd', clevel=3)], +) +z[:] = np.arange(60 * 100, dtype='float64').reshape(60, 100) +np.testing.assert_array_equal(z[:], np.arange(60 * 100, dtype='float64').reshape(60, 100)) +print("Roundtrip OK") +``` + +### Rectilinear shard boundaries + +Rectilinear chunk grids can also be used for shard boundaries when combined +with sharding. In this case, the outer grid (shards) is rectilinear while the +inner chunks remain regular. Each shard dimension must be divisible by the +corresponding inner chunk size: + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 40, 20], [50, 50]], + dtype='int32', +) +z[:] = np.arange(120 * 100, dtype='int32').reshape(120, 100) +print(z[50:70, 40:60]) +``` + +Note that rectilinear inner chunks with sharding are not supported — only the +shard boundaries can be rectilinear. + +### Metadata format + +Rectilinear chunk grid metadata uses run-length encoding (RLE) for compact +serialization. When reading metadata, both bare integers and `[value, count]` +pairs are accepted: + +- `[10, 20, 30]` — three chunks with explicit sizes +- `[[10, 3]]` — three chunks of size 10 (RLE shorthand) +- `[[10, 3], 5]` — three chunks of size 10, then one chunk of size 5 + +When writing, Zarr automatically compresses repeated values into RLE format. + +## Features not yet ported to Zarr-Python 3 -The following features have not been ported to 3.0 yet. +The following Zarr-Python 2 features are not yet available in Zarr-Python 3. ### Copying and migrating data diff --git a/docs/user-guide/attributes.md b/docs/user-guide/attributes.md index 44d2f9fa87..8c11c853f1 100644 --- a/docs/user-guide/attributes.md +++ b/docs/user-guide/attributes.md @@ -3,10 +3,9 @@ Zarr arrays and groups support custom key/value attributes, which can be useful for storing application-specific metadata. For example: -```python exec="true" session="arrays" source="above" result="ansi" +```python exec="true" session="attributes" source="above" result="ansi" import zarr -store = zarr.storage.MemoryStore() -root = zarr.create_group(store=store) +root = zarr.create_group(store="memory://attributes-demo") root.attrs['foo'] = 'bar' z = root.create_array(name='zzz', shape=(10000, 10000), dtype='int32') z.attrs['baz'] = 42 @@ -14,24 +13,49 @@ z.attrs['qux'] = [1, 4, 7, 12] print(sorted(root.attrs)) ``` -```python exec="true" session="arrays" source="above" result="ansi" +```python exec="true" session="attributes" source="above" result="ansi" print('foo' in root.attrs) ``` -```python exec="true" session="arrays" source="above" result="ansi" +```python exec="true" session="attributes" source="above" result="ansi" print(root.attrs['foo']) ``` -```python exec="true" session="arrays" source="above" result="ansi" + +```python exec="true" session="attributes" source="above" result="ansi" print(sorted(z.attrs)) ``` -```python exec="true" session="arrays" source="above" result="ansi" +```python exec="true" session="attributes" source="above" result="ansi" print(z.attrs['baz']) ``` -```python exec="true" session="arrays" source="above" result="ansi" +```python exec="true" session="attributes" source="above" result="ansi" print(z.attrs['qux']) ``` -Internally Zarr uses JSON to store array attributes, so attribute values must be -JSON serializable. +Attributes can be deleted with the `del` operator: + +```python exec="true" session="attributes" source="above" result="ansi" +del z.attrs['baz'] +print(sorted(z.attrs)) +``` + +Note that each attribute assignment or deletion writes the node's metadata +document back to the store. To change several attributes in a single write, +use [`zarr.Array.update_attributes`][] (or [`zarr.Group.update_attributes`][] +for groups), which merges the given dict into the existing attributes and +returns the updated array or group: + +```python exec="true" session="attributes" source="above" result="ansi" +z = z.update_attributes({'baz': 43, 'quux': True}) +print(sorted(z.attrs)) +``` + +Internally Zarr uses JSON to store array and group attributes, so attribute +values must be JSON serializable. + +When working with hierarchies that contain many arrays and groups, reading the +attributes of each node separately can be slow. See +[Consolidated metadata](consolidated_metadata.md) for a way to store the +metadata (including attributes) of all nodes in a hierarchy in a single +document. diff --git a/docs/user-guide/cli.md b/docs/user-guide/cli.md index fc812c1a20..77f50f5eaf 100644 --- a/docs/user-guide/cli.md +++ b/docs/user-guide/cli.md @@ -2,9 +2,22 @@ Zarr-Python provides a command-line interface that enables: -- migration of Zarr v2 metadata to v3 +- migration of Zarr v2 metadata to v3 (see the [3.0 Migration Guide](v3_migration.md) for + migrating your *code* from the Zarr-Python 2 API to the Zarr-Python 3 API) - removal of v2 or v3 metadata +## Installation + +The command-line interface requires the `cli` optional dependencies. Install them with: + +```bash +pip install "zarr[cli]" +``` + +Without this extra, running `zarr` in a terminal will fail with `ModuleNotFoundError`. + +## Getting help + To see available commands run the following in a terminal: ```bash @@ -45,9 +58,13 @@ This will write new `zarr.json` files to `input.zarr`, leaving the existing v2 m To open the array/group using the new metadata use: -```python +```python exec="true" session="cli-open" source="above" import zarr -zarr_with_v3_metadata = zarr.open('path/to/input.zarr', zarr_format=3) + +# create a small array to open (stands in for the migrated store) +zarr.create_array("data/cli-demo.zarr", shape=(4, 4), chunks=(2, 2), dtype="i4", overwrite=True) + +zarr_with_v3_metadata = zarr.open("data/cli-demo.zarr", zarr_format=3) ``` Once you are happy with the conversion, you can run the following to remove the old v2 metadata: @@ -79,7 +96,7 @@ zarr remove-metadata v3 path/to/input.zarr By default, this will only allow removal of metadata if a valid alternative exists. For example, you can't remove v2 metadata unless v3 metadata exists at that location. -To override this behaviour use `--force`: +To override this behavior use `--force`: ```bash zarr remove-metadata v3 path/to/input.zarr --force @@ -94,7 +111,7 @@ or modifying any files. zarr migrate v3 path/to/input.zarr --dry-run Dry run enabled - no new files will be created or changed. Log of files that would be created on a real run: -Saving metadata to path/to/input.zarr/zarr.json +Saving metadata to file://path/to/input.zarr/zarr.json ``` ## Verbose @@ -109,5 +126,8 @@ zarr --verbose remove-metadata v2 path/to/input.zarr ## Equivalent functions -All features of the command-line interface are also available via functions under -`zarr.metadata`. \ No newline at end of file +All features of the command-line interface are also available as functions in the +`zarr.metadata.migrate_v3` module: +[`migrate_v2_to_v3`][zarr.metadata.migrate_v3.migrate_v2_to_v3] and +[`remove_metadata`][zarr.metadata.migrate_v3.remove_metadata]. +See the [`zarr.metadata` API reference](../api/zarr/metadata.md) for details. diff --git a/docs/user-guide/config.md b/docs/user-guide/config.md index 21fe9b5def..d1a70a14b0 100644 --- a/docs/user-guide/config.md +++ b/docs/user-guide/config.md @@ -6,14 +6,22 @@ is based on the [donfig](https://github.com/pytroll/donfig) Python library. Configuration values can be set using code like the following: ```python exec="true" session="config" source="above" result="ansi" - import zarr +zarr.config.set({'array.order': 'F'}) + print(zarr.config.get('array.order')) ``` +`zarr.config.set` can also be used as a context manager, which restores the +previous configuration on exit, and `zarr.config.reset` restores the default +configuration: + ```python exec="true" session="config" source="above" result="ansi" -zarr.config.set({'array.order': 'F'}) +zarr.config.reset() + +with zarr.config.set({'array.order': 'F'}): + print(zarr.config.get('array.order')) print(zarr.config.get('array.order')) ``` @@ -27,17 +35,20 @@ For more information, see the Configuration options include the following: -- Default Zarr format `default_zarr_version` +- Default Zarr format `default_zarr_format` - Default array order in memory `array.order` - Whether empty chunks are written to storage `array.write_empty_chunks` +- Enable experimental rectilinear chunks `array.rectilinear_chunks` +- Whether missing chunks are filled with the array's fill value on read `array.read_missing_chunks` (default `True`). Set to `False` to raise a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError] instead. - Async and threading options, e.g. `async.concurrency` and `threading.max_workers` - Selections of implementations of codecs, codec pipelines and buffers -- Enabling GPU support with `zarr.config.enable_gpu()`. See GPU support for more. +- Enabling GPU support with `zarr.config.enable_gpu()`. See [GPU support](gpu.md) for more. +- Control request merging when reading multiple chunks from the same shard with `array.sharding_coalesce_max_gap_bytes` and `array.sharding_coalesce_max_bytes`. Reads of nearby chunks are coalesced into a single request to the store when separated by at most `sharding_coalesce_max_gap_bytes` and the resulting merged read is no larger than `sharding_coalesce_max_bytes`. For selecting custom implementations of codecs, pipelines, buffers and ndbuffers, first register the implementations in the registry and then select them in the config. For example, an implementation of the bytes codec in a class `'custompackage.NewBytesCodec'`, -requires the value of `codecs.bytes.name` to be `'custompackage.NewBytesCodec'`. +requires the value of `codecs.bytes` to be `'custompackage.NewBytesCodec'`. This is the current default configuration: diff --git a/docs/user-guide/consolidated_metadata.md b/docs/user-guide/consolidated_metadata.md index d4fc9d6bab..9cb4d87c89 100644 --- a/docs/user-guide/consolidated_metadata.md +++ b/docs/user-guide/consolidated_metadata.md @@ -5,7 +5,7 @@ stores. [zarr-specs#309](https://github.com/zarr-developers/zarr-specs/pull/309) has proposed a formal extension to the v3 specification to support consolidated metadata. -Zarr-Python implements the [Consolidated Metadata](https://github.com/zarr-developers/zarr-specs/pull/309) for v2 and v3 stores. +Zarr-Python implements the Consolidated Metadata feature for both the v2 and v3 formats. Consolidated metadata can reduce the time needed to load the metadata for an entire hierarchy, especially when the metadata is being served over a network. Consolidated metadata essentially stores all the metadata for a hierarchy in the @@ -17,7 +17,7 @@ If consolidated metadata is present in a Zarr Group's metadata then it is used by default. The initial read to open the group will need to communicate with the store (reading from a file for a [`zarr.storage.LocalStore`][], making a network request for a [`zarr.storage.FsspecStore`][]). After that, any subsequent -metadata reads get child Group or Array nodes will *not* require reads from the store. +metadata reads to get child Group or Array nodes will *not* require reads from the store. In Python, the consolidated metadata is available on the `.consolidated_metadata` attribute of the `GroupMetadata` object. @@ -27,8 +27,7 @@ import zarr import warnings warnings.filterwarnings("ignore", category=UserWarning) -store = zarr.storage.MemoryStore() -group = zarr.create_group(store=store) +group = zarr.create_group(store="memory://consolidated-metadata-demo") print(group) array = group.create_array(shape=(1,), name='a', dtype='float64') print(array) @@ -45,38 +44,37 @@ print(array) ``` ```python exec="true" session="consolidated_metadata" source="above" result="ansi" -result = zarr.consolidate_metadata(store) +result = zarr.consolidate_metadata("memory://consolidated-metadata-demo") print(result) ``` -If we open that group, the Group's metadata has a `zarr.core.group.ConsolidatedMetadata` -that can be used.: +If we open that group, the Group's metadata includes a `ConsolidatedMetadata` object +holding the metadata for every child node, which can be used: ```python exec="true" session="consolidated_metadata" source="above" result="ansi" from pprint import pprint import io -consolidated = zarr.open_group(store=store) +consolidated = zarr.open_group(store="memory://consolidated-metadata-demo") consolidated_metadata = consolidated.metadata.consolidated_metadata.metadata -# Note: pprint can be users without capturing the output regularly output = io.StringIO() pprint(dict(sorted(consolidated_metadata.items())), stream=output, width=60) print(output.getvalue()) ``` -Operations on the group to get children automatically use the consolidated metadata.: +Operations on the group to get children automatically use the consolidated metadata: ```python exec="true" session="consolidated_metadata" source="above" result="ansi" print(consolidated['a']) # no read / HTTP request to the Store is required ``` -With nested groups, the consolidated metadata is available on the children, recursively.: +With nested groups, the consolidated metadata is available on the children, recursively: ```python exec="true" session="consolidated_metadata" source="above" result="ansi" child = group.create_group('child', attributes={'kind': 'child'}) -grandchild = child.create_group('child', attributes={'kind': 'grandchild'}) -consolidated = zarr.consolidate_metadata(store) +grandchild = child.create_group('grandchild', attributes={'kind': 'grandchild'}) +consolidated = zarr.consolidate_metadata("memory://consolidated-metadata-demo") output = io.StringIO() pprint(consolidated['child'].metadata.consolidated_metadata, stream=output, width=60) @@ -87,9 +85,26 @@ print(output.getvalue()) The keys in the consolidated metadata are sorted prior to writing. Keys are sorted in ascending order by path depth, where a path is defined as a sequence of strings joined by `"/"`. For keys with the same path length, lexicographic - order is used to break the tie. This behaviour ensures deterministic metadata + order is used to break the tie. This behavior ensures deterministic metadata output for a given group. +### Controlling the use of consolidated metadata + +By default, [`zarr.open_group`][] uses consolidated metadata if it is present, and +falls back to reading metadata from the store otherwise. This behavior can be +controlled with the `use_consolidated` keyword. Pass `use_consolidated=False` to +ignore consolidated metadata and always read the metadata of child nodes directly +from the store: + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +group = zarr.open_group(store="memory://consolidated-metadata-demo", use_consolidated=False) +print(group.metadata.consolidated_metadata) +``` + +Passing `use_consolidated=True` instead raises an error if consolidated metadata is +not found, which is useful when reading over a network, where relying on many +per-node metadata requests would be slow. + ## Synchronization and Concurrency Consolidated metadata is intended for read-heavy use cases on slowly changing @@ -100,8 +115,9 @@ removed, or modified, consolidated metadata may not be desirable. would need to be re-consolidated to keep it in sync with the store. 2. Readers using consolidated metadata will regularly see a "past" version of the metadata, at the time they read the root node with its consolidated - metadata. - + metadata. Readers who need the latest view of a changing hierarchy can pass + `use_consolidated=False` to [`zarr.open_group`][] to always read child + metadata directly from the store. ## Stores Without Support for Consolidated Metadata diff --git a/docs/user-guide/data_types.md b/docs/user-guide/data_types.md index aa19baf891..91f828a738 100644 --- a/docs/user-guide/data_types.md +++ b/docs/user-guide/data_types.md @@ -1,6 +1,6 @@ # Array data types -## Zarr's Data Type Model +## Zarr's data type model Zarr is designed for interoperability with NumPy, so if you are familiar with NumPy or any other N-dimensional array library, Zarr's model for array data types should seem familiar. However, Zarr @@ -14,7 +14,7 @@ which adds some unique aspects to the Zarr data type model. The following sections explain Zarr's data type model in greater detail and demonstrate the Zarr Python APIs for working with Zarr data types. -### Array Data Types +### Array data types Every Zarr array has a data type, which defines the meaning of the array's elements. An array's data type is encoded in the JSON metadata for the array. This means that the data type of an array must be @@ -38,10 +38,10 @@ For the boolean data type, the scalar encoding is simple—booleans are natively JSON, so Zarr saves booleans as JSON booleans. Other scalars, like floats or raw bytes, have more elaborate encoding schemes, and in some cases, this scheme depends on the Zarr format version. -## Data Types in Zarr Version 2 +## Data types in Zarr version 2 Version 2 of the Zarr format defined its data types relative to -[NumPy's data types](https://numpy.org/doc/2.1/reference/arrays.dtypes.html#data-type-objects-dtype), +[NumPy's data types](https://numpy.org/doc/stable/reference/arrays.dtypes.html#data-type-objects-dtype), and added a few non-NumPy data types as well. With one exception ([structured data types](#structured-data-type)), the Zarr V2 JSON identifier for a data type is just the NumPy `str` attribute of that data type: @@ -64,7 +64,7 @@ print(dtype_meta) !!! note The `<` character in the data type metadata encodes the - [endianness](https://numpy.org/doc/2.2/reference/generated/numpy.dtype.byteorder.html), + [endianness](https://numpy.org/doc/stable/reference/generated/numpy.dtype.byteorder.html), or "byte order," of the data type. As per the NumPy model, in Zarr version 2 each data type has an endianness where applicable. However, Zarr version 3 data types do not store endianness information. @@ -72,7 +72,7 @@ print(dtype_meta) There are two special cases to consider: ["structured" data types](#structured-data-type), and ["object"](#object-data-type) data types. -### Structured Data Type +### Structured data type NumPy allows the construction of a so-called "structured" data types comprised of ordered collections of named fields, where each field is itself a distinct NumPy data type. See the NumPy documentation @@ -101,7 +101,7 @@ dtype_meta = json.loads(store['.zarray'].to_bytes())["dtype"] print(dtype_meta) ``` -### Object Data Type +### Object data type The NumPy "object" type is essentially an array of references to arbitrary Python objects. It can model arrays of variable-length UTF-8 strings, arrays of variable-length byte strings, or @@ -129,7 +129,7 @@ Although this fact can be ignored for many simple numeric data types, any compre Zarr V2 data types must either reject the "object" data types or include the "object codec" identifier in the JSON form of the basic data type model. -## Data Types in Zarr Version 3 +## Data types in Zarr version 3 The NumPy-based Zarr V2 data type representation was effective for simple data types but struggled with more complex data types, like "object" and "structured" data types. To address these limitations, @@ -139,17 +139,17 @@ Zarr V3 introduced several key changes to how data types are represented: The basic data types are identified by strings like `"int8"`, `"int16"`, etc., and data types that require a configuration can be identified by a JSON object. - For example, this JSON object declares a datetime data type: + For example, this JSON object declares a datetime data type: - ```json - { - "name": "numpy.datetime64", - "configuration": { - "unit": "s", - "scale_factor": 10 + ```json + { + "name": "numpy.datetime64", + "configuration": { + "unit": "s", + "scale_factor": 10 + } } - } - ``` + ``` - Zarr V3 data types do not have endianness. This is a departure from Zarr V2, where multi-byte data types are defined with endianness information. Instead, Zarr V3 requires that the endianness @@ -159,7 +159,7 @@ Zarr V3 introduced several key changes to how data types are represented: For more about data types in Zarr V3, see the [V3 specification](https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html). -## Data Types in Zarr Python +## Data types in Zarr Python The two Zarr formats that Zarr Python supports specify data types in different ways: data types in Zarr version 2 are encoded as NumPy-compatible strings (or lists, in the case of structured data @@ -191,12 +191,14 @@ API for the following operations: The following section lists the data types built in to Zarr Python. With a few exceptions, Zarr Python supports nearly all of the data types in NumPy. If you need a data type that is not listed -here, it's possible to create it yourself: see [Adding New Data Types](#adding-new-data-types). +here, it's possible to create it yourself: see [Adding new data types](#adding-new-data-types). #### Boolean + - [Boolean][zarr.dtype.Bool] #### Integral + - [Signed 8-bit integer][zarr.dtype.Int8] - [Signed 16-bit integer][zarr.dtype.Int16] - [Signed 32-bit integer][zarr.dtype.Int32] @@ -207,6 +209,7 @@ here, it's possible to create it yourself: see [Adding New Data Types](#adding-n - [Unsigned 64-bit integer][zarr.dtype.UInt64] #### Floating-point + - [16-bit floating-point][zarr.dtype.Float16] - [32-bit floating-point][zarr.dtype.Float32] - [64-bit floating-point][zarr.dtype.Float64] @@ -214,29 +217,64 @@ here, it's possible to create it yourself: see [Adding New Data Types](#adding-n - [128-bit complex floating-point][zarr.dtype.Complex128] #### String + - [Fixed-length UTF-32 string][zarr.dtype.FixedLengthUTF32] - [Variable-length UTF-8 string][zarr.dtype.VariableLengthUTF8] #### Bytes + - [Fixed-length null-terminated bytes][zarr.dtype.NullTerminatedBytes] - [Fixed-length raw bytes][zarr.dtype.RawBytes] - [Variable-length bytes][zarr.dtype.VariableLengthBytes] #### Temporal + - [DateTime64][zarr.dtype.DateTime64] - [TimeDelta64][zarr.dtype.TimeDelta64] #### Struct-like + - [Structured][zarr.dtype.Structured] -### Example Usage +!!! note "Zarr V3 Structured Data Types" + + In Zarr V3, structured data types are specified using the `struct` extension defined in the + [zarr-extensions repository](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/struct). + The JSON representation uses an object format for fields: + + ```json + { + "name": "struct", + "configuration": { + "fields": [ + {"name": "x", "data_type": "float32"}, + {"name": "y", "data_type": "int64"} + ] + } + } + ``` + + For backward compatibility, Zarr Python also accepts the legacy `structured` name with + tuple-format fields when reading existing data. + + Fill values for structured types are represented as JSON objects mapping field names to values: + + ```json + {"x": 1.5, "y": 42} + ``` + + When using structured types with multi-byte fields, the `bytes` codec must specify an + explicit `endian` parameter. If omitted, Zarr Python assumes little-endian for legacy + compatibility but emits a warning. + +### Example usage -This section will demonstrates the basic usage of Zarr data types. +This section will demonstrate the basic usage of Zarr data types. Create a `ZDType` from a native data type: ```python exec="true" session="data_types" source="above" -from zarr.core.dtype import Int8 +from zarr.dtype import Int8 import numpy as np int8 = Int8.from_native_dtype(np.dtype('int8')) ``` @@ -260,7 +298,6 @@ Serialize to JSON for Zarr V2: ```python exec="true" session="data_types" source="above" result="ansi" json_v2 = int8.to_json(zarr_format=2) print(json_v2) -{'name': '|i1', 'object_codec_id': None} ``` !!! note @@ -293,7 +330,7 @@ scalar_value = int8.from_json_scalar(42, zarr_format=3) assert scalar_value == np.int8(42) ``` -### Adding New Data Types +### Adding new data types Each Zarr data type is a separate Python class that inherits from [ZDType][zarr.dtype.ZDType]. You can define a custom data type by @@ -301,7 +338,7 @@ writing your own subclass of [ZDType][zarr.dtype.ZDType] and adding your data type to the data type registry. To see an executable demonstration of this process, see the [`custom_dtype` example](../user-guide/examples/custom_dtype.md). -### Data Type Resolution +### Data type resolution Although Zarr Python uses a different data type model from NumPy, you can still define a Zarr array with a NumPy data type object: @@ -329,7 +366,7 @@ print(type(a.dtype)) But if we inspect the metadata for the array, we can see the Zarr data type object: -```python +```python exec="false" reason="REPL output transcript, not executable source" type(a.metadata.data_type) ``` @@ -344,16 +381,14 @@ For simple data types like `int`, the solution could be extremely simple: just maintain a lookup table that maps a NumPy data type to the Zarr data type equivalent. But not all data types are so simple. Consider this case: -```python exec="true" session="data_types" source="above" +```python exec="true" session="data_types" source="above" result="ansi" from zarr import create_array -import warnings import numpy as np -warnings.simplefilter("ignore", category=FutureWarning) a = create_array({}, shape=(10,), dtype=[('a', 'f8'), ('b', 'i8')]) print(a.dtype) # this is the NumPy data type ``` -```python exec="true" session="data_types" source="above" +```python exec="true" session="data_types" source="above" result="ansi" print(a.metadata.data_type) # this is the Zarr data type ``` diff --git a/docs/user-guide/examples/codec_pipeline_performance.md b/docs/user-guide/examples/codec_pipeline_performance.md new file mode 100644 index 0000000000..f21e31636e --- /dev/null +++ b/docs/user-guide/examples/codec_pipeline_performance.md @@ -0,0 +1,7 @@ +--8<-- "examples/codec_pipeline_performance/README.md" + +## Source Code + +```python exec="false" reason="pymdownx snippet include directive, not python source" +--8<-- "examples/codec_pipeline_performance/codec_pipeline_performance.py" +``` diff --git a/docs/user-guide/examples/custom_dtype.md b/docs/user-guide/examples/custom_dtype.md index d6736e25dd..391407b822 100644 --- a/docs/user-guide/examples/custom_dtype.md +++ b/docs/user-guide/examples/custom_dtype.md @@ -2,6 +2,6 @@ ## Source Code -```python +```python exec="false" reason="pymdownx snippet include directive, not python source" --8<-- "examples/custom_dtype/custom_dtype.py" ``` diff --git a/docs/user-guide/examples/rectilinear_chunks.md b/docs/user-guide/examples/rectilinear_chunks.md new file mode 100644 index 0000000000..098cdf1e2f --- /dev/null +++ b/docs/user-guide/examples/rectilinear_chunks.md @@ -0,0 +1,173 @@ +# Rectilinear Chunk Grids + +This example demonstrates rectilinear (variable-sized) chunk grids, introduced in +[#3802](https://github.com/zarr-developers/zarr-python/pull/3802). Rectilinear grids +allow different chunk sizes along each dimension, which is useful for data that +doesn't partition evenly — for example, sparse HEALPix cells grouped by parent tile, +boundary-padded HPC arrays, or ingesting existing variable-chunked datasets via +VirtualiZarr. See [Rectilinear (variable) chunk grids](../arrays.md#rectilinear-variable-chunk-grids) +in the arrays guide for an introduction to the feature. + +The example chunks a HEALPix dataset by parent tile, writes it as a Zarr v3 array +with a rectilinear chunk grid, and verifies the round trip through +[Xarray](https://xarray.dev). + +!!! warning "Experimental" + Rectilinear chunk grids are an experimental feature and may change in future + releases. In addition, this example currently requires + [a fork of Xarray](https://github.com/maxrjones/xarray/tree/poc/unified-zarr-chunk-grid) + with rectilinear chunk grid support (this will ideally be incorporated into a + future Xarray release), as well as the `dask`, `healpix-geo`, and `obstore` + packages, and it reads an example dataset from a remote server. For these + reasons the code on this page is not executed when the documentation is built; + the outputs shown were captured from a live run. + +## Setup + +Rectilinear chunk grids are disabled by default and must be explicitly enabled via +the `array.rectilinear_chunks` configuration option: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +import json +import tempfile +from pathlib import Path + +import numpy as np +import xarray as xr +from healpix_geo import nested +from obstore.store import HTTPStore + +import zarr +from zarr.storage import ObjectStore + +# Increase concurrency for better performance with obstore +zarr.config.set({'async.concurrency': 128}) +# Opt in to rectilinear chunks +zarr.config.set({'array.rectilinear_chunks': True}) +``` + +## Inspect the HEALPix dataset + +Load the remote Zarr store to understand the data structure before chunking it: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +ob_store = HTTPStore.from_url("https://data-taos.ifremer.fr/GRID4EARTH/no_chunk_healpix.zarr") +store = ObjectStore(ob_store) +g = zarr.open_group(store, mode="r", zarr_format=2, use_consolidated=True) +arr = g['da'] + +print("Members:", list(g.members())) +print("Attrs:", dict(g.attrs)) +print("Write chunk sizes:", arr.write_chunk_sizes) +``` + +```text +Members: [('cell_ids', ), ('da', )] +Attrs: {} +Write chunk sizes: ((55611, 55611, 55611, 55609),) +``` + +## HEALPix-style variable chunking + +Inspired by [this use case](https://github.com/zarr-developers/zarr-python/pull/3534#issuecomment-3848669859): +HEALPix grids where cells are grouped by parent tile at a coarser resolution level, +producing variable-sized chunks along the cell dimension when accounting for sparsity. + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +da = xr.open_zarr( + store, + zarr_format=2, + consolidated=True, +) + +depth = da.cell_ids.attrs['level'] +new_depth = depth - 6 +parents = nested.zoom_to(da.cell_ids, depth=depth, new_depth=new_depth) +_, chunk_sizes = np.unique(parents, return_counts=True) +print(chunk_sizes) +``` + +```text +[ 25 645 1510 2363 3203 74 769 3963 4096 233 1603 2450 4096 4096 + 3327 4047 4096 4096 1278 2113 4096 3879 4096 3842 2173 983 4046 2187 + 4095 1369 4096 4096 4096 4096 3515 1395 4096 3622 4096 4096 3875 4096 + 4096 4096 4096 4096 2034 4096 358 3991 4096 4096 4096 4096 2714 1210 + 4096 4096 4096 4096 92 3826 4096 2629 4096 1438 4096 353 4078 3410 + 2407 226 132 2738 1223 23] +``` + +Rechunk the dataset with these variable-sized chunks: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +da = da.chunk({"cell_ids": tuple(chunk_sizes.tolist())}) +print(da.chunks) +``` + +```text +Frozen({'cell_ids': (25, 645, 1510, 2363, 3203, 74, 769, 3963, 4096, 233, 1603, 2450, 4096, 4096, 3327, 4047, 4096, 4096, 1278, 2113, 4096, 3879, 4096, 3842, 2173, 983, 4046, 2187, 4095, 1369, 4096, 4096, 4096, 4096, 3515, 1395, 4096, 3622, 4096, 4096, 3875, 4096, 4096, 4096, 4096, 4096, 2034, 4096, 358, 3991, 4096, 4096, 4096, 4096, 2714, 1210, 4096, 4096, 4096, 4096, 92, 3826, 4096, 2629, 4096, 1438, 4096, 353, 4078, 3410, 2407, 226, 132, 2738, 1223, 23)}) +``` + +## Write as rectilinear Zarr v3 + +Write the variable-chunked dataset to a local Zarr v3 store with rectilinear chunk +grids enabled: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +output_path = Path(tempfile.mkdtemp()) / "healpix_rectilinear.zarr" + +encoding = { + "da": {"chunks": [chunk_sizes.tolist()]}, + "cell_ids": {"chunks": [chunk_sizes.tolist()]}, +} + +da.to_zarr(output_path, zarr_format=3, mode="w", encoding=encoding, consolidated=False) + +print(f"Written to: {output_path}") +``` + +```text +Written to: /var/folders/.../T/tmp6dibcrho/healpix_rectilinear.zarr +``` + +## Verify the rectilinear metadata + +Inspect the output store to confirm the chunk grid is serialized as `"rectilinear"` +in `zarr.json`, following the +[rectilinear chunk grid extension spec](https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear). + +Key things to look for in `chunk_grid`: + +- **`name`**: `"rectilinear"` (the extension identifier) +- **`configuration.kind`**: `"inline"` (edge lengths stored directly in metadata) +- **`configuration.chunk_shapes`**: one entry per dimension — here a single list for + the 1D `cell_ids` axis. Each element is either: + - a **bare integer** for a unique edge length (e.g., `25`, `645`) + - a **`[value, count]` array** using + [run-length encoding](https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear#run-length-encoding) + for consecutive repeated sizes (e.g., `[4096, 4]` means four consecutive chunks + of size 4096) + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +# Read the zarr.json for the 'da' array +da_meta_path = output_path / "da" / "zarr.json" +meta = json.loads(da_meta_path.read_text()) +print(meta['chunk_grid']) +``` + +```text +{'name': 'rectilinear', 'configuration': {'kind': 'inline', 'chunk_shapes': [[25, 645, 1510, 2363, 3203, 74, 769, 3963, 4096, 233, 1603, 2450, [4096, 2], 3327, 4047, [4096, 2], 1278, 2113, 4096, 3879, 4096, 3842, 2173, 983, 4046, 2187, 4095, 1369, [4096, 4], 3515, 1395, 4096, 3622, [4096, 2], 3875, [4096, 5], 2034, 4096, 358, 3991, [4096, 4], 2714, 1210, [4096, 4], 92, 3826, 4096, 2629, 4096, 1438, 4096, 353, 4078, 3410, 2407, 226, 132, 2738, 1223, 23]]}} +``` + +## Round-trip verification + +Read the rectilinear store back and confirm the chunk sizes are preserved: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +roundtrip = xr.open_zarr(output_path, zarr_format=3, consolidated=False) + +print("Round-trip chunk sizes:", roundtrip.chunks) +``` + +```text +Round-trip chunk sizes: Frozen({'cell_ids': (25, 645, 1510, 2363, 3203, 74, 769, 3963, 4096, 233, 1603, 2450, 4096, 4096, 3327, 4047, 4096, 4096, 1278, 2113, 4096, 3879, 4096, 3842, 2173, 983, 4046, 2187, 4095, 1369, 4096, 4096, 4096, 4096, 3515, 1395, 4096, 3622, 4096, 4096, 3875, 4096, 4096, 4096, 4096, 4096, 2034, 4096, 358, 3991, 4096, 4096, 4096, 4096, 2714, 1210, 4096, 4096, 4096, 4096, 92, 3826, 4096, 2629, 4096, 1438, 4096, 353, 4078, 3410, 2407, 226, 132, 2738, 1223, 23)}) +``` diff --git a/docs/user-guide/examples/sharding_coalescing.md b/docs/user-guide/examples/sharding_coalescing.md new file mode 100644 index 0000000000..8b2e054af5 --- /dev/null +++ b/docs/user-guide/examples/sharding_coalescing.md @@ -0,0 +1,7 @@ +--8<-- "examples/sharding_coalescing/README.md" + +## Source Code + +```python exec="false" reason="pymdownx snippet include directive, not python source" +--8<-- "examples/sharding_coalescing/sharding_coalescing.py" +``` diff --git a/docs/user-guide/experimental.md b/docs/user-guide/experimental.md index eaa53a4622..e14146610c 100644 --- a/docs/user-guide/experimental.md +++ b/docs/user-guide/experimental.md @@ -1,10 +1,99 @@ # Experimental features -This section contains documentation for experimental Zarr Python features. The features described here are exciting and potentially useful, but also volatile -- we might change them at any time. Take this into account if you consider depending on these features. +This section contains documentation for experimental Zarr Python features. The features described here are exciting and potentially useful, but also volatile -- we might change them at any time. Take this into account if you consider depending on these features. See the +[experimental API policy](../contributing.md#experimental-api-policy) for the stability +guarantees (or lack thereof) that apply to everything documented on this page. + +## `FusedCodecPipeline` + +A *codec pipeline* is the machinery that turns chunks of array data into stored bytes and back, by running the configured codecs (filters, serializer, compressors) and performing the storage IO. +The default pipeline, `BatchedCodecPipeline`, schedules both the IO and codec work asynchronously -- roughly one coroutine per chunk operation. + +`FusedCodecPipeline` is an experimental alternative that runs codec compute and synchronous IO *synchronously*, avoiding that per-chunk async scheduling overhead and nasty [`asyncio.to_thread` overhead](https://github.com/python/cpython/issues/136084). +On real workloads the scheduling cost can dominate the actual codec work, so removing it is a significant speedup -- especially for **sharded arrays**, where a single shard read or write involves many inner chunks. + +> **Note:** The win is *not* a faster compressor or a different on-disk format -- the bytes written are +> identical. It is purely the removal of async scheduling overhead, plus a few vectorized fast paths +> for dense, uncompressed shards i.e., removing compute where it is not needed. + +### When it helps + +There are two main benefits in this new pipeline: + +1. When storage IO is fast enough that the *scheduling* overhead, not the IO itself, is the bottleneck. That means **low-latency stores** that are themselves synchronous -- in particular [`zarr.storage.MemoryStore`][] and [`zarr.storage.LocalStore`][]. + +2. Whenever codec work that is truly synchronous will not need the overhead of `async` scheduling i.e., inner-chunk codec work in sharding using something like `zstd`. We also now make use of `asyncio.as_completed` so that IO from asynchronous sources can begin decompression immediately. + +### Opting in + +`FusedCodecPipeline` is opt-in: the default pipeline is unchanged, so existing code behaves exactly as +before. Select it through the [runtime configuration](config.md), by setting `codec_pipeline.path`: + +```python exec="true" session="experimental-fused" source="above" result="ansi" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +) +``` + +You can set this globally as above (affecting every array created or opened afterwards), or scope it to +a block of code using `zarr.config.set` as a context manager: + +```python exec="true" session="experimental-fused" source="above" +import numpy as np +import zarr +from zarr.storage import MemoryStore + +with zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +): + # A sharded array on an in-memory store -- the low-latency case the + # synchronous pipeline targets. + arr = zarr.create_array( + store=MemoryStore(), + shape=(1000, 1000), + chunks=(100, 100), + shards=(1000, 1000), + dtype="float32", + ) + arr[:] = np.random.random((1000, 1000)).astype("float32") + result = arr[:] + +print(result.shape) +``` + +To return to the default pipeline, set `codec_pipeline.path` back to the batched implementation: + +```python exec="true" session="experimental-fused" source="above" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"} +) +``` + +### Threading + +By default the synchronous pipeline runs fully threaded i.e., `os.cpu_count()`. +For memory-backed workflows, you may find that setting `max_workers` to 1 helps (since requests for data from the store are GIL-locked, unlike, say, file-backed i/o). + +```python exec="true" session="experimental-fused" source="above" +import zarr + +# Use a fixed-size thread pool for codec compute. +zarr.config.set({"codec_pipeline.max_workers": 8}) + +# Or "auto", sized to the number of CPUs. +zarr.config.set({"codec_pipeline.max_workers": None}) +``` + +On many-core nodes a pool sized to `cpu_count` can oversubscribe workloads that already parallelize at a higher level (e.g. Dask). +`codec_pipeline.max_workers` only affects `FusedCodecPipeline`; the default `BatchedCodecPipeline` ignores it. ## `CacheStore` -Zarr Python 3.1.4 adds [`zarr.experimental.cache_store.CacheStore`][] provides a dual-store caching implementation +Zarr Python 3.1.4 adds [`zarr.experimental.cache_store.CacheStore`][], which provides a dual-store caching implementation that can be wrapped around any Zarr store to improve performance for repeated data access. This is particularly useful when working with remote stores (e.g., S3, HTTP) where network latency can significantly impact data access speed. @@ -16,10 +105,11 @@ when the cache reaches its maximum size. Because the `CacheStore` uses an ordinary Zarr `Store` object as the caching layer, you can reuse the data stored in the cache later. -> **Note:** The CacheStore is a wrapper store that maintains compatibility with the full -> `zarr.abc.store.Store` API while adding transparent caching functionality. +!!! note + The CacheStore is a wrapper store that maintains compatibility with the full + `zarr.abc.store.Store` API while adding transparent caching functionality. -## Basic Usage +### Basic Usage Creating a CacheStore requires both a source store and a cache store. The cache store can be any Store implementation, providing flexibility in cache persistence: @@ -51,11 +141,11 @@ zarr_array[:] = np.random.random((100, 100)) The dual-store architecture allows you to use different store types for source and cache, such as a remote store for source data and a local store for persistent caching. -## Performance Benefits +### Performance Benefits The CacheStore provides significant performance improvements for repeated data access: -```python exec="true" session="experimental" source="above" result="ansi" +```python exec="true" session="experimental" source="above" import time # Benchmark reading with cache @@ -78,21 +168,15 @@ print(f"Speedup is {speedup}") Cache effectiveness is particularly pronounced with repeated access to the same data chunks. - -## Cache Configuration +### Cache Configuration The CacheStore can be configured with several parameters: -**max_size**: Controls the maximum size of cached data in bytes +**max_size**: Controls the maximum size of cached data in bytes. The +[Basic Usage](#basic-usage) example above sets a 256MB limit with +`max_size=256*1024*1024`: ```python exec="true" session="experimental" source="above" -# 256MB cache with size limit -cache = CacheStore( - store=source_store, - cache_store=cache_store, - max_size=256*1024*1024 -) - # Unlimited cache size (use with caution) cache = CacheStore( store=source_store, @@ -121,7 +205,7 @@ cache = CacheStore( **cache_set_data**: Controls whether written data is cached -```python exec="true" session="experimental" source="above" result="ansi" +```python exec="true" session="experimental" source="above" # Cache data when writing (default) cache = CacheStore( store=source_store, @@ -137,14 +221,15 @@ cache = CacheStore( ) ``` -## Cache Statistics +### Cache Statistics The CacheStore provides statistics to monitor cache performance and state: -```python exec="true" session="experimental" source="above" result="ansi" +```python exec="true" session="experimental" source="above" # Access some data to generate cache activity -data = zarr_array[0:50, 0:50] # First access - cache miss -data = zarr_array[0:50, 0:50] # Second access - cache hit +# (these chunks were already cached by the reads above, so both accesses are cache hits) +data = zarr_array[0:50, 0:50] +data = zarr_array[0:50, 0:50] # Get comprehensive cache information info = cached_store.cache_info() @@ -159,7 +244,7 @@ print(info['cache_set_data']) The `cache_info()` method returns a dictionary with detailed information about the cache state. -## Cache Management +### Cache Management The CacheStore provides methods for manual cache management: @@ -177,7 +262,7 @@ assert info['current_size'] == 0 The `clear_cache()` method is an async method that clears both the cache store (if it supports the `clear` method) and all internal tracking data. -## Best Practices +### Best Practices 1. **Choose appropriate cache store**: Use MemoryStore for fast temporary caching or LocalStore for persistent caching 2. **Size the cache appropriately**: Set `max_size` based on available storage and expected data access patterns @@ -186,12 +271,12 @@ The `clear_cache()` method is an async method that clears both the cache store 5. **Consider data locality**: Group related data accesses together to improve cache efficiency 6. **Set appropriate expiration**: Use `max_age_seconds` for time-sensitive data or "infinity" for static data -## Working with Different Store Types +### Working with Different Store Types The CacheStore can wrap any store that implements the `zarr.abc.store.Store` interface and use any store type for the cache backend: -### Local Store with Memory Cache +#### Local Store with Memory Cache ```python exec="true" session="experimental-memory-cache" source="above" from zarr.storage import LocalStore, MemoryStore @@ -208,7 +293,7 @@ cached_store = CacheStore( ) ``` -### Memory Store with Persistent Cache +#### Memory Store with Persistent Cache ```python exec="true" session="experimental-local-cache" source="above" from tempfile import mkdtemp @@ -228,11 +313,11 @@ cached_store = CacheStore( The dual-store architecture provides flexibility in choosing the best combination of source and cache stores for your specific use case. -## Examples from Real Usage +### Examples from Real Usage Here's a complete example demonstrating cache effectiveness: -```python exec="true" session="experimental-final" source="above" result="ansi" +```python exec="true" session="experimental-final" source="above" import numpy as np import time from tempfile import mkdtemp diff --git a/docs/user-guide/extending.md b/docs/user-guide/extending.md index 39444135df..f852f9105e 100644 --- a/docs/user-guide/extending.md +++ b/docs/user-guide/extending.md @@ -14,6 +14,7 @@ in the following ways: [numcodecs.registry.register_codec](https://numcodecs.readthedocs.io/en/stable/registry.html#numcodecs.registry.register_codec). There are three types of codecs in Zarr: + - array-to-array - array-to-bytes - bytes-to-bytes @@ -50,8 +51,8 @@ Custom codecs should also implement the following methods: To use custom codecs in Zarr, they need to be registered using the [entrypoint mechanism](https://packaging.python.org/en/latest/specifications/entry-points/). Commonly, entrypoints are declared in the `pyproject.toml` of your package under the -`[project.entry-points."zarr.codecs"]` section. Zarr will automatically discover and -load all codecs registered with the entrypoint mechanism from imported modules. +`[project.entry-points."zarr.codecs"]` section. Zarr will automatically discover +all codecs registered via the entrypoint mechanism in installed packages. ```toml [project.entry-points."zarr.codecs"] @@ -74,15 +75,25 @@ implementation. ## Custom stores -Coming soon. +Custom stores can be created by implementing the [`zarr.abc.store.Store`][] interface. +See [developing custom stores](storage.md#developing-custom-stores) for more information. ## Custom array buffers -Zarr-python provides control over where and how arrays stored in memory through +Zarr-python provides control over where and how arrays are stored in memory through [`zarr.abc.buffer.Buffer`][]. Currently both CPU (the default) and GPU implementations are provided (see [Using GPUs with Zarr](gpu.md) for more information). You can implement your own buffer classes by implementing the interface defined in [`zarr.abc.buffer.BufferPrototype`][]. +Like codecs, custom buffer implementations can be registered via entrypoints, using the +`zarr.buffer` and `zarr.ndbuffer` entrypoint groups. + +## Custom data types + +Zarr supports user-defined data types. See the +[data types documentation](data_types.md) for an explanation of how Zarr Python +models data types and how to write your own, and the +[custom data type example](examples/custom_dtype.md) for a complete worked example. ## Other extensions -In the future, Zarr will support writing custom custom data types and chunk grids. +In the future, Zarr will support writing custom chunk grids. diff --git a/docs/user-guide/glossary.md b/docs/user-guide/glossary.md index a490b7c341..dde08388a1 100644 --- a/docs/user-guide/glossary.md +++ b/docs/user-guide/glossary.md @@ -9,12 +9,18 @@ This page defines key terms used throughout the zarr-python documentation and AP An N-dimensional typed array stored in a Zarr [store](#store). An array's [metadata](#metadata) defines its shape, data type, chunk layout, and codecs. +### Group + +A container for [arrays](#array) and other groups, enabling hierarchical +organization of data — similar to directories in a file system, or groups in +HDF5. Like arrays, each group has its own [metadata](#metadata) and +[attributes](#attributes). See the [groups documentation](groups.md). + ### Chunk The fundamental unit of data in a Zarr array. An array is divided into chunks -along each dimension according to the [chunk grid](#chunk-grid), which is currently -part of Zarr's private API. Each chunk is independently compressed and encoded -through the array's [codec](#codec) pipeline. +along each dimension according to the [chunk grid](#chunk-grid). Each chunk is +independently compressed and encoded through the array's [codec](#codec) pipeline. When [sharding](#shard) is used, "chunk" refers to the inner chunks within each shard, because those are the compressible units. The chunks are the smallest units @@ -36,12 +42,24 @@ The partitioning of an array's elements into [chunks](#chunk). In Zarr V3, the chunk grid is defined in the array [metadata](#metadata) and determines the boundaries of each storage object. +Zarr V3 supports two chunk grid types: + +- **Regular**: All chunks have the same shape (the last chunk along each + dimension may be smaller than the declared size). +- **Rectilinear** *(experimental)*: Each dimension can have different chunk + sizes, specified as a list of edge lengths per dimension. Enable with + `zarr.config.set({'array.rectilinear_chunks': True})`. + When sharding is used, the chunk grid defines the [shard](#shard) boundaries, not the inner chunk boundaries. The inner chunk shape is defined within the [sharding codec](#shard). **API**: The `chunk_grid` field in array metadata contains the storage-level -grid. +grid. [`Array.chunks`][zarr.Array.chunks] returns the chunk shape for regular +grids. For all grid types, `Array.read_chunk_sizes` and `Array.write_chunk_sizes` +return the per-dimension chunk sizes in dask-style `tuple[tuple[int, ...], ...]` +format. Note that while the chunk grid is a public concept of the Zarr format, +the classes zarr-python uses to model chunk grids are currently private API. ### Shard @@ -77,12 +95,28 @@ file) in the store, addressed by a key derived from its grid coordinates. ### Metadata -The JSON document (`zarr.json`) that describes an [array](#array) or group. For -arrays, metadata includes the shape, data type, [chunk grid](#chunk-grid), fill +The JSON document that describes an [array](#array) or [group](#group). In Zarr +format 3 this is a single `zarr.json` document; Zarr format 2 stores the +equivalent information in separate `.zarray`, `.zgroup`, and `.zattrs` documents. +For arrays, metadata includes the shape, data type, [chunk grid](#chunk-grid), fill value, and [codec](#codec) pipeline. Metadata is stored alongside the data in the [store](#store). Zarr-Python does not yet expose its internal metadata representation as part of its public API. +### Attributes + +User-defined key-value pairs (any JSON-serializable values) attached to an +[array](#array) or [group](#group). Attributes are stored in the +[metadata](#metadata) document. See the +[attributes documentation](attributes.md). + +### Consolidated Metadata + +A copy of the [metadata](#metadata) of every array and group in a hierarchy, +stored in the metadata of the root group so that the entire hierarchy can be +inspected with a single read from the [store](#store). See the +[consolidated metadata documentation](consolidated_metadata.md). + ## Codecs ### Codec @@ -104,7 +138,9 @@ The following properties are available on [`zarr.Array`][]: | Property | Description | |----------|-------------| -| `.chunks` | Chunk shape — the inner chunk shape when sharding is used | +| `.chunks` | Chunk shape — the inner chunk shape when sharding is used. Raises for rectilinear grids | | `.shards` | Shard shape, or `None` if no sharding | +| `.read_chunk_sizes` | Per-dimension chunk data sizes (`tuple[tuple[int, ...], ...]`). Works for all grid types | +| `.write_chunk_sizes` | Per-dimension storage chunk sizes (`tuple[tuple[int, ...], ...]`). Works for all grid types | | `.nchunks` | Total number of independently compressible units across the array | | `.cdata_shape` | Number of independently compressible units per dimension | diff --git a/docs/user-guide/gpu.md b/docs/user-guide/gpu.md index 3317bdf065..26d1c114b0 100644 --- a/docs/user-guide/gpu.md +++ b/docs/user-guide/gpu.md @@ -1,31 +1,60 @@ # Using GPUs with Zarr -Zarr can use GPUs to accelerate your workload by running `zarr.Config.enable_gpu`. +Zarr can use GPUs to accelerate your workload by running `zarr.config.enable_gpu()`. !!! note `zarr-python` currently supports reading the ndarray data into device (GPU) memory as the final stage of the codec pipeline. Data will still be read into or copied to host (CPU) memory for encoding and decoding. - In the future, codecs will be available compressing and decompressing data on + In the future, codecs will be available for compressing and decompressing data on the GPU, avoiding the need to move data between the host and device for compression and decompression. +## Installation + +Zarr's GPU support requires [CuPy](https://cupy.dev), which in turn requires a +CUDA-compatible NVIDIA GPU. CuPy can be installed alongside Zarr with the `gpu` +extra (see [Installation](installation.md) for the other optional dependency groups): + +```console +pip install "zarr[gpu]" +``` + +This installs the `cupy-cuda12x` package. If you need a CuPy build for a different +CUDA version, see the [CuPy installation guide](https://docs.cupy.dev/en/stable/install.html) +and install the appropriate package yourself. + ## Reading data into device memory -[`zarr.config`][] configures Zarr to use GPU memory for the data -buffers used internally by Zarr via `enable_gpu()`. +Calling `zarr.config.enable_gpu()` configures Zarr to use GPU memory for the data +buffers used internally by Zarr: -```python +```python test="true" session="gpu-demo" markers="gpu" source="above" import zarr import cupy as cp + zarr.config.enable_gpu() -store = zarr.storage.MemoryStore() z = zarr.create_array( - store=store, shape=(100, 100), chunks=(10, 10), dtype="float32", + store="memory://gpu-demo", shape=(100, 100), chunks=(10, 10), dtype="float32", ) -type(z[:10, :10]) -# cupy.ndarray +assert isinstance(z[:10, :10], cp.ndarray) +``` + +Note that the arrays returned by reads are of type `cupy.ndarray` rather than +NumPy arrays. + +`zarr.config.enable_gpu()` returns a [donfig](https://donfig.readthedocs.io/en/latest/) +`ConfigSet`, which can be used as a context manager to enable GPU support for a +limited scope: + +```python test="true" session="gpu-demo" markers="gpu" source="above" +with zarr.config.enable_gpu(): + data = z[:10, :10] +assert isinstance(data, cp.ndarray) ``` -Note that the output type is a `cupy.ndarray` rather than a NumPy array. +Under the hood, `enable_gpu()` selects the GPU-backed buffer classes +`zarr.buffer.gpu.Buffer` and `zarr.buffer.gpu.NDBuffer` via the `buffer` and +`ndbuffer` configuration keys. See [Custom array buffers](extending.md#custom-array-buffers) +for more on Zarr's buffer classes, including how to implement your own. diff --git a/docs/user-guide/groups.md b/docs/user-guide/groups.md index 58a9c1c806..7429a03847 100644 --- a/docs/user-guide/groups.md +++ b/docs/user-guide/groups.md @@ -4,15 +4,21 @@ Zarr supports hierarchical organization of arrays via groups. As with arrays, groups can be stored in memory, on disk, or via other storage systems that support a similar interface. -To create a group, use the [`zarr.group`][] function: +To create a group, use the [`zarr.create_group`][] function: ```python exec="true" session="groups" source="above" result="ansi" import zarr -store = zarr.storage.MemoryStore() -root = zarr.create_group(store=store) +root = zarr.create_group(store="memory://groups-demo") print(root) ``` +Zarr-Python provides three related functions for making groups: +[`zarr.create_group`][] creates a new group; [`zarr.open_group`][] creates or +re-opens a group depending on its `mode` argument (see below); and +[`zarr.group`][], which is kept for compatibility with Zarr-Python 2, is +equivalent to calling [`zarr.open_group`][] with `mode='a'` (or `mode='w'` +when `overwrite=True`). + Groups have a similar API to the Group class from [h5py](https://www.h5py.org/). For example, groups can contain other groups: ```python exec="true" session="groups" source="above" @@ -27,7 +33,8 @@ z1 = bar.create_array(name='baz', shape=(10000, 10000), chunks=(1000, 1000), dty print(z1) ``` -Members of a group can be accessed via the suffix notation, e.g.: +Members of a group can be accessed with square-bracket item access, like a +Python `dict`, e.g.: ```python exec="true" session="groups" source="above" result="ansi" print(root['foo']) @@ -44,6 +51,29 @@ print(root['foo/bar']) print(root['foo/bar/baz']) ``` +Accessing a member with `[]` returns either an [`zarr.Array`][] or a [`zarr.Group`][], depending on +what is stored at the given path. When you expect a node of a particular kind, use +[`zarr.Group.get_array`][] or [`zarr.Group.get_group`][] instead. These methods accept the same +paths as `[]`, but they have precise return types and raise an error if no node exists at the +given path, or if the node is not of the expected kind: + +```python exec="true" session="groups" source="above" result="ansi" +print(root.get_group('foo')) +``` + +```python exec="true" session="groups" source="above" result="ansi" +print(root.get_array('foo/bar/baz')) +``` + +```python exec="true" session="groups" source="above" result="ansi" +from zarr.errors import ContainsGroupError + +try: + root.get_array('foo') +except ContainsGroupError as e: + print(e) +``` + The [`zarr.Group.tree`][] method can be used to print a tree representation of the hierarchy, e.g.: @@ -67,10 +97,46 @@ print(z) For more information on groups see the [`zarr.Group` API docs](../api/zarr/group.md). -## Batch Group Creation +## Exploring group contents + +Groups also support a dict-like interface for enumerating their contents. The +[`zarr.Group.keys`][] method iterates over member names, and the `in` operator +tests for membership: + +```python exec="true" session="groups" source="above" result="ansi" +print(list(root.keys())) +print('foo' in root) +``` + +The [`zarr.Group.members`][] method returns `(name, member)` pairs for the +arrays and groups contained in a group: + +```python exec="true" session="groups" source="above" result="ansi" +for name, member in root.members(): + print(name, member) +``` + +By default only immediate members are returned. Pass `max_depth=None` to +recursively traverse the whole hierarchy below a group: + +```python exec="true" session="groups" source="above" result="ansi" +for name, member in root.members(max_depth=None): + print(name, member) +``` + +Members can be deleted with the `del` operator, which removes the member's +metadata and data from the store: + +```python exec="true" session="groups" source="above" result="ansi" +del root['foo/bar/baz'] +for name, member in root.members(max_depth=None): + print(name, member) +``` + +## Batch group creation You can also create multiple groups concurrently with a single function call. [`zarr.create_hierarchy`][] takes -a [`zarr Storage instance`](../api/zarr/storage.md) instance and a dict of `key : metadata` pairs, parses that dict, and +a [`Store`](../api/zarr/storage.md) instance and a dict of `key : metadata` pairs, parses that dict, and writes metadata documents to storage: ```python exec="true" session="groups" source="above" result="ansi" @@ -105,8 +171,7 @@ Diagnostic information about arrays and groups is available via the `info` property. E.g.: ```python exec="true" session="groups" source="above" result="ansi" -store = zarr.storage.MemoryStore() -root = zarr.group(store=store) +root = zarr.group(store="memory://diagnostics-demo") foo = root.create_group('foo') bar = foo.create_array(name='bar', shape=1000000, chunks=100000, dtype='int64') bar[:] = 42 @@ -132,4 +197,3 @@ Groups also have the [`zarr.Group.tree`][] method, e.g.: ```python exec="true" session="groups" source="above" result="ansi" print(root.tree()) ``` - diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index ff6e354d80..6b9a547776 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -7,7 +7,7 @@ Welcome to the user guide, where you can learn more about using Zarr-Python! New to Zarr-Python? Start here: - **[Installation](installation.md)** - Install Zarr-Python -- **[Quick-start](../quick-start.md)** - Quick overview of core functionality +- **[Quick start](../quick-start.md)** - Quick overview of core functionality ## Core Concepts @@ -15,7 +15,7 @@ Learn the essential building blocks: - **[Arrays](arrays.md)** - Learn the fundamentals of working with arrays - **[Groups](groups.md)** - Organize your data with groups -- **[Attributes](attributes.md)** - Configure metadata to your data structures +- **[Attributes](attributes.md)** - Attach metadata to your arrays and groups - **[Storage](storage.md)** - Learn how data is stored and accessed ## Configuration & Setup @@ -23,6 +23,7 @@ Learn the essential building blocks: Customize your experience: - **[Runtime Configuration](config.md)** - Configure Zarr-Python for your needs +- **[Command-Line Interface](cli.md)** - Migrate and manage Zarr metadata from the terminal - **[V3 Migration](v3_migration.md)** - Upgrading from version 2 to version 3 ## Advanced Topics @@ -34,6 +35,14 @@ Take your skills to the next level: - **[GPU](gpu.md)** - Leverage GPU acceleration - **[Extending](extending.md)** - Extend functionality with custom code - **[Consolidated Metadata](consolidated_metadata.md)** - Advanced metadata management +- **[Experimental Features](experimental.md)** - Preview features that may change at any time + +## Examples + +Worked, end-to-end examples: + +- **[Custom Data Type](examples/custom_dtype.md)** - Extend Zarr-Python with a user-defined data type +- **[Rectilinear Chunk Grids](examples/rectilinear_chunks.md)** - Use variable-sized chunks along each dimension ## Reference diff --git a/docs/user-guide/installation.md b/docs/user-guide/installation.md index 6c1414e81a..a7487e83c8 100644 --- a/docs/user-guide/installation.md +++ b/docs/user-guide/installation.md @@ -4,13 +4,13 @@ Required dependencies include: -- [Python](https://docs.python.org/3/) (3.11 or later) -- [packaging](https://packaging.pypa.io) (22.0 or later) +- [Python](https://docs.python.org/3/) (3.12 or later) +- [packaging](https://packaging.pypa.io/en/stable/) (22.0 or later) - [numpy](https://numpy.org) (2.0 or later) -- [numcodecs](https://numcodecs.readthedocs.io) (0.14 or later) +- [numcodecs](https://numcodecs.readthedocs.io/en/stable/) (0.14 or later) - [google-crc32c](https://github.com/googleapis/python-crc32c) (1.5 or later) -- [typing_extensions](https://typing-extensions.readthedocs.io) (4.9 or later) -- [donfig](https://donfig.readthedocs.io) (0.8 or later) +- [typing_extensions](https://typing-extensions.readthedocs.io/en/latest/) (4.14 or later) +- [donfig](https://donfig.readthedocs.io/en/latest/) (0.8 or later) ## pip @@ -23,10 +23,11 @@ pip install zarr There are a number of optional dependency groups you can install for extra functionality. These can be installed using `pip install "zarr[]"`, e.g. `pip install "zarr[gpu]"` -- `gpu`: support for GPUs -- `remote`: support for reading/writing to remote data stores - -Additional optional dependencies include `universal_pathlib`. These must be installed separately. +- `remote`: support for reading/writing to remote data stores (fsspec, obstore) +- `gpu`: support for GPUs (cupy) +- `cli`: support for the `zarr` [command-line interface](cli.md) (typer) +- `optional`: support for path-like access to local and remote stores (universal-pathlib) +- `cast-value-rs`: support for the `cast_value` codec (cast-value-rs) ## conda @@ -39,7 +40,7 @@ conda install -c conda-forge zarr Conda does not support optional dependencies, so you will have to manually install any packages needed to enable extra functionality. -# Nightly wheels +## Nightly wheels Development wheels are built nightly and published to the [scientific-python-nightly-wheels](https://anaconda.org/scientific-python-nightly-wheels) index. To install the latest nightly build: @@ -48,6 +49,7 @@ pip install --pre --extra-index-url https://pypi.anaconda.org/scientific-python- ``` Note that nightly wheels may be unstable and are intended for testing purposes. + ## Dependency support Zarr has endorsed [Scientific-Python SPEC 0](https://scientific-python.org/specs/spec-0000/) and now follows the version support window as outlined below: @@ -57,4 +59,4 @@ Zarr has endorsed [Scientific-Python SPEC 0](https://scientific-python.org/specs ## Development -To install the latest development version of Zarr, see the contributing guide. +To install the latest development version of Zarr, see the [contributing guide](../contributing.md). diff --git a/docs/user-guide/performance.md b/docs/user-guide/performance.md index 0e0fa3cd55..52c1cf0d71 100644 --- a/docs/user-guide/performance.md +++ b/docs/user-guide/performance.md @@ -81,37 +81,44 @@ z6 = zarr.create_array(store={}, shape=(10000, 10000, 1000), shards=(1000, 1000, print(z6.info) ``` -`shards` can be `"auto"` as well, in which case the `array.target_shard_size_bytes` setting can be used to control the size of shards (i.e., the size of the chunks cumulatively and uncompressed within the shard will be as close to, without being bigger than, `array.target_shard_size_bytes`); otherwise, a default is used. +`shards` can be `"auto"` as well, in which case Zarr chooses a shard shape for you. +The `array.target_shard_size_bytes` configuration setting controls this choice: the +cumulative uncompressed size of the chunks within each shard will be as close as +possible to, without exceeding, that target. If the setting is `None` (the default), +Zarr falls back to a built-in heuristic for choosing the shard shape. ### Chunk memory layout -The order of bytes **within each chunk** of an array can be changed via the -`order` config option, to use either C or Fortran layout. For -multi-dimensional arrays, these two layouts may provide different compression -ratios, depending on the correlation structure within the data. E.g.: +The memory layout of the in-memory arrays that Zarr produces and consumes can be +changed via the `order` config option, to use either C or Fortran layout. This can +matter for performance when the data is passed to other libraries that expect a +particular memory layout. E.g.: ```python exec="true" session="performance" source="above" result="ansi" import numpy as np -a = np.arange(100000000, dtype='int32').reshape(10000, 10000).T -c = zarr.create_array(store={}, shape=a.shape, chunks=(1000, 1000), dtype=a.dtype, config={'order': 'C'}) -c[:] = a -print(c.info_complete()) +c = zarr.create_array(store={}, shape=(10000, 10000), chunks=(1000, 1000), dtype='int32', config={'order': 'C'}) +print(c[:100, :100].flags.c_contiguous) ``` ```python exec="true" session="performance" source="above" result="ansi" with zarr.config.set({'array.order': 'F'}): - f = zarr.create_array(store={}, shape=a.shape, chunks=(1000, 1000), dtype=a.dtype) - f[:] = a -print(f.info_complete()) - + f = zarr.create_array(store={}, shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +print(f[:100, :100].flags.f_contiguous) ``` -In the above example, Fortran order gives a better compression ratio. This is an -artificial example but illustrates the general point that changing the order of -bytes within chunks of an array may improve the compression ratio, depending on -the structure of the data, the compression algorithm used, and which compression -filters (e.g., byte-shuffle) have been applied. +Note that for Zarr format 3 arrays the `order` option only affects the in-memory +layout: the bytes written to storage are identical for both settings. The layout of +the serialized data is instead determined by the array's codecs (e.g. the transpose +codec), which can change how well the data compresses depending on the correlation +structure within the data and which compression filters (e.g., byte-shuffle) have +been applied. + +### Subchunk memory layout + +The order of chunks **within each shard** can be changed via the `subchunk_write_order` parameter of the `ShardingCodec`. That parameter is a string which must be one of `["morton", "unordered", "lexicographic", "colexicographic"]`. + +By default [`morton`](https://en.wikipedia.org/wiki/Z-order_curve) order provides good spatial locality. [`lexicographic` (i.e., row-major)](https://en.wikipedia.org/wiki/Row-_and_column-major_order), for example, may be better suited to "batched" workflows where some form of sequential reading through a fixed number of outer dimensions is desired, and `colexicographic` is its reverse. `unordered` makes no guarantee about the order in which subchunks are laid out within a shard. ### Empty chunks @@ -135,7 +142,7 @@ assert arr.config.write_empty_chunks == False ``` The following example illustrates the effect of the `write_empty_chunks` flag on -the time required to write an array with different values.: +the time required to write an array with different values: ```python exec="true" session="performance" source="above" result="ansi" import zarr @@ -175,12 +182,17 @@ for write_empty_chunks in (True, False): print(f'\nwrite_empty_chunks={write_empty_chunks}:\n\tRandom Data: {full[0]:.4f}s, {full[1]} objects stored\n\t Empty Data: {empty[0]:.4f}s, {empty[1]} objects stored\n') ``` -In this example, writing random data is slightly slower with `write_empty_chunks=True`, -but writing empty data is substantially faster and generates far fewer objects in storage. +In this example, writing random data is slightly slower with `write_empty_chunks=False`, +because every chunk must be checked for emptiness before it is stored. Writing empty +data with `write_empty_chunks=False` is substantially faster, however, and stores no +objects at all. ### Changing chunk shapes (rechunking) -Coming soon. +Zarr-Python does not yet provide a built-in way to change the chunk shape of an +existing array in place. Arrays can, however, be resized and appended to along any +dimension — see [Resizing and appending](arrays.md#resizing-and-appending) — and data +can be copied to a new array created with the desired chunk shape. ## Parallel computing and synchronization @@ -197,7 +209,7 @@ determines the maximum number of concurrent I/O operations. The default value is 10, which is a conservative value. You may get improved performance by tuning the concurrency limit. You can adjust this value based on your specific needs: -```python +```python exec="true" session="perf-concurrency" source="above" import zarr # Set concurrency for the current session @@ -208,30 +220,54 @@ zarr.config.set({'async.concurrency': 128}) ``` Higher concurrency values can improve throughput when: + - Working with remote storage (e.g., S3, GCS) where network latency is high - Reading/writing many small chunks in parallel - The storage backend can handle many concurrent requests Lower concurrency values may be beneficial when: + - Working with local storage with limited I/O bandwidth - Memory is constrained (each concurrent operation requires buffer space) - Using Zarr within a parallel computing framework (see below) +### Thread pool size (`threading.max_workers`) + +When synchronous Zarr code calls async operations internally, Zarr uses a +`ThreadPoolExecutor` to run those coroutines. The `threading.max_workers` +configuration option controls the maximum number of worker threads in that pool. +By default it is `None`, which lets Python choose the pool size (typically +`min(32, os.cpu_count() + 4)`). + +You can set it explicitly when you want more predictable resource usage: + +```python exec="true" session="perf-workers" source="above" +import zarr + +zarr.config.set({'threading.max_workers': 8}) +``` + +Reducing this value can help avoid overloading the event loop when Zarr is used +inside a parallel computing framework such as Dask that already manages its own +thread pool (see the Dask section below). Increasing it may improve throughput +in CPU-bound workloads where many synchronous-to-async dispatches happen +concurrently. + ### Using Zarr with Dask [Dask](https://www.dask.org/) is a popular parallel computing library that works well with Zarr for processing large arrays. When using Zarr with Dask, it's important to consider the interaction between Dask's thread pool and Zarr's concurrency settings. **Important**: When using many Dask threads, you may need to reduce both Zarr's `async.concurrency` and `threading.max_workers` settings to avoid creating too many concurrent operations. The total number of concurrent I/O operations can be roughly estimated as: -``` +```text total_concurrency ≈ dask_threads × zarr_async_concurrency ``` -For example, if you're running Dask with 10 threads and Zarr's default concurrency of 64, you could potentially have up to 640 concurrent operations, which may overwhelm your storage system or cause memory issues. +For example, if you're running Dask with 10 threads and Zarr's default concurrency of 10, you could potentially have up to 100 concurrent operations, which may overwhelm your storage system or cause memory issues. **Recommendation**: When using Dask with many threads, configure Zarr's concurrency settings: -```python +```python exec="false" reason="requires dask, which is not in the docs test environment" import zarr import dask.array as da @@ -254,7 +290,7 @@ result = arr.mean(axis=0).compute() **Configuration guidelines for Dask workloads**: - `async.concurrency`: Controls the maximum number of concurrent async I/O operations. Start with a lower value (e.g., 4-8) when using many Dask threads. -- `threading.max_workers`: Controls Zarr's internal thread pool size for blocking operations (defaults to CPU count). Reduce this to avoid thread contention with Dask's scheduler. +- `threading.max_workers`: Controls Zarr's internal thread pool size for blocking operations (defaults to `None`, letting Python choose the pool size). Reduce this to avoid thread contention with Dask's scheduler. You may need to experiment with different values to find the optimal balance for your workload. Monitor your system's resource usage and adjust these settings based on whether your storage system or CPU is the bottleneck. @@ -263,6 +299,7 @@ You may need to experiment with different values to find the optimal balance for Zarr arrays are designed to be thread-safe for concurrent reads and writes from multiple threads within the same process. However, proper synchronization is required when writing to overlapping regions from multiple threads. For multi-process parallelism, Zarr provides safe concurrent writes as long as: + - Different processes write to different chunks - The storage backend supports atomic writes (most do) @@ -271,14 +308,17 @@ When writing to the same chunks from multiple processes, you should use external ## Pickle support Zarr arrays and groups can be pickled, as long as the underlying store object can be -pickled. With the exception of the `zarr.storage.MemoryStore`, any of the -storage classes provided in the `zarr.storage` module can be pickled. +pickled. All of the storage classes provided in the `zarr.storage` module can be pickled. -If an array or group is backed by a persistent store such as the a `zarr.storage.LocalStore`, +If an array or group is backed by a persistent store such as a `zarr.storage.LocalStore`, `zarr.storage.ZipStore` or `zarr.storage.FsspecStore` then the store data **are not** pickled. The only thing that is pickled is the necessary parameters to allow the store to re-open any underlying files or databases upon being unpickled. +Note that pickling a `zarr.storage.MemoryStore` copies the data it holds into the +pickle stream: unpickling produces an independent in-memory copy, so a `MemoryStore` +cannot be used to share data between processes. + E.g., pickle/unpickle a local store array: ```python exec="true" session="performance" source="above" result="ansi" @@ -291,7 +331,3 @@ z2 = pickle.loads(s) assert z1 == z2 print(np.all(z1[:] == z2[:])) ``` - -## Configuring Blosc - -Coming soon. diff --git a/docs/user-guide/storage.md b/docs/user-guide/storage.md index e75cd21381..a34e2e2874 100644 --- a/docs/user-guide/storage.md +++ b/docs/user-guide/storage.md @@ -1,7 +1,7 @@ # Storage guide Zarr-Python supports multiple storage backends, including: local file systems, -Zip files, remote stores via [fsspec](https://filesystem-spec.readthedocs.io) (S3, HTTP, etc.), and in-memory stores. In +Zip files, remote stores via [fsspec](https://filesystem-spec.readthedocs.io/en/latest/) (S3, HTTP, etc.), and in-memory stores. In Zarr-Python 3, stores must implement the abstract store API from [`zarr.abc.store.Store`][]. @@ -12,19 +12,19 @@ Zarr-Python 3, stores must implement the abstract store API from ## Implicit Store Creation In most cases, it is not required to create a `Store` object explicitly. Passing a string -(or other [StoreLike value](#storelike)) to Zarr's top level API will result in the store +(or other [StoreLike value](#user-guide-store-like)) to Zarr's top level API will result in the store being created automatically: ```python exec="true" session="storage" source="above" result="ansi" import zarr -# Implicitly create a writable LocalStore +# Implicitly creates a writable LocalStore group = zarr.create_group(store='data/foo/bar') print(group) ``` ```python exec="true" session="storage" source="above" result="ansi" -# Implicitly create a read-only FsspecStore +# Implicitly creates a read-only FsspecStore # Note: requires s3fs to be installed group = zarr.open_group( store='s3://noaa-nwm-retro-v2-zarr-pds', @@ -41,17 +41,18 @@ group = zarr.create_group(store=data) print(group) ``` -[](){#user-guide-store-like} -### StoreLike +### StoreLike {#user-guide-store-like} `StoreLike` values can be: - a `Path` or string indicating a location on the local file system. This will create a [local store](#local-store): + ```python exec="true" session="storage" source="above" result="ansi" group = zarr.open_group(store='data/foo/bar') print(group) ``` + ```python exec="true" session="storage" source="above" result="ansi" from pathlib import Path group = zarr.open_group(store=Path('data/foo/bar')) @@ -59,6 +60,7 @@ print(group) ``` - an FSSpec URI string, indicating a [remote store](#remote-store) location: + ```python exec="true" session="storage" source="above" result="ansi" # Note: requires s3fs to be installed group = zarr.open_group( @@ -70,10 +72,12 @@ print(group) ``` - an empty dictionary or None, which will create a new [memory store](#memory-store): + ```python exec="true" session="storage" source="above" result="ansi" group = zarr.create_group(store={}) print(group) ``` + ```python exec="true" session="storage" source="above" result="ansi" group = zarr.create_group(store=None) print(group) @@ -86,6 +90,16 @@ print(group) - an FSSpec [FSMap object](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.FSMap), which will create an [FsspecStore](#remote-store). +- a [universal-pathlib](https://github.com/fsspec/universal_pathlib) `UPath`, which will create an + [FsspecStore](#remote-store), or a [local store](#local-store) if the `UPath` is local. Put your + storage options on the `UPath` itself; passing a separate `storage_options` argument alongside + one raises `TypeError`. + + ```python exec="false" reason="requires universal-pathlib, which is not in the docs environment" + from upath import UPath + group = zarr.open_group(UPath('s3://noaa-nwm-retro-v2-zarr-pds', anon=True), mode='r') + ``` + - a [`Store`][zarr.abc.store.Store] or [`StorePath`][zarr.storage.StorePath] - see explicit store creation below. @@ -117,12 +131,25 @@ array = zarr.create_array(store=store, shape=(2,), dtype='float64') print(array) ``` +In place of a path, `ZipStore` also accepts an open binary file object (for +example a file opened with `fsspec`, or an `obstore` reader), enabling zip +archives on remote storage. The file must stay open for as long as the store +is in use: + +```python exec="true" session="storage" source="above" result="ansi" +store.close() +f = open('data.zip', mode='rb') # must stay open while the store is used +array = zarr.open_array(store=zarr.storage.ZipStore(f), mode='r') +print(array[:]) +f.close() +``` + ### Remote Store -The [`zarr.storage.FsspecStore`][] stores the contents of a Zarr hierarchy in following the same +The [`zarr.storage.FsspecStore`][] stores the contents of a Zarr hierarchy following the same logical layout as the [`LocalStore`][zarr.storage.LocalStore], except the store is assumed to be on a remote storage system such as cloud object storage (e.g. AWS S3, Google Cloud Storage, Azure Blob Store). The -[`zarr.storage.FsspecStore`][] is backed by [fsspec](https://filesystem-spec.readthedocs.io) and can support any backend +[`zarr.storage.FsspecStore`][] is backed by [fsspec](https://filesystem-spec.readthedocs.io/en/latest/) and can support any backend that implements the [AbstractFileSystem](https://filesystem-spec.readthedocs.io/en/stable/api.html#fsspec.spec.AbstractFileSystem) API. `storage_options` can be used to configure the fsspec backend: @@ -138,24 +165,24 @@ print(group) ``` The type of filesystem (e.g. S3, https, etc..) is inferred from the scheme of the url (e.g. s3 for "**s3**://noaa-nwm-retro-v2-zarr-pds"). -In case a specific filesystem is needed, one can explicitly create it. For example to create an S3 filesystem: +In case a specific filesystem is needed, one can explicitly create it. For example to create an S3 filesystem +(note that the filesystem must be created with `asynchronous=True`): ```python exec="true" session="storage" source="above" result="ansi" # Note: requires s3fs to be installed import fsspec -fs = fsspec.filesystem( - 's3', anon=True, asynchronous=True, - client_kwargs={'endpoint_url': "https://noaa-nwm-retro-v2-zarr-pds.s3.amazonaws.com"} -) -store = zarr.storage.FsspecStore(fs) +fs = fsspec.filesystem('s3', anon=True, asynchronous=True) +store = zarr.storage.FsspecStore(fs, path='noaa-nwm-retro-v2-zarr-pds', read_only=True) print(store) ``` +When using an S3-compatible service other than AWS, pass the service endpoint to the +filesystem via `client_kwargs={'endpoint_url': 'https://...'}`. ### Memory Store -The [`zarr.storage.MemoryStore`][] an in-memory store that allows for serialization of -Zarr data (metadata and chunks) to a dictionary: +The [`zarr.storage.MemoryStore`][] stores Zarr data (metadata and chunks) in an +in-memory dictionary: ```python exec="true" session="storage" source="above" result="ansi" data = {} @@ -199,3 +226,5 @@ print(group.info) Zarr-Python [`zarr.abc.store.Store`][] API is meant to be extended. The Store Abstract Base Class includes all of the methods needed to be a fully operational store in Zarr Python. Zarr also provides a test harness for custom stores: [`zarr.testing.store.StoreTests`][]. +See the [Custom stores](extending.md#custom-stores) section of the extending guide for +more on implementing your own store. diff --git a/docs/user-guide/v3_migration.md b/docs/user-guide/v3_migration.md index d5a8067a88..4d97963be2 100644 --- a/docs/user-guide/v3_migration.md +++ b/docs/user-guide/v3_migration.md @@ -16,6 +16,12 @@ migrate your code from version 2 to version 3. If we have missed anything, pleas open a [GitHub issue](https://github.com/zarr-developers/zarr-python/issues/new) so we can improve this guide. +!!! tip + This page is about migrating your *code* from the Zarr-Python 2 API to the + Zarr-Python 3 API. If you want to migrate the *metadata* of stored data from + Zarr format 2 to Zarr format 3, see the `zarr migrate` command described in + the [command-line interface documentation](cli.md). + ## Compatibility target The goals described above necessitated some breaking changes to the API (hence the @@ -36,34 +42,40 @@ the following actions in order: will be compatible in Zarr-Python 3. However, the following breaking API changes are planned: - - `numcodecs.*` will no longer be available in `zarr.*`. To migrate, import codecs - directly from `numcodecs`: - - ```python - from numcodecs import Blosc - # instead of: - # from zarr import Blosc - ``` - - - The `zarr.v3_api_available` feature flag is being removed. In Zarr-Python 3 - the v3 API is always available, so you shouldn't need to use this flag. - - The following internal modules are being removed or significantly changed. If - your application relies on imports from any of the below modules, you will need - to either a) modify your application to no longer rely on these imports or b) - vendor the parts of the specific modules that you need. - - * `zarr.attrs` has gone, with no replacement - * `zarr.codecs` has changed, see "Codecs" section below for more information - * `zarr.context` has gone, with no replacement - * `zarr.core` remains but should be considered private API - * `zarr.hierarchy` has gone, with no replacement (use `zarr.Group` inplace of `zarr.hierarchy.Group`) - * `zarr.indexing` has gone, with no replacement - * `zarr.meta` has gone, with no replacement - * `zarr.meta_v1` has gone, with no replacement - * `zarr.sync` has gone, with no replacement - * `zarr.types` has gone, with no replacement - * `zarr.util` has gone, with no replacement - * `zarr.n5` has gone, see below for an alternative N5 options + - `numcodecs.*` will no longer be available in `zarr.*`. To migrate, import codecs + directly from `numcodecs`: + + ```python exec="false" reason="intentionally shows the old/incorrect import for contrast" + from numcodecs import Blosc + # instead of: + # from zarr import Blosc + ``` + + - The `zarr.v3_api_available` feature flag is being removed. In Zarr-Python 3 + the v3 API is always available, so you shouldn't need to use this flag. + - `zarr.errors` has been consolidated. Several exception classes from + Zarr-Python 2 (such as `zarr.errors.PathNotFoundError`) have been removed + or replaced. For example, missing nodes now raise `zarr.errors.NodeNotFoundError` + (which subclasses both `BaseZarrError` and `FileNotFoundError`) instead of + `zarr.errors.PathNotFoundError`. Review any code that catches exceptions + from `zarr.errors` after migrating. + - The following internal modules are being removed or significantly changed. If + your application relies on imports from any of the below modules, you will need + to either a) modify your application to no longer rely on these imports or b) + vendor the parts of the specific modules that you need. + + * `zarr.attrs` has gone, with no replacement + * `zarr.codecs` has changed, see "Codecs" section below for more information + * `zarr.context` has gone, with no replacement + * `zarr.core` remains but should be considered private API + * `zarr.hierarchy` has gone, with no replacement (use `zarr.Group` in place of `zarr.hierarchy.Group`) + * `zarr.indexing` has gone, with no replacement + * `zarr.meta` has gone, with no replacement + * `zarr.meta_v1` has gone, with no replacement + * `zarr.sync` has gone, with no replacement + * `zarr.types` has gone, with no replacement + * `zarr.util` has gone, with no replacement + * `zarr.n5` has gone, see below for an alternative N5 option 3. Test that your package works with version 3. 4. Update the pin to include `zarr>=3,<4`. @@ -71,8 +83,9 @@ the following actions in order: ## Zarr-Python 2 support window Zarr-Python 2.x is still available, though we recommend migrating to Zarr-Python 3 for -its performance improvements and new features. Security and bug fixes will be made to -the 2.x series for at least six months following the first Zarr-Python 3 release. +its performance improvements and new features. Security and bug fixes were made to +the 2.x series for six months following the first Zarr-Python 3 release (January 2025); +the 2.x series is no longer actively maintained. If you need to use the latest Zarr-Python 2 release, you can install it with: ```console @@ -97,7 +110,7 @@ The following sections provide details on breaking changes in Zarr-Python 3. 2. Defaulting to `zarr_format=3` - newly created arrays will use the version 3 of the Zarr specification. To continue using version 2, set `zarr_format=2` when creating arrays - or set `default_zarr_version=2` in Zarr's runtime configuration. + or set `default_zarr_format=2` in Zarr's runtime configuration. 3. Function signature change to [`zarr.Array.resize`][] - the `resize` function now takes a `zarr.core.common.ShapeLike` input rather than separate arguments for each dimension. @@ -107,17 +120,27 @@ The following sections provide details on breaking changes in Zarr-Python 3. 1. Disallow direct construction - use [`zarr.open_group`][] or [`zarr.create_group`][] instead of directly constructing the `zarr.Group` class. -2. Most of the h5py compatibility methods are deprecated and will issue warnings if used. - The following functions are drop in replacements that have the same signature and functionality: +2. The h5py compatibility methods `create_dataset` and `require_dataset` have been removed. + Use the following replacements: + + - [`zarr.Group.create_array`][] in place of `Group.create_dataset` + - [`zarr.Group.require_array`][] in place of `Group.require_dataset` - - Use [`zarr.Group.create_array`][] in place of `zarr.Group.create_dataset` - - Use [`zarr.Group.require_array`][] in place of `zarr.Group.require_dataset` 3. Disallow "." syntax for getting group members. To get a member of a group named `foo`, use `group["foo"]` in place of `group.foo`. +4. The `zarr.storage.init_group` low-level helper function has been removed. Use + [`zarr.open_group`][] or [`zarr.create_group`][] instead: + + ```diff + - from zarr.storage import init_group + - init_group(store, overwrite=True, path="my/path") + + import zarr + + zarr.open_group(store, mode="w", path="my/path") + ``` ### The Store class -The Store API has changed significant in Zarr-Python 3. +The Store API has changed significantly in Zarr-Python 3. #### The base store class @@ -142,11 +165,9 @@ The following stores have been renamed or changed: | `DirectoryStore` | [`zarr.storage.LocalStore`][] | | `FSStore` | [`zarr.storage.FsspecStore`][] | | `TempStore` | Use [`tempfile.TemporaryDirectory`][] with [`LocalStore`][zarr.storage.LocalStore] | -| `zarr. - A number of deprecated stores were also removed. -See issue #1274 for more details on the removal of these stores. +See [issue #1274](https://github.com/zarr-developers/zarr-python/issues/1274) for more details on the removal of these stores. - `N5Store` - see https://github.com/zarr-developers/n5py for an alternative interface to N5 formatted data. @@ -160,7 +181,7 @@ See issue #1274 for more details on the removal of these stores. The latter five stores in this list do not have an equivalent in Zarr-Python 3. If you are interested in developing a custom store that targets these backends, see -[developing custom stores](storage.md/#developing-custom-stores) or open an +[developing custom stores](storage.md#developing-custom-stores) or open an [issue](https://github.com/zarr-developers/zarr-python/issues) to discuss your use case. ### Codecs @@ -186,44 +207,38 @@ When installing using `pip`: ### Miscellaneous -- The keyword argument `zarr_version` available in most creation functions in `zarr` +- The keyword argument `zarr_version` in most creation functions in `zarr` (e.g. [`zarr.create`][], [`zarr.open`][], [`zarr.group`][], [`zarr.array`][]) has - been deprecated in favor of `zarr_format`. + been removed. Use `zarr_format` instead. -## 🚧 Work in Progress 🚧 +## Unimplemented Zarr-Python 2 features -Zarr-Python 3 is still under active development, and is not yet fully complete. -The following list summarizes areas of the codebase that we expect to build out -after the 3.0.0 release. If features listed below are important to your use case +A few features of Zarr-Python 2 remain unimplemented in Zarr-Python 3. +If any of the features listed below are important to your use case of Zarr-Python, please open (or comment on) a [GitHub issue](https://github.com/zarr-developers/zarr-python/issues/new). -- The following functions / methods have not been ported to Zarr-Python 3 yet: +The following functions / methods have not been ported to Zarr-Python 3: - * `zarr.copy` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) - * `zarr.copy_all` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) - * `zarr.copy_store` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) - * `zarr.Group.move` ([issue #2108](https://github.com/zarr-developers/zarr-python/issues/2108)) +- `zarr.copy` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) +- `zarr.copy_all` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) +- `zarr.copy_store` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) -- The following features (corresponding to function arguments to functions in - `zarr`) have not been ported to Zarr-Python 3 yet. Using these features +The following features (corresponding to function arguments to functions in + `zarr`) have not been ported to Zarr-Python 3. Using these features will raise a warning or a `NotImplementedError`: - * `cache_attrs` - * `cache_metadata` - * `chunk_store` ([issue #2495](https://github.com/zarr-developers/zarr-python/issues/2495)) - * `meta_array` - * `object_codec` ([issue #2617](https://github.com/zarr-developers/zarr-python/issues/2617)) - * `synchronizer` ([issue #1596](https://github.com/zarr-developers/zarr-python/issues/1596)) - * `dimension_separator` - -- The following features that were supported by Zarr-Python 2 have not been ported - to Zarr-Python 3 yet: - - * Structured arrays / dtypes ([issue #2134](https://github.com/zarr-developers/zarr-python/issues/2134)) - * Fixed-length string dtypes ([issue #2347](https://github.com/zarr-developers/zarr-python/issues/2347)) - * Datetime and timedelta dtypes ([issue #2616](https://github.com/zarr-developers/zarr-python/issues/2616)) - * Object dtypes ([issue #2616](https://github.com/zarr-developers/zarr-python/issues/2616)) - * Ragged arrays ([issue #2618](https://github.com/zarr-developers/zarr-python/issues/2618)) - * Groups and Arrays do not implement `__enter__` and `__exit__` protocols ([issue #2619](https://github.com/zarr-developers/zarr-python/issues/2619)) - * Default filters for object dtypes for Zarr format 2 arrays ([issue #2627](https://github.com/zarr-developers/zarr-python/issues/2627)) +- `cache_attrs` +- `cache_metadata` +- `chunk_store` ([issue #2495](https://github.com/zarr-developers/zarr-python/issues/2495)) +- `meta_array` +- `object_codec` ([issue #2617](https://github.com/zarr-developers/zarr-python/issues/2617)) +- `synchronizer` ([issue #1596](https://github.com/zarr-developers/zarr-python/issues/1596)) + +The following features that were supported by Zarr-Python 2 have not been ported + to Zarr-Python 3: + +- Object dtypes ([issue #2616](https://github.com/zarr-developers/zarr-python/issues/2616)) +- Ragged arrays ([issue #2618](https://github.com/zarr-developers/zarr-python/issues/2618)) +- Groups and Arrays do not implement `__enter__` and `__exit__` protocols ([issue #2619](https://github.com/zarr-developers/zarr-python/issues/2619)) +- Default filters for object dtypes for Zarr format 2 arrays ([issue #2627](https://github.com/zarr-developers/zarr-python/issues/2627)) diff --git a/examples/codec_pipeline_performance/README.md b/examples/codec_pipeline_performance/README.md new file mode 100644 index 0000000000..5d85412c29 --- /dev/null +++ b/examples/codec_pipeline_performance/README.md @@ -0,0 +1,59 @@ +# Codec Pipeline Performance + +This example compares the default `BatchedCodecPipeline` against the opt-in +`FusedCodecPipeline` on a sharded array, across two stores (memory and local) +and two codec regimes (uncompressed and gzip), at one worker and at `cpu_count`. + +A *codec pipeline* turns chunks of array data into stored bytes and back, running +the configured codecs and performing the storage IO. The default +`BatchedCodecPipeline` schedules both asynchronously -- roughly one coroutine per +chunk operation. That model pays off for high-latency stores, where there is +useful work to do while waiting on IO. For low-latency stores (in-process memory, +the local filesystem) the IO completes too quickly for the overlap to be worth +its cost, and the async scheduling becomes pure overhead. + +`FusedCodecPipeline` runs codec compute and synchronous IO synchronously, +removing that overhead. It is +[experimental](https://zarr.readthedocs.io/en/stable/user-guide/experimental/) +and opt-in; the default pipeline is unchanged. + +## What it shows + +- How to select a pipeline with `zarr.config.set`, and why the array must be + *created* inside the config block: the pipeline class is resolved at array + construction time and then travels with the array. +- That the benefit depends strongly on layout and on whether compression is in + play. Some configurations are slower under the fused pipeline -- the script + reports speedups below 1.00x rather than hiding them. +- That `codec_pipeline.max_workers` is read only by `FusedCodecPipeline`; the + default pipeline ignores it entirely. + +## Running + +```bash +uv run codec_pipeline_performance.py +``` + +The script has no arguments and writes only to an in-memory store. + +## Interpreting the output + +The numbers are specific to your CPU, your Python build, and the workload chosen +here. They are a measurement of your machine, not a published benchmark -- treat +a single run as indicative and re-measure against your own data and store before +switching pipelines in production. + +Two effects are worth watching for: + +- **The two codec regimes tell opposite stories about `max_workers`.** + Uncompressed IO is dominated by per-chunk *scheduling*, so `Fused (1 worker)` + is already fastest and a thread pool only adds overhead. gzip is genuinely + CPU-bound: a single worker compresses chunk after chunk sequentially and can + be *slower than the default*, while a thread pool spreads that compression + over cores and reclaims the win. That flip is why the fused pipeline is + threaded by default, and why pinning `max_workers=1` is worth it for + memory-backed uncompressed data. +- **Chunk size decides whether threading can help at all.** The 64×64 inner + chunks here are small enough that per-chunk scheduling dominates uncompressed + IO, yet large enough that per-chunk gzip is real work to parallelize. Much + coarser chunks leave the pool with too few items to spread. diff --git a/examples/codec_pipeline_performance/codec_pipeline_performance.py b/examples/codec_pipeline_performance/codec_pipeline_performance.py new file mode 100644 index 0000000000..b821f3e6a7 --- /dev/null +++ b/examples/codec_pipeline_performance/codec_pipeline_performance.py @@ -0,0 +1,214 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", +# "numpy", +# ] +# /// + +""" +Compare the `BatchedCodecPipeline` and the `FusedCodecPipeline`. + +The default `BatchedCodecPipeline` schedules storage IO and codec compute +asynchronously -- roughly one coroutine per chunk operation. For a *sharded* +array that means one coroutine per inner chunk inside every shard. That is the +right model for high-latency stores, where there is useful work to do while +waiting for IO. For low-latency stores (in-process memory, the local +filesystem) the IO completes too quickly for the overlap to pay for itself, and +the scheduling becomes pure overhead. + +The `FusedCodecPipeline` runs codec compute and synchronous IO synchronously, +removing that overhead. Whether it wins, and whether its thread pool helps, +depends on which resource is actually scarce: + + * Uncompressed IO is dominated by per-chunk *scheduling*, not compute. There + is nothing for a thread pool to parallelize, so a single worker is already + fastest and extra workers only add overhead. + * gzip is genuinely CPU-bound. A single worker compresses every chunk + sequentially and can be *slower than the default*, while a thread pool + spreads that compression across cores and reclaims the win. This is when + `max_workers > 1` earns its keep. + +Run it with: + + uv run codec_pipeline_performance.py + +Numbers are hardware-, layout-, and codec-dependent. Treat the output as a +measurement of *your* machine, not as a published benchmark. +""" + +from __future__ import annotations + +import operator +import os +import statistics +import tempfile +import timeit +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np + +import zarr +from zarr.storage import LocalStore, MemoryStore + +if TYPE_CHECKING: + from collections.abc import Callable + + from zarr.abc.store import Store + +BATCHED = "zarr.core.codec_pipeline.BatchedCodecPipeline" +FUSED = "zarr.core.codec_pipeline.FusedCodecPipeline" + +# gzip is CPU-bound to encode, which is exactly the regime where the thread +# pool matters. Level 6 is gzip's own default. +GZIP = {"name": "gzip", "configuration": {"level": 6}} + +# 4096x4096 int32 = 64 MiB, split into 16 shards of 1024x1024, each holding +# 16x16 = 256 inner chunks of 64x64 -> 4096 inner chunks in total. The chunks +# are small enough that per-chunk coroutine scheduling dominates uncompressed +# IO, yet large enough that per-chunk gzip is real work to spread over cores. +SHAPE = (4096, 4096) +SHARDS = (1024, 1024) +CHUNKS = (64, 64) +DTYPE = "int32" + +CONFIGS: tuple[tuple[str, dict[str, object]], ...] = ( + ("Batched (default)", {"codec_pipeline.path": BATCHED}), + ("Fused (1 worker)", {"codec_pipeline.path": FUSED, "codec_pipeline.max_workers": 1}), + ("Fused (cpu_count)", {"codec_pipeline.path": FUSED, "codec_pipeline.max_workers": None}), +) + + +def time_call(fn: Callable[[], object], repeat: int = 3) -> float: + """Median wall-clock seconds for one call to `fn`. + + `timeit.Timer` supplies `perf_counter` and disables the cyclic garbage + collector during each run, so a collection triggered by earlier work cannot + land inside a measurement. `number=1` because a single call here already + moves 64 MiB -- the per-call overhead `timeit` amortizes is irrelevant at + this scale. + """ + return statistics.median(timeit.Timer(fn).repeat(repeat=repeat, number=1)) + + +def measure( + settings: dict[str, object], + store: Store, + data: np.ndarray, + compressors: object, +) -> tuple[float, float]: + """Time one full write and one full read of `data` under `settings`. + + The whole operation runs inside `zarr.config.set`, not just the array + construction. The pipeline class is resolved when the array is built, but + `codec_pipeline.max_workers` is read *per operation*, so a timed call made + outside the config block would silently use whatever worker count was + globally in effect -- which makes every configuration look identical. + """ + everything = slice(None) + + def write_once() -> None: + with zarr.config.set(settings): + array = zarr.create_array( + store=store, + shape=SHAPE, + chunks=CHUNKS, + shards=SHARDS, + dtype=DTYPE, + compressors=compressors, + fill_value=0, + overwrite=True, + ) + operator.setitem(array, everything, data) + + write = time_call(write_once) + + # The bytes on disk are identical whichever pipeline wrote them, so reading + # back what we just wrote isolates read performance on the same data. + def read_once() -> object: + with zarr.config.set(settings): + return zarr.open_array(store=store, mode="r")[everything] + + read = time_call(read_once) + + if not np.array_equal(read_once(), data): + raise AssertionError("round trip mismatch") + return write, read + + +def make_store(kind: str, tmp: Path) -> Store: + if kind == "memory": + return MemoryStore() + return LocalStore(tmp / f"demo_{kind}_{os.getpid()}.zarr") + + +def main() -> None: + n_cpu = os.cpu_count() or 1 + + # Each regime gets the data that actually exercises it. `arange` is + # trivially compressible, which is fine when nothing compresses it, but it + # would make gzip finish almost instantly and hide the CPU-bound behavior + # this example is about. The noisy array keeps gzip genuinely busy. + n = int(np.prod(SHAPE)) + plain_data = np.arange(n, dtype=DTYPE).reshape(SHAPE) + noisy_data = np.random.default_rng(0).integers(0, 2**24, size=SHAPE, dtype=DTYPE) + + n_shards = int(np.prod([s // c for s, c in zip(SHAPE, SHARDS, strict=True)])) + per_shard = int(np.prod([s // c for s, c in zip(SHARDS, CHUNKS, strict=True)])) + print(f"zarr {zarr.__version__} | {n_cpu} CPUs") + print( + f"array {SHAPE} {DTYPE} = {plain_data.nbytes / 2**20:.0f} MiB | " + f"{n_shards} shards x {per_shard} inner chunks = {n_shards * per_shard} chunks\n" + ) + + with tempfile.TemporaryDirectory() as tmp: + for store_kind in ("memory", "local"): + for codec_label, compressors, data in ( + ("uncompressed", None, plain_data), + ("gzip-6 (CPU-bound)", GZIP, noisy_data), + ): + print(f"=== {store_kind} store / {codec_label} ===") + print( + f"{'pipeline':<22}{'write (s)':>11}{'vs base':>10}" + f"{'read (s)':>12}{'vs base':>10}" + ) + results: dict[str, tuple[float, float]] = {} + for label, settings in CONFIGS: + store = make_store(store_kind, Path(tmp)) + results[label] = measure(settings, store, data, compressors) + + base_write, base_read = results[CONFIGS[0][0]] + for label, (write, read) in results.items(): + print( + f"{label:<22}{write:>10.3f}{base_write / write:>9.1f}x" + f"{read:>11.3f}{base_read / read:>9.1f}x" + ) + + # The headline comparison: does the thread pool earn its keep? + single_write, single_read = results["Fused (1 worker)"] + pool_write, pool_read = results["Fused (cpu_count)"] + print( + f" workers (cpu_count vs 1 worker): " + f"write {single_write / pool_write:.1f}x " + f"read {single_read / pool_read:.1f}x" + ) + print() + + print( + "Reading it:\n" + " * Uncompressed IO is scheduling-bound, so Fused (1 worker) is already\n" + " fastest -- a thread pool has nothing to parallelize and only adds\n" + " overhead.\n" + " * gzip is CPU-bound, so Fused (1 worker) can be *slower* than the\n" + " default, while Fused (cpu_count) spreads compression across cores\n" + " and reclaims the win. That flip is why the fused pipeline is\n" + " threaded by default, and why pinning max_workers=1 is worth it for\n" + " memory-backed uncompressed data.\n" + " * `codec_pipeline.max_workers` is read only by the FusedCodecPipeline;\n" + " the default BatchedCodecPipeline ignores it." + ) + + +if __name__ == "__main__": + main() diff --git a/examples/custom_dtype/README.md b/examples/custom_dtype/README.md index c0722d0661..266f398ca8 100644 --- a/examples/custom_dtype/README.md +++ b/examples/custom_dtype/README.md @@ -1,4 +1,4 @@ -# Custom Data Type Example +# Custom Data Type This example demonstrates how to extend Zarr Python by defining a new data type. @@ -11,12 +11,17 @@ The example shows how to: ## Running the Example +The script declares its dependencies inline +([PEP 723](https://peps.python.org/pep-0723/)), so the easiest way to run it is +with [uv](https://docs.astral.sh/uv/), which installs them automatically: + ```bash -python examples/custom_dtype/custom_dtype.py +uv run examples/custom_dtype/custom_dtype.py ``` -Or run with uv: +Alternatively, run it with plain Python, in which case you must first install +`zarr`, `ml_dtypes`, and `pytest` yourself: ```bash -uv run examples/custom_dtype/custom_dtype.py +python examples/custom_dtype/custom_dtype.py ``` diff --git a/examples/custom_dtype/custom_dtype.py b/examples/custom_dtype/custom_dtype.py index ec38d782b6..53acb70f52 100644 --- a/examples/custom_dtype/custom_dtype.py +++ b/examples/custom_dtype/custom_dtype.py @@ -1,8 +1,8 @@ # /// script -# requires-python = ">=3.11" +# requires-python = ">=3.12" # dependencies = [ # "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", -# "ml_dtypes==0.5.1", +# "ml_dtypes==0.5.4", # "pytest==8.4.1" # ] # /// @@ -22,14 +22,9 @@ import pytest import zarr -from zarr.core.common import JSON, ZarrFormat -from zarr.core.dtype import ZDType, data_type_registry -from zarr.core.dtype.common import ( - DataTypeValidationError, - DTypeConfig_V2, - DTypeJSON, - check_dtype_spec_v2, -) +from zarr.dtype import ZDType, check_dtype_spec_v2, data_type_registry +from zarr.errors import DataTypeValidationError +from zarr.types import JSON, DTypeConfig_V2, DTypeJSON, ZarrFormat # This is the int2 array data type int2_dtype_cls = type(np.dtype("int2")) @@ -120,7 +115,7 @@ def _from_json_v3(cls: type[Self], data: DTypeJSON) -> Self: msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" raise DataTypeValidationError(msg) - @overload # type: ignore[override] + @overload def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal["int2"], None]: ... @overload @@ -145,7 +140,7 @@ def to_json( """ if zarr_format == 2: return {"name": "int2", "object_codec_id": None} - elif zarr_format == 3: + if zarr_format == 3: return self._zarr_v3_name raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover @@ -191,9 +186,11 @@ def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> int: """ # We could add a type check here, but we don't need to for this example val: int = int(data) # type: ignore[call-overload] - if val not in (-2, -1, 0, 1): - raise ValueError("Invalid value. Expected -2, -1, 0, or 1.") - return val + + if val in {-2, -1, 0, 1}: + return val + + raise ValueError("Invalid value. Expected -2, -1, 0, or 1.") def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> ml_dtypes.int2: """ @@ -220,7 +217,11 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> ml_dtypes. def test_custom_dtype(tmp_path: Path, zarr_format: ZarrFormat) -> None: # create array and write values z_w = zarr.create_array( - store=tmp_path, shape=(4,), dtype="int2", zarr_format=zarr_format, compressors=None + store=tmp_path, + shape=(4,), + dtype="int2", + zarr_format=zarr_format, + compressors=None, ) z_w[:] = [-1, -2, 0, 1] @@ -230,10 +231,7 @@ def test_custom_dtype(tmp_path: Path, zarr_format: ZarrFormat) -> None: print(z_r.info_complete()) # look at the array metadata - if zarr_format == 2: - meta_file = tmp_path / ".zarray" - else: - meta_file = tmp_path / "zarr.json" + meta_file = tmp_path / (".zarray" if zarr_format == 2 else "zarr.json") print(json.dumps(json.loads(meta_file.read_text()), indent=2)) @@ -242,4 +240,16 @@ def test_custom_dtype(tmp_path: Path, zarr_format: ZarrFormat) -> None: # Without the dummy configuration file, at test time pytest will attempt to use the # configuration file in the project root, which will error because Zarr is using some # plugins that are not installed in this example. - sys.exit(pytest.main(["-s", __file__, f"-c {__file__}"])) + sys.exit( + pytest.main( + [ + "-s", + __file__, + f"-c {__file__}", + # Suppress: "PytestAssertRewriteWarning: Module already imported so + # cannot be rewritten; zarr" + "-W", + "ignore::pytest.PytestAssertRewriteWarning", + ] + ) + ) diff --git a/examples/sharding_coalescing/README.md b/examples/sharding_coalescing/README.md new file mode 100644 index 0000000000..29ba08c9ce --- /dev/null +++ b/examples/sharding_coalescing/README.md @@ -0,0 +1,63 @@ +# Sharded Read Coalescing + +This example demonstrates byte-range coalescing for partial reads of sharded +arrays, a performance optimization added in Zarr-Python 3.3.0 and enabled by +default. + +A shard is one stored object containing many inner chunks, each occupying its own +byte range. Reading N inner chunks could mean N separate byte-range requests. +Because byte ranges are intervals, nearby ranges can be merged: `[a, b)` and +`[b, c)` together cover `[a, c)`, so a single request can serve both. Merging +trades reading some bytes you did not ask for against issuing fewer requests -- +worthwhile whenever a request is expensive, as with object storage. + +## What it shows + +- Reading scattered inner chunks from one shard with coalescing **off** issues + one store request per inner chunk; with the **default** settings the same read + collapses to a single request. +- The resulting wall-clock difference against a store with simulated latency. +- That coalescing changes only *how* data is fetched, never *what* is returned -- + the script asserts both configurations produce identical arrays. +- A case where coalescing changes nothing: a contiguous selection already has + adjacent byte ranges, so it merges under any setting. + +## Running + +```bash +uv run sharding_coalescing.py +``` + +## How the comparison is set up + +Two details make the effect observable, and both are worth understanding if you +adapt this script: + +- **The selection must have gaps.** A contiguous read produces adjacent byte + ranges that merge regardless of configuration. The strided selections skip + inner chunks, creating the gaps that the `sharding_coalesce_max_gap_bytes` + budget decides whether to bridge. +- **Latency must be charged per merged fetch.** The example defines a small + `WrapperStore` subclass that sleeps in `get`. It deliberately does *not* keep + `WrapperStore.get_ranges`, which forwards straight to the wrapped store and + would bypass the latency entirely; inheriting the `Store` ABC's `get_ranges` + instead runs the coalescer over its own `get`, so each merged fetch pays once. + + `zarr.testing.store` ships a ready-made `LatencyStore`, but importing it pulls + in `pytest`. Defining the wrapper inline keeps the example runnable with only + `zarr` and `numpy` installed. + +## Configuration + +Two settings control the behavior, both settable globally via `zarr.config` or +per array via `config=` on `zarr.create_array` / `Array.with_config`: + +| Setting | Default | Meaning | +| --- | --- | --- | +| `sharding_coalesce_max_gap_bytes` | 1 MiB | Merge two ranges only if the gap between them is no larger than this | +| `sharding_coalesce_max_bytes` | 16 MiB | Never let a merged read exceed this size | + +Setting the gap to `0` merges only exactly-adjacent ranges, which approximates +the pre-3.3.0 behavior; that is how the example emulates the old path. Raising +the gap reads more unwanted bytes in exchange for fewer round trips -- the right +value depends on how expensive a request is against how fast your link is. diff --git a/examples/sharding_coalescing/sharding_coalescing.py b/examples/sharding_coalescing/sharding_coalescing.py new file mode 100644 index 0000000000..5da62ed806 --- /dev/null +++ b/examples/sharding_coalescing/sharding_coalescing.py @@ -0,0 +1,226 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", +# "numpy", +# ] +# /// + +""" +Demonstrate byte-range coalescing for partial reads of sharded arrays. + +A shard is a single stored object holding many inner chunks, each occupying +its own byte range. Reading N inner chunks could mean issuing N separate +byte-range requests to the store. Because byte ranges are intervals, a reader +can instead merge nearby ranges: `[a, b)` and `[b, c)` together cover +`[a, c)`, so one request can serve both. Merging trades reading some bytes you +did not ask for against issuing fewer requests -- a good trade whenever a +request is expensive, which is the normal case for object storage. + +Zarr-Python 3.3.0 does this automatically. Two settings control it: + + * `sharding_coalesce_max_gap_bytes` (default 1 MiB) -- merge two ranges only + if the gap between them is no larger than this. + * `sharding_coalesce_max_bytes` (default 16 MiB) -- never let a merged read + exceed this size. + +Setting the gap to 0 disables merging of non-adjacent ranges, which +approximates the pre-3.3.0 behavior. This script compares the two, counting +store requests and measuring wall-clock time against a store with simulated +latency. + +Run it with: + + uv run sharding_coalescing.py +""" + +from __future__ import annotations + +import asyncio +import operator +import statistics +import timeit +from contextlib import contextmanager +from functools import partial +from typing import TYPE_CHECKING + +import numpy as np + +import zarr +import zarr.core._coalesce as coalesce_module +from zarr.abc.store import ByteRequest, RangeByteRequest, Store +from zarr.storage import MemoryStore, WrapperStore + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + + from zarr.core.buffer import Buffer, BufferPrototype + +# Emulates the pre-3.3.0 behavior: with a zero gap budget, only ranges that are +# exactly adjacent get merged, so scattered inner chunks are fetched one by one. +NO_COALESCING = {"sharding_coalesce_max_gap_bytes": 0} + +# The shipped defaults. Spelled out here so the comparison is explicit rather +# than relying on whatever the global config happens to be. +DEFAULT_COALESCING = { + "sharding_coalesce_max_gap_bytes": 1 << 20, # 1 MiB + "sharding_coalesce_max_bytes": 16 << 20, # 16 MiB +} + +GET_LATENCY_S = 0.005 # 5 ms per request, a modest stand-in for object storage + + +class PerRequestLatencyStore(WrapperStore[Store]): + """Wraps a store, charging a fixed latency per byte-range fetch. + + `zarr.testing.store` ships a `LatencyStore`, but importing it pulls in + `pytest`; defining the wrapper here keeps this example runnable with only + zarr and numpy installed. + + Two details matter for the measurement: + + * The latency is applied in `get`, which is what an individual fetch costs. + * `get_ranges` is explicitly *not* overridden to forward to the wrapped + store. `WrapperStore.get_ranges` does forward, which would skip this + class's `get` entirely and make every configuration look identical. + Inheriting the `Store` ABC's implementation instead runs the coalescer + over `self.get`, so each *merged* fetch pays the latency once -- which is + exactly the cost coalescing exists to reduce. + """ + + get_ranges = Store.get_ranges + + def __init__(self, store: Store, *, get_latency: float) -> None: + super().__init__(store) + self.get_latency = get_latency + + def _with_store(self, store: Store) -> PerRequestLatencyStore: + # `WrapperStore` rebuilds the wrapper when opening read-only, so the + # latency setting has to be carried across. + return type(self)(store, get_latency=self.get_latency) + + async def get( + self, + key: str, + prototype: BufferPrototype, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + await asyncio.sleep(self.get_latency) + return await self._store.get(key, prototype, byte_range) + + +@contextmanager +def counting_requests() -> Iterator[Callable[[], int]]: + """Count the store fetches issued inside the block. + + Wraps the coalescing planner rather than the store: every merged group it + returns, plus every range it declined to merge, becomes exactly one fetch. + Counting here rather than at the store means the number reported is the + planner's decision, which is precisely what the settings control. + """ + original = coalesce_module.coalesce_ranges + total = 0 + + def counting_coalesce_ranges( + byte_ranges: Sequence[ByteRequest | None], + *, + max_gap_bytes: int, + max_coalesced_bytes: int, + ) -> tuple[ + list[list[tuple[int, RangeByteRequest]]], + list[tuple[int, ByteRequest | None]], + ]: + nonlocal total + groups, uncoalescable = original( + byte_ranges, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ) + total += len(groups) + len(uncoalescable) + return groups, uncoalescable + + coalesce_module.coalesce_ranges = counting_coalesce_ranges + try: + yield lambda: total + finally: + coalesce_module.coalesce_ranges = original + + +def measure_read(array: zarr.Array, selection: slice) -> tuple[int, float]: + """Return (store fetches, median seconds) for reading `selection`.""" + read = partial(operator.getitem, array, selection) + + with counting_requests() as fetches: + result = read() + requests = fetches() + + # `timeit.Timer` supplies the loop, `perf_counter`, and GC handling. The + # median of several runs keeps one unlucky run from dominating. + elapsed = statistics.median(timeit.Timer(read).repeat(repeat=5, number=1)) + + assert result.size > 0 # a read that returned nothing would time as "fast" + return requests, elapsed + + +def main() -> None: + n = 8192 + chunk = 64 + inner_chunks = n // chunk + + base = MemoryStore() + source = (np.arange(n, dtype="uint64") % 251).astype("uint8") + + # One shard holding every inner chunk, uncompressed so inner-chunk byte + # offsets stay predictable and the demonstration is easy to reason about. + writable = zarr.create_array( + store=base, shape=(n,), chunks=(chunk,), shards=(n,), dtype="uint8", compressors=None + ) + writable[:] = source + + store = PerRequestLatencyStore(base, get_latency=GET_LATENCY_S) + + print(f"zarr {zarr.__version__}") + print(f"array: {n} uint8 values, {inner_chunks} inner chunks of {chunk} in a single shard") + print(f"store: MemoryStore wrapped with {GET_LATENCY_S * 1000:.0f} ms of latency per request\n") + + # A strided selection touches inner chunks with unread chunks in between, + # so there are real gaps for the coalescer to bridge. A contiguous + # selection would merge under any setting, since its ranges are adjacent. + selections = { + "every 2nd inner chunk": slice(None, None, chunk * 2), + "every 4th inner chunk": slice(None, None, chunk * 4), + "contiguous quarter": slice(0, n // 4), + } + + header = f"{'selection':<24} {'coalescing':<12} {'requests':>9} {'time':>10}" + print(header) + print("-" * len(header)) + + for label, selection in selections.items(): + results = {} + for mode, config in (("off", NO_COALESCING), ("default", DEFAULT_COALESCING)): + array = zarr.open_array(store=store, mode="r").with_config(config) + requests, elapsed = measure_read(array, selection) + results[mode] = (requests, elapsed) + print(f"{label:<24} {mode:<12} {requests:>9} {elapsed * 1000:>9.1f}ms") + + off_requests, off_time = results["off"] + on_requests, on_time = results["default"] + if on_requests < off_requests: + print( + f"{'':<24} {'->':<12} " + f"{off_requests // on_requests:>8}x fewer {off_time / on_time:>9.1f}x faster" + ) + else: + print(f"{'':<24} {'->':<12} {'no change (ranges already adjacent)':>30}") + print() + + # Correctness is the point: coalescing must not change what you read back. + for mode, config in (("off", NO_COALESCING), ("default", DEFAULT_COALESCING)): + array = zarr.open_array(store=store, mode="r").with_config(config) + assert np.array_equal(array[::128], source[::128]), mode + print("Both configurations return identical data; coalescing only changes how it is fetched.") + + +if __name__ == "__main__": + main() diff --git a/lychee.toml b/lychee.toml new file mode 100644 index 0000000000..54a5b49b8d --- /dev/null +++ b/lychee.toml @@ -0,0 +1,25 @@ +# Configuration for the lychee link checker (https://lychee.cli.rs/). +# Auto-discovered as ./lychee.toml by the lychee GitHub Action. + +# Treat redirect status codes as success rather than failures. +accept = ["200..=299"] + +# Files lychee should not scan for links. +exclude_path = [ + # mkdocs-material theme overrides: hrefs are Jinja expressions like + # `{{ '../' ~ base_url }}`, not real URLs, so lychee cannot resolve them. + "docs/overrides", + # Design notes: working records that point at transient artifacts (commits, + # fork branches, compare URLs) which are expected to disappear over time. + "design", +] + +# URL patterns to ignore (regex, matched against the full URL). +exclude = [ + # Local docs preview server shown in the contributing guide ("hatch run serve"), + # documentation of a command rather than a reachable link. + '^https?://0\.0\.0\.0', + '^https?://(localhost|127\.0\.0\.1)(:\d+)?', + # SPEC 0 page times out but is valid. + '^https://scientific-python\.org/specs/spec-0000', +] diff --git a/mkdocs.yml b/mkdocs.yml index 24adb66457..4d06701a87 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -17,65 +17,98 @@ nav: - user-guide/arrays.md - user-guide/groups.md - user-guide/attributes.md + - user-guide/data_types.md - user-guide/storage.md - user-guide/config.md - - user-guide/cli.md - - user-guide/v3_migration.md - - user-guide/data_types.md - user-guide/performance.md + - user-guide/cli.md - user-guide/extending.md - user-guide/gpu.md - user-guide/consolidated_metadata.md - user-guide/experimental.md + - user-guide/v3_migration.md - user-guide/glossary.md - Examples: - user-guide/examples/custom_dtype.md + - user-guide/examples/rectilinear_chunks.md + - user-guide/examples/codec_pipeline_performance.md + - user-guide/examples/sharding_coalescing.md + - subprojects.md - API Reference: - api/zarr/index.md - - api/zarr/array.md - - api/zarr/group.md - - api/zarr/create.md - - api/zarr/dtype.md - - api/zarr/load.md - - api/zarr/open.md - - api/zarr/save.md - - api/zarr/codecs.md - - api/zarr/codecs/numcodecs.md - - api/zarr/config.md - - api/zarr/convenience.md - - api/zarr/errors.md - - api/zarr/metadata.md - - api/zarr/registry.md - - api/zarr/storage.md - - api/zarr/experimental.md - - ABC: + - ' zarr.abc': - api/zarr/abc/index.md - - api/zarr/abc/buffer.md - - api/zarr/abc/codec.md - - api/zarr/abc/numcodec.md - - api/zarr/abc/metadata.md - - api/zarr/abc/store.md - - API: + - ' zarr.abc.buffer': api/zarr/abc/buffer.md + - ' zarr.abc.codec': api/zarr/abc/codec.md + - ' zarr.abc.metadata': api/zarr/abc/metadata.md + - ' zarr.abc.numcodec': api/zarr/abc/numcodec.md + - ' zarr.abc.store': api/zarr/abc/store.md + - ' zarr.api': - api/zarr/api/index.md - - api/zarr/api/asynchronous.md - - api/zarr/api/synchronous.md - - Buffer: + - ' zarr.api.asynchronous': api/zarr/api/asynchronous.md + - ' zarr.api.synchronous': api/zarr/api/synchronous.md + - ' zarr.Array': api/zarr/array.md + - ' zarr.array': api/zarr/functions/array.md + - ' zarr.buffer': - api/zarr/buffer/index.md - - api/zarr/buffer/cpu.md - - api/zarr/buffer/gpu.md - - Testing: + - ' zarr.buffer.cpu': api/zarr/buffer/cpu.md + - ' zarr.buffer.gpu': api/zarr/buffer/gpu.md + - ' zarr.codecs': api/zarr/codecs.md + - ' zarr.codecs.numcodecs': api/zarr/codecs/numcodecs.md + - ' zarr.config': api/zarr/config.md + - ' zarr.consolidate_metadata': api/zarr/functions/consolidate_metadata.md + - ' zarr.create': api/zarr/functions/create.md + - ' zarr.create_array': api/zarr/functions/create_array.md + - ' zarr.create_group': api/zarr/functions/create_group.md + - ' zarr.create_hierarchy': api/zarr/functions/create_hierarchy.md + - ' zarr.dtype': api/zarr/dtype.md + - ' zarr.empty': api/zarr/functions/empty.md + - ' zarr.empty_like': api/zarr/functions/empty_like.md + - ' zarr.errors': api/zarr/errors.md + - ' zarr.experimental': api/zarr/experimental.md + - ' zarr.from_array': api/zarr/functions/from_array.md + - ' zarr.full': api/zarr/functions/full.md + - ' zarr.full_like': api/zarr/functions/full_like.md + - ' zarr.Group': api/zarr/group.md + - ' zarr.group': api/zarr/functions/group.md + - ' zarr.load': api/zarr/functions/load.md + - ' zarr.metadata': api/zarr/metadata.md + - ' zarr.ones': api/zarr/functions/ones.md + - ' zarr.ones_like': api/zarr/functions/ones_like.md + - ' zarr.open': api/zarr/functions/open.md + - ' zarr.open_array': api/zarr/functions/open_array.md + - ' zarr.open_consolidated': api/zarr/functions/open_consolidated.md + - ' zarr.open_group': api/zarr/functions/open_group.md + - ' zarr.open_like': api/zarr/functions/open_like.md + - ' zarr.print_debug_info': api/zarr/functions/print_debug_info.md + - ' zarr.registry': api/zarr/registry.md + - ' zarr.save': api/zarr/functions/save.md + - ' zarr.save_array': api/zarr/functions/save_array.md + - ' zarr.save_group': api/zarr/functions/save_group.md + - ' zarr.storage': api/zarr/storage.md + - ' zarr.testing': - api/zarr/testing/index.md - - api/zarr/testing/buffer.md - - api/zarr/testing/conftest.md - - api/zarr/testing/stateful.md - - api/zarr/testing/store.md - - api/zarr/testing/strategies.md - - api/zarr/testing/utils.md - - deprecated: - - Convenience sub-module: api/zarr/deprecated/convenience.md - - Creation sub-module: api/zarr/deprecated/creation.md + - ' zarr.testing.buffer': api/zarr/testing/buffer.md + - ' zarr.testing.stateful': api/zarr/testing/stateful.md + - ' zarr.testing.store': api/zarr/testing/store.md + - ' zarr.testing.strategies': api/zarr/testing/strategies.md + - ' zarr.testing.utils': api/zarr/testing/utils.md + - ' zarr.zeros': api/zarr/functions/zeros.md + - ' zarr.zeros_like': api/zarr/functions/zeros_like.md + # The companion packages are Read the Docs subprojects of this one; link + # to the /projects/ paths Read the Docs advertises as canonical rather + # than to their standalone *.readthedocs.io domains, so following one + # 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/ - release-notes.md + - roadmap.md - contributing.md + - Blog: + - blog/index.md +hooks: + - mkdocs_hooks.py + watch: - src/zarr - docs @@ -131,6 +164,14 @@ extra_css: plugins: - autorefs + - blog: + blog_dir: blog + post_dir: "{blog}/posts" + post_url_format: "{slug}" + # The blog is a simple reverse-chronological list of posts; the archive + # and category indexes add navigation we don't have the volume to justify. + archive: false + categories: false - search - markdown-exec - mkdocstrings: @@ -159,6 +200,7 @@ plugins: - https://docs.xarray.dev/en/stable/objects.inv - https://numpy.org/doc/stable/objects.inv - https://numcodecs.readthedocs.io/en/stable/objects.inv + - https://msgspec.dev/objects.inv - https://developmentseed.org/obstore/latest/objects.inv - https://filesystem-spec.readthedocs.io/en/latest/objects.inv - https://requests.readthedocs.io/en/latest/objects.inv @@ -180,7 +222,6 @@ plugins: 'search.html.md': 'index.md' 'tutorial.md': 'user-guide/installation.md' 'getting-started.md': 'quick-start.md' - 'roadmap.md': 'https://zarr.readthedocs.io/en/v3.0.8/developers/roadmap.html' 'installation.md': 'user-guide/installation.md' 'release.md': 'release-notes.md' 'about.html.md': 'index.md' @@ -215,9 +256,11 @@ plugins: 'developers/contributing.html.md': 'contributing.md' 'developers/index.html.md': 'contributing.md' 'developers/roadmap.html.md': 'https://zarr.readthedocs.io/en/v3.0.8/developers/roadmap.html' - 'api/zarr/creation.md': 'api/zarr/deprecated/creation.md' - 'api/zarr/codecs/numcodecs.md': 'api/zarr/deprecated/creation.md' 'api.md': 'api/zarr/index.md' + 'api/zarr/create.md': 'api/zarr/functions/create.md' + 'api/zarr/open.md': 'api/zarr/functions/open.md' + 'api/zarr/save.md': 'api/zarr/functions/save.md' + 'api/zarr/load.md': 'api/zarr/functions/load.md' 'api/zarr/metadata/migrate_v3.md': 'api/zarr/metadata.md' # Based on https://github.com/developmentseed/titiler/blob/50934c929cca2fa8d3c408d239015f8da429c6a8/docs/mkdocs.yml#L115-L140 diff --git a/mkdocs_hooks.py b/mkdocs_hooks.py new file mode 100644 index 0000000000..88368926b9 --- /dev/null +++ b/mkdocs_hooks.py @@ -0,0 +1,82 @@ +"""MkDocs hook that renders validation-marked code fences as ordinary code blocks. + +The docs validation convention (see ``tests/test_docs.py`` and the contributing +guide) requires every python fence to carry ``exec="true"``, ``test="true"``, or +``exec="false" reason="..."``. Markdown Exec's superfences fence only claims +``exec="true"`` blocks; without this hook the remaining marked fences fail +superfences validation and their contents spill into the page as raw markdown +(e.g. the PEP 723 header of the custom dtype example rendered as headings). + +This hook registers a second ``python`` fence, tried when Markdown Exec's +declines, that strips the validation attributes and delegates to the standard +superfences highlighter so the block renders exactly like a plain code fence. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from markdown import Markdown + from mkdocs.config.defaults import MkDocsConfig + +# Mirrors markdown_exec's _to_bool: everything but these means "true". +_FALSY = {"", "no", "off", "false", "0"} + + +def _validator( + language: str, + inputs: dict[str, str], + options: dict[str, Any], + attrs: dict[str, Any], + md: Markdown, +) -> bool: + """Claim fences marked test="true" or exec="false"; leave the rest alone.""" + if "exec" not in inputs and "test" not in inputs: + # Plain fence: let the default superfences pathway highlight it. + return False + if str(inputs.get("exec", "false")).lower() not in _FALSY: + # Executable fence: Markdown Exec's own custom fence handles it. + return False + # Consume the validation attributes so they don't leak into the output. + inputs.clear() + return True + + +def _formatter( + source: str, + language: str, + css_class: str, + options: dict[str, Any], + md: Markdown, + classes: list[str] | None = None, + id_value: str = "", + attrs: dict[str, Any] | None = None, + **kwargs: Any, +) -> str: + """Render with the same highlighter superfences uses for plain fences.""" + fenced = md.preprocessors["fenced_code_block"] + fenced.get_hl_settings() + return fenced.highlight( + src=source, + language=language, + options={}, + md=md, + classes=classes, + id_value=id_value, + attrs=attrs or {}, + ) + + +def on_config(config: MkDocsConfig) -> MkDocsConfig: + superfences = config.setdefault("mdx_configs", {}).setdefault("pymdownx.superfences", {}) + custom_fences = superfences.setdefault("custom_fences", []) + custom_fences.append( + { + "name": "python", + "class": "python", + "validator": _validator, + "format": _formatter, + } + ) + return config diff --git a/packages/zarr-http-server/.readthedocs.yaml b/packages/zarr-http-server/.readthedocs.yaml new file mode 100644 index 0000000000..efbda6852d --- /dev/null +++ b/packages/zarr-http-server/.readthedocs.yaml @@ -0,0 +1,43 @@ +# Read the Docs configuration for the zarr-http-server docs site, separate from +# the zarr-python site configured by the repo-root .readthedocs.yaml. The RTD +# project for zarr-http-server must set its configuration-file path to +# packages/zarr-http-server/.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. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- packages/zarr-http-server; + then + exit 183; + fi + install: + - pip install --upgrade pip + - pip install ./packages/zarr-http-server --group packages/zarr-http-server/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-indexing 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-http-server && mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html + +mkdocs: + configuration: packages/zarr-http-server/mkdocs.yml diff --git a/packages/zarr-http-server/CHANGELOG.md b/packages/zarr-http-server/CHANGELOG.md new file mode 100644 index 0000000000..7c4bc92cad --- /dev/null +++ b/packages/zarr-http-server/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release notes + + diff --git a/packages/zarr-http-server/LICENSE.txt b/packages/zarr-http-server/LICENSE.txt new file mode 100644 index 0000000000..1e8da4d242 --- /dev/null +++ b/packages/zarr-http-server/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-http-server/README.md b/packages/zarr-http-server/README.md new file mode 100644 index 0000000000..53df0d2f50 --- /dev/null +++ b/packages/zarr-http-server/README.md @@ -0,0 +1,71 @@ +# zarr-http-server + +HTTP server for Zarr stores, arrays, and groups. + +Documentation: + +`zarr-http-server` exposes a Zarr `Store`, `Array`, or `Group` over HTTP via an +ASGI app, so any HTTP-capable client — including zarr-python itself, via +`FsspecStore` or `ObjectStore` — can read the data. The app is built on +[Starlette](https://www.starlette.io/) and can be run with any ASGI server; +the `serve` / `serve_background` helpers run it with +[Uvicorn](https://uvicorn.dev/). + +> [!WARNING] +> This package is experimental. Its API may change or be removed at any point. + +## Installation + +```bash +pip install zarr-http-server +``` + +## Quick start + +```python +import zarr +from zarr_http_server import node_app, serve_background + +store = zarr.storage.MemoryStore() +array = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="float64") + +with serve_background(node_app(array)) as server: + print(server.url) # e.g. http://127.0.0.1:8000 +``` + +Building an app and running it are separate steps, and either app works with +either runner: + +- **Build** with `store_app` to serve every key in a store, or `node_app` to + serve only the keys belonging to one `Array` or `Group` — requests for keys + outside that node return 404 even when those keys exist in the underlying + store. +- **Run** with `serve`, which blocks, or `serve_background`, which returns a + handle you can shut down later. + +Reads are all that is enabled by default: `GET` and `HEAD` are served, and +`PUT`, `POST`, `DELETE` and `PATCH` are answered with 405. + +> [!CAUTION] +> `store_app` applies no per-key filtering. Only point it at a store whose full +> contents are safe to serve, and note that enabling `PUT` grants write access +> to everything the store contains. The +> [user guide](https://zarr-http-server.readthedocs.io/en/latest/guide/#read-only-serving) +> covers the read-only guarantees available. + +The [user guide](https://zarr-http-server.readthedocs.io/en/latest/guide/) +covers byte ranges, CORS, writes, serving several nodes, running from a +notebook, and Uvicorn configuration. + +## Examples + +[`examples/`](examples/) holds a runnable script and a notebook, both executed +by the test suite so neither can drift from the code: + +```bash +uv run examples/serve.py +``` + +## License + +MIT — see [LICENSE.txt](LICENSE.txt). diff --git a/packages/zarr-http-server/changes/3732.feature.md b/packages/zarr-http-server/changes/3732.feature.md new file mode 100644 index 0000000000..accd91ab81 --- /dev/null +++ b/packages/zarr-http-server/changes/3732.feature.md @@ -0,0 +1,3 @@ +Initial release of `zarr-http-server`: an HTTP server exposing Zarr stores, +arrays, and groups over an ASGI app, extracted from the +`zarr.experimental.serve` prototype in zarr-python. diff --git a/packages/zarr-http-server/changes/README.md b/packages/zarr-http-server/changes/README.md new file mode 100644 index 0000000000..80f0be782c --- /dev/null +++ b/packages/zarr-http-server/changes/README.md @@ -0,0 +1,25 @@ +Writing a changelog entry for `zarr-http-server` +--------------------------------------------- + +Fragments in **this** directory are released notes for the `zarr-http-server` +package only — kept separate from the parent zarr-python `changes/` +directory so a PR touching only `packages/zarr-http-server/` 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-http-server`. + +A `zarr-http-server` release runs `towncrier build` in `packages/zarr-http-server/`, +which consumes the fragments here and updates `CHANGELOG.md`. Fragments +that describe parent zarr-python changes (not the server package) +belong in the top-level `changes/` directory, not here. diff --git a/packages/zarr-http-server/docs/_static/favicon-96x96.png b/packages/zarr-http-server/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000..e77977ccf4 Binary files /dev/null and b/packages/zarr-http-server/docs/_static/favicon-96x96.png differ diff --git a/packages/zarr-http-server/docs/_static/logo_bw.png b/packages/zarr-http-server/docs/_static/logo_bw.png new file mode 100644 index 0000000000..df1979d3cc Binary files /dev/null and b/packages/zarr-http-server/docs/_static/logo_bw.png differ diff --git a/packages/zarr-http-server/docs/api/index.md b/packages/zarr-http-server/docs/api/index.md new file mode 100644 index 0000000000..ce5d748b26 --- /dev/null +++ b/packages/zarr-http-server/docs/api/index.md @@ -0,0 +1,41 @@ +--- +title: API reference +--- + +# API reference + +Everything public is re-exported from the top-level `zarr_http_server` +namespace; the private `_serve` and `_keys` modules are implementation detail +and carry no compatibility guarantee. + +## Building an app + +::: zarr_http_server.store_app + +::: zarr_http_server.node_app + +## Running a server + +::: zarr_http_server.serve + +::: zarr_http_server.serve_background + +::: zarr_http_server.BackgroundServer + +## Configuration + +::: zarr_http_server.CorsOptions + +::: zarr_http_server.HTTPMethod + +::: zarr_http_server.ReadOnlyHTTPMethod + +::: zarr_http_server.READ_ONLY_HTTP_METHODS + +::: zarr_http_server.READ_WRITE_HTTP_METHODS + +::: zarr_http_server.AUTO_PORT + +::: zarr_http_server.DEFAULT_PORT + +::: zarr_http_server.DEFAULT_MAX_BODY_SIZE diff --git a/packages/zarr-http-server/docs/guide.md b/packages/zarr-http-server/docs/guide.md new file mode 100644 index 0000000000..d52d5b882d --- /dev/null +++ b/packages/zarr-http-server/docs/guide.md @@ -0,0 +1,393 @@ +--- +title: User guide +--- + +# User guide + +## Building an ASGI app + +[`store_app`][zarr_http_server.store_app] creates an ASGI app that exposes +every key in a store. Only point it at a store whose full contents are safe to +serve publicly — it grants read (and, if `PUT` is enabled, write) access to +everything the store contains, with no per-key filtering: + +```python +import zarr +from zarr_http_server import store_app + +store = zarr.storage.MemoryStore() +zarr.create_array(store, shape=(100, 100), chunks=(10, 10), dtype="float64") + +app = store_app(store) + +# Run with any ASGI server, e.g. Uvicorn: +# uvicorn my_module:app --host 0.0.0.0 --port 8000 +``` + +[`node_app`][zarr_http_server.node_app] creates an ASGI app that only serves +keys belonging to a specific `Array` or `Group`. Requests for keys outside the +node receive a 404, even if those keys exist in the underlying store: + +```python +import zarr +from zarr_http_server import node_app + +store = zarr.storage.MemoryStore() +root = zarr.open_group(store) +root.create_array("a", shape=(10,), dtype="int32") +root.create_array("b", shape=(20,), dtype="float64") + +# Only serve the array at "a" — requests for "b" will return 404. +app = node_app(root["a"]) +``` + +## Running the server + +Build an app, then run it. Either app works with either runner. + +[`serve`][zarr_http_server.serve] blocks until the server is stopped, which is +the shape for a script or a container entrypoint: + +```python +from zarr_http_server import serve, store_app + +serve(store_app(store), host="127.0.0.1", port=8000) +``` + +[`serve_background`][zarr_http_server.serve_background] instead starts the +server in a daemon thread and returns a +[`BackgroundServer`][zarr_http_server.BackgroundServer] as soon as the socket +is listening, so the caller can carry on. These are two functions rather than +one with a flag, because they differ in the only thing that matters at a call +site: whether control comes back. + +### Choosing a port + +Both default to `port="auto"`, which prefers port 8000 but falls back to any +free port if it is taken, reporting the result through `server.url` and +Uvicorn's startup line. An **explicit** port means the opposite — bind exactly +that or fail — because a caller who names one usually has a proxy or a +container port mapping expecting the server there, and silently moving would +break it while looking healthy. `port=0` keeps its usual meaning of "any free +port, no preference". + +### Reading back with a zarr client + +`BackgroundServer` is a context manager, so the server stops when the block +exits. The example below also *reads back* over HTTP, which is a client-side +concern: `zarr.open_array(server.url)` goes through `FsspecStore`, which needs +an HTTP-capable fsspec that `zarr-http-server` does not pull in +(`pip install "fsspec[http]"`). + +```python +import numpy as np +import zarr +from zarr.storage import MemoryStore + +from zarr_http_server import node_app, serve_background + +store = MemoryStore() +arr = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="float64") +arr[:] = np.arange(100, dtype="float64") + +with serve_background(node_app(arr), host="127.0.0.1") as server: + remote = zarr.open_array(server.url, mode="r") + np.testing.assert_array_equal(remote[:], arr[:]) +# Server is shut down automatically when the block exits. +``` + +### Shutting down + +`BackgroundServer.shutdown()` — and leaving the `with` block — waits up to +`shutdown_timeout` seconds, 5 by default, for in-flight requests to finish +before forcing the server closed. It raises if the thread will not stop, so a +silent failure cannot leave you believing the port is free when it is not. + +```python +with serve_background(node_app(arr), shutdown_timeout=30) as server: + ... +``` + +## Serving several nodes + +Serving two arrays does not mean running two servers. Which approach fits +depends on where the arrays live. + +If they share a parent group, serve the parent — `node_app` recurses through +its members, so both are reachable under one port and node scoping still +applies to everything outside it: + +```python +server = serve_background(node_app(root)) +# -> /a/zarr.json, /a/c/0, /b/zarr.json, ... +``` + +If everything in the store is safe to expose, `store_app(store)` does the same +for the whole key space. + +Otherwise — arrays in *different* stores, or nodes that are not siblings — +`store_app` and `node_app` return plain Starlette apps, so mount them and run +the result: + +```python +from starlette.applications import Starlette +from starlette.routing import Mount + +from zarr_http_server import node_app, serve_background + +app = Starlette(routes=[ + Mount("/first", app=node_app(one)), + Mount("/second", app=node_app(other)), +]) +server = serve_background(app) +``` + +Each mount keeps its own validation, so a request under one cannot reach +another's data — `/first/../second/zarr.json` and its percent-encoded spellings +all return 404. + +Both runners take any ASGI app, so the split is clean: what an app *serves* +(`methods`, `cors_options`, `max_body_size`) is settled when the app is built, +while `serve` / `serve_background` only decide how it runs (`host`, `port`, +`shutdown_timeout`, `uvicorn_options`). + +## Serving from a notebook + +A notebook needs a server that outlives the cell that started it, so the `with` +form above is the wrong shape — it shuts the server down as soon as the block +ends. Start it, keep the handle, and stop it later: + +```python +# cell 1 — start +server = serve_background(node_app(array), host="127.0.0.1") +print(server.url) # e.g. http://127.0.0.1:54635 + +# cell 2..n — use it, across as many cells as you like +httpx.get(f"{server.url}/zarr.json") + +# last cell — stop +server.shutdown() +``` + +Two things make this comfortable in a kernel you re-run. `serve_background` +runs Uvicorn in a daemon thread with its own event loop, so it never touches +the kernel's loop and cannot block it. And its default `port="auto"` falls back +to a free port when 8000 is taken — re-running a start cell without stopping +the previous server is the classic notebook mistake, and a fixed port fails +there with *address already in use*. `server.url` reports the port actually +bound. + +If you forget to stop one, the thread is a daemon, so restarting the kernel +always clears it — and since each start takes a fresh port, a forgotten server +does not block the next one. + +[`examples/serve_notebook.ipynb`](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/examples/serve_notebook.ipynb) +is a runnable version of this. It is executed by the test suite, so it cannot +drift from the code. + +## Uvicorn configuration + +`serve` and `serve_background` name the options most callers need — `host`, +`port`, `shutdown_timeout` — and forward anything else to `uvicorn.Config` +through `uvicorn_options`, so nothing Uvicorn can do is out of reach: + +```python +server = serve_background( + store_app(store), + host="0.0.0.0", + port=8443, + uvicorn_options={ + "ssl_keyfile": "key.pem", + "ssl_certfile": "cert.pem", + "proxy_headers": True, + "forwarded_allow_ips": "10.0.0.0/8", + "log_level": "warning", + }, +) +``` + +Keys you pass are merged over the ones set for you, so they win. `server.url` +reflects the scheme actually in use (`https` when TLS is configured) and is +`None` when the server is not bound to a TCP host and port — a `uds` or `fd` +bind has no URL to report. + +## CORS + +Both app builders accept a [`CorsOptions`][zarr_http_server.CorsOptions] +parameter to enable +[CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) middleware for +browser-based clients: + +```python +from zarr_http_server import CorsOptions, store_app + +app = store_app( + store, + cors_options=CorsOptions( + allow_origins=["*"], + allow_methods=["GET"], + ), +) +``` + +`CorsOptions` carries every parameter Starlette's `CORSMiddleware` accepts — +`allow_headers`, `allow_credentials`, `allow_origin_regex`, +`allow_private_network`, `expose_headers` and `max_age` as well as the two +above — so configuring CORS never means reaching around this package. All keys +are optional. + +Two defaults differ from Starlette's, because the server knows things the +caller should not have to. It emits `Content-Range` on every ranged response, +which is *not* a CORS-safelisted response header, so `expose_headers` defaults +to `["Content-Range"]` — otherwise a browser client can read the bytes but not +learn which bytes it got. And it accepts a `Range` request header, so +`allow_headers` defaults to `["Range"]` — otherwise a preflight naming `Range` +is rejected. A key you supply replaces the default outright, so +`expose_headers=[]` means "expose nothing". + +`allow_methods` is checked against what the app actually serves: advertising a +method the route rejects raises `ValueError`, and `"*"` expands to what is +served rather than to every verb Starlette knows. + +## HTTP range requests + +The server supports the standard `Range` header for partial reads. The three +forms defined by [RFC 9110](https://httpwg.org/specs/rfc9110.html#field.range) +are supported: + +| Header | Meaning | +| ------------ | ------------------------ | +| `bytes=0-99` | First 100 bytes | +| `bytes=100-` | Everything from byte 100 | +| `bytes=-50` | Last 50 bytes | + +A successful range request returns HTTP 206 (Partial Content) with a +`Content-Range` header, including for suffix ranges — the server resolves +`bytes=-50` against the object's size so the response says which bytes it +carries. + +A range that is well-formed but names nothing readable — one lying wholly +beyond the end of the object, an inverted one such as `bytes=5-2`, or +`bytes=-0` — returns 416 (Range Not Satisfiable). A last-byte-position past the +end of the object is *not* in that category: per RFC 9110 §14.1.2 it is +clamped, so `bytes=0-999999` on a short object returns the whole thing. + +A `Range` header the server cannot use is **ignored** rather than refused, per +RFC 9110 §14.2: an unrecognized unit (`chars=0-7`), a multi-range request +(`bytes=0-7, 10-20`, which this server does not build multipart responses for), +or malformed syntax all return 200 with the full representation. + +## Read-only serving + +Read-only is the default. `store_app(store)` and `node_app(node)` accept `GET` +and `HEAD` and answer **405** to `PUT`, `POST`, `DELETE` and `PATCH` — no +argument is needed to get there. `HEAD` is served wherever `GET` is, as RFC +9110 §9.3.2 asks of every origin server, and is answered from the value's size +without transferring it. + +`POST` is not merely unrouted, it is unconfigurable: the accepted methods are +`GET`, `HEAD` and `PUT`, and asking for anything else raises `ValueError` when +the app is built. + +Two named sets let a call site state which it is, instead of leaving it to the +presence or absence of an argument: + +```python +from zarr_http_server import READ_ONLY_HTTP_METHODS, READ_WRITE_HTTP_METHODS, store_app + +app = store_app(store, methods=READ_ONLY_HTTP_METHODS) # GET, HEAD +app = store_app(store, methods=READ_WRITE_HTTP_METHODS) # GET, HEAD, PUT +``` + +The distinction also exists in the type domain. +[`ReadOnlyHTTPMethod`][zarr_http_server.ReadOnlyHTTPMethod] is a +`Literal["GET", "HEAD"]`, so a read-only set can be *declared* rather than +merely configured — a `frozenset[ReadOnlyHTTPMethod]` containing `"PUT"` is a +type error, not a runtime surprise: + +```python +from zarr_http_server import ReadOnlyHTTPMethod + +reads: frozenset[ReadOnlyHTTPMethod] = frozenset({"GET", "HEAD"}) # ok +reads = frozenset({"GET", "PUT"}) # type error +``` + +Both constants are derived from those Literals, so the runtime sets and the +static types cannot disagree about what the server serves. + +`READ_ONLY_HTTP_METHODS` is exactly the default, so passing it changes nothing +except that the intent is written down. The practical value is the other +direction: a writable app *must* name a method set, so `grep -r 'methods='` +finds every place that opts into writes. + +For a guarantee that does not depend on getting `methods` right, make the +*store* read-only. The store refuses writes itself, so no routing mistake — now +or in a later edit — can produce one: + +```python +app = store_app(store.with_read_only(True)) + +# For a node, open it read-only and node_app inherits that store: +app = node_app(zarr.open_array(store, mode="r")) +``` + +These two layers are independent, and the store is the stronger one: it holds +even if the HTTP layer is misconfigured. Asking for both at once — +`READ_WRITE_HTTP_METHODS` on a read-only store — is a contradiction that can +never succeed, so it raises `ValueError` at construction rather than turning +into a 403 for whichever client tries to write first. + +## Writes + +To enable writes, name a method set that includes `PUT`: + +```python +from zarr_http_server import READ_WRITE_HTTP_METHODS, store_app + +app = store_app(store, methods=READ_WRITE_HTTP_METHODS) +``` + +A `PUT` stores the request body at the given path and returns 204 (No Content). +Bodies are capped at +[`DEFAULT_MAX_BODY_SIZE`][zarr_http_server.DEFAULT_MAX_BODY_SIZE] (256 MiB) and +a larger one returns 413 (Content Too Large) — `Store.set` takes a whole +buffer, so an accepted body is held in memory in full. Raise or remove the cap +with `max_body_size`: + +```python +app = store_app(store, methods=READ_WRITE_HTTP_METHODS, max_body_size=None) +``` + +!!! danger "Writes through `store_app` are unvalidated" + + `store_app` exposes every key in the store, so `PUT` grants unrestricted + write access to all of it. It also does not *validate* keys, because it + proxies the raw key space and has no array semantics to check against: a + client that misspells a chunk key — `c/00/00` where zarr writes `c/0/0` — + gets a successful write to a key no reader will ever consult, so the data + is stored but invisible to anyone opening the array. + + `node_app` rejects such a key with 404, since it knows which node it is + serving and therefore which keys are real. If you are serving a zarr + hierarchy to clients you do not control and writes are enabled, prefer + `node_app`. + + Note also that a client that can write a node's metadata can change what + that node contains, and so what it will serve. + +## Examples + +Both live in +[`examples/`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server/examples) +and are executed by the test suite, so neither can drift from the code. + +`serve.py` creates an in-memory Zarr array, serves it, and fetches the +`zarr.json` metadata document and a raw chunk with `httpx`. It declares its own +dependencies inline, so uv installs them for you: + +```bash +uv run examples/serve.py +``` + +`serve_notebook.ipynb` is the notebook equivalent, showing how to start a +server in one cell and stop it in another. diff --git a/packages/zarr-http-server/docs/index.md b/packages/zarr-http-server/docs/index.md new file mode 100644 index 0000000000..271de6445e --- /dev/null +++ b/packages/zarr-http-server/docs/index.md @@ -0,0 +1,71 @@ +# zarr-http-server + +HTTP server for Zarr stores, arrays, and groups. + +`zarr-http-server` is developed in the +[zarr-python repository](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server) +and released independently of `zarr` itself. Install it with: + +``` +pip install zarr-http-server +``` + +!!! warning "Experimental" + + This package is experimental. Its API may change or be removed at any + point. + +## What this is + +`zarr-http-server` exposes a Zarr `Store`, `Array`, or `Group` over HTTP via an +ASGI app, so any HTTP-capable client — including zarr-python itself, via +`FsspecStore` or `ObjectStore` — can read the data. The app is built on +[Starlette](https://www.starlette.io/) and can be run with any ASGI server; +the `serve` / `serve_background` helpers run it with +[Uvicorn](https://uvicorn.dev/). + +Building an app and running it are separate steps, and either app works with +either runner: + +- **Build** with [`store_app`][zarr_http_server.store_app] to serve every key + in a store, or [`node_app`][zarr_http_server.node_app] to serve only the keys + belonging to one `Array` or `Group` — requests for keys outside that node + return 404 even when those keys exist in the underlying store. +- **Run** with [`serve`][zarr_http_server.serve], which blocks, or + [`serve_background`][zarr_http_server.serve_background], which returns a + handle you can shut down later. + +Byte-range reads, configurable CORS headers, and a configurable set of allowed +HTTP methods are handled by the app. + +## Quick start + +```python +import zarr +from zarr_http_server import node_app, serve_background + +store = zarr.storage.MemoryStore() +array = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="float64") + +with serve_background(node_app(array)) as server: + print(server.url) # e.g. http://127.0.0.1:8000 +``` + +Reads are all that is enabled by default: `GET` and `HEAD` are served, and +`PUT`, `POST`, `DELETE` and `PATCH` are answered with 405. + +!!! danger "Serving a whole store grants access to all of it" + + `store_app` applies no per-key filtering. Only point it at a store whose + full contents are safe to serve, and note that enabling `PUT` grants write + access to everything the store contains. See + [read-only serving](guide.md#read-only-serving) for the guarantees + available. + +## Next steps + +- [User guide](guide.md) — building apps, running them, byte ranges, CORS, + writes, notebooks, and Uvicorn configuration +- [API reference](api/index.md) +- [Changelog](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/CHANGELOG.md) +- [License (MIT)](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/LICENSE.txt) diff --git a/packages/zarr-http-server/examples/serve.py b/packages/zarr-http-server/examples/serve.py new file mode 100644 index 0000000000..45caa9ea67 --- /dev/null +++ b/packages/zarr-http-server/examples/serve.py @@ -0,0 +1,45 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr-http-server @ git+https://github.com/zarr-developers/zarr-python.git@main#subdirectory=packages/zarr-http-server", +# "httpx", +# ] +# /// +""" +Serve a Zarr array over HTTP and fetch its metadata and chunks. + +This example creates an in-memory array, serves it in a background thread, +then uses ``httpx`` to request the ``zarr.json`` metadata document and a raw +chunk. +""" + +import json + +import httpx +import numpy as np +import zarr +from zarr.storage import MemoryStore + +from zarr_http_server import node_app, serve_background + +# -- create an array -------------------------------------------------------- +store = MemoryStore() +data = np.arange(1000, dtype="uint8").reshape(10, 10, 10) +# no compression +arr = zarr.create_array(store, data=data, chunks=(5, 5, 5), write_data=True, compressors=None) + +# -- serve it in the background --------------------------------------------- +# port=0 asks the OS for a free port, so running this twice -- or running it +# while something else holds 8000 -- works. `server.url` reports what it bound. +with serve_background(node_app(arr), host="127.0.0.1") as server: + # -- fetch metadata ------------------------------------------------------ + resp = httpx.get(f"{server.url}/zarr.json") + assert resp.status_code == 200 + meta = resp.json() + print("zarr.json:") + print(json.dumps(meta, indent=2)) + + # -- fetch a raw chunk --------------------------------------------------- + resp = httpx.get(f"{server.url}/c/0/0/0") + assert resp.status_code == 200 + print(f"\nchunk c/0/0/0: {len(resp.content)} bytes") diff --git a/packages/zarr-http-server/examples/serve_notebook.ipynb b/packages/zarr-http-server/examples/serve_notebook.ipynb new file mode 100644 index 0000000000..e751a526c1 --- /dev/null +++ b/packages/zarr-http-server/examples/serve_notebook.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "6cb56289", + "metadata": {}, + "source": [ + "# Serving a Zarr array from a notebook\n", + "\n", + "A notebook needs a server that outlives the cell that started it, which is the\n", + "one thing the `with serve_background(...)` form in the README cannot give\n", + "that shuts the server down as soon as the block ends.\n", + "\n", + "The notebook pattern is instead:\n", + "\n", + "1. start with `serve_background` and keep the handle,\n", + "2. use the server across as many cells as you like,\n", + "3. `shutdown()` when you are done.\n", + "\n", + "Two details make this comfortable in a kernel you re-run:\n", + "\n", + "- **`serve_background`** runs uvicorn in a daemon thread with its own event\n", + " loop, so it never touches the kernel's loop and cannot block it.\n", + "- **`port=\"auto\"`**, its default, prefers port 8000 but takes a free one if\n", + " it is busy. Re-running a start cell without stopping the previous server is\n", + " the classic notebook mistake, and a fixed port fails there with *address\n", + " already in use*. `server.url` reports the port actually bound." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e2e217fa", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import zarr\n", + "from zarr.storage import MemoryStore\n", + "\n", + "from zarr_http_server import node_app, serve_background\n", + "\n", + "store = MemoryStore()\n", + "array = zarr.create_array(\n", + " store,\n", + " data=np.arange(1000, dtype=\"uint8\").reshape(10, 10, 10),\n", + " chunks=(5, 5, 5),\n", + " compressors=None,\n", + " write_data=True,\n", + ")\n", + "array.info" + ] + }, + { + "cell_type": "markdown", + "id": "35752272", + "metadata": {}, + "source": [ + "## Start\n", + "\n", + "`serve_background` returns a `BackgroundServer` as soon as the socket is\n", + "so the next cell can use it immediately." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b5010cdb", + "metadata": {}, + "outputs": [], + "source": [ + "server = serve_background(node_app(array), host=\"127.0.0.1\")\n", + "\n", + "print(f\"serving at {server.url}\")\n", + "assert server.url is not None" + ] + }, + { + "cell_type": "markdown", + "id": "d4e1f8d6", + "metadata": {}, + "source": [ + "## Use it\n", + "\n", + "The server is alive across cells now. Anything that speaks HTTP can read from\n", + "it -- here `httpx`, but a browser or another zarr client works the same way.\n", + "\n", + "(With `fsspec[http]` installed you can also do\n", + "`zarr.open_array(server.url, mode=\"r\")` to read the array back through zarr\n", + "itself.)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ac501fa", + "metadata": {}, + "outputs": [], + "source": [ + "import httpx\n", + "\n", + "metadata = httpx.get(f\"{server.url}/zarr.json\", timeout=30)\n", + "print(metadata.status_code, metadata.headers[\"content-type\"])\n", + "assert metadata.status_code == 200\n", + "assert metadata.json()[\"shape\"] == [10, 10, 10]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c7a94eff", + "metadata": {}, + "outputs": [], + "source": [ + "chunk = httpx.get(f\"{server.url}/c/0/0/0\", timeout=30)\n", + "print(f\"chunk c/0/0/0: {len(chunk.content)} bytes\")\n", + "assert chunk.status_code == 200\n", + "\n", + "# Byte ranges work too, and say which bytes came back.\n", + "part = httpx.get(f\"{server.url}/c/0/0/0\", headers={\"Range\": \"bytes=0-9\"}, timeout=30)\n", + "print(part.status_code, part.headers[\"content-range\"], part.content)\n", + "assert part.status_code == 206\n", + "assert part.content == chunk.content[:10]" + ] + }, + { + "cell_type": "markdown", + "id": "c8fd3ea2", + "metadata": {}, + "source": [ + "## Writes are off unless you ask\n", + "\n", + "The default is read-only, so a stray `PUT` from a notebook cell -- or from\n", + "anyone else who can reach the port -- is refused." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f6bee45", + "metadata": {}, + "outputs": [], + "source": [ + "refused = httpx.put(f\"{server.url}/c/0/0/0\", content=b\"nope\", timeout=30)\n", + "print(\"PUT ->\", refused.status_code)\n", + "assert refused.status_code == 405" + ] + }, + { + "cell_type": "markdown", + "id": "74f4bebc", + "metadata": {}, + "source": [ + "## Stop\n", + "\n", + "`shutdown()` waits for in-flight requests, then forces the server closed. It\n", + "raises if the thread will not stop, so a silent failure cannot leave you\n", + "believing the port is free when it is not." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "53a3e8d4", + "metadata": {}, + "outputs": [], + "source": [ + "server.shutdown()\n", + "\n", + "# The port really is closed now.\n", + "try:\n", + " httpx.get(f\"{server.url}/zarr.json\", timeout=5)\n", + "except httpx.HTTPError as exc:\n", + " print(f\"as expected, no longer serving: {type(exc).__name__}\")\n", + "else:\n", + " raise AssertionError(\"server still responding after shutdown\")" + ] + }, + { + "cell_type": "markdown", + "id": "8a7742e0", + "metadata": {}, + "source": [ + "## If you forget to stop one\n", + "\n", + "The server thread is a daemon, so it dies with the kernel -- restarting the\n", + "kernel always clears it. Because `port=0` picks a fresh port each time, a\n", + "forgotten server does not block the next one either; it just holds a port\n", + "until the kernel exits.\n", + "\n", + "If you want the shutdown tied to a block rather than a cell, the context\n", + "manager form still works inside a single cell:\n", + "\n", + "```python\n", + "with serve_background(node_app(array)) as server:\n", + " ... # everything must happen in this cell\n", + "```" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/packages/zarr-http-server/justfile b/packages/zarr-http-server/justfile new file mode 100644 index 0000000000..d65b1b53b7 --- /dev/null +++ b/packages/zarr-http-server/justfile @@ -0,0 +1,68 @@ +# Development verbs for the zarr-http-server package. Recipes run with this +# directory as the working directory regardless of where `just` is invoked. +# +# CI calls these recipes rather than repeating their commands, so a green run +# in .github/workflows/zarr-http-server.yml means the same thing as a green +# `just check` here. + +# Pinned to the ruff that .pre-commit-config.yaml uses, so this and the +# pre-commit gate enforce one standard. An unpinned `uvx ruff` floats to the +# newest release: when ruff 0.16 began selecting BLE001 under the root +# config's `B` prefix, this job failed on rules the pinned ruff never enforced, +# with no code change to blame. Bump alongside the pre-commit rev. +ruff_version := "0.16.0" + +# List available recipes +default: + @just --list + +# The `examples` group carries the deps the README examples need, so the test +# that reads a served array back with a zarr client runs here instead of +# silently skipping. +# Run the test suite; extra args are passed to pytest +test *args: + uv run --group test --group examples pytest tests {{ args }} + +# Lint the package sources and tests +lint: + uvx ruff@{{ ruff_version }} check . + +# This package type-checks with mypy (see [tool.mypy] in pyproject.toml) +# rather than the pyright used by the other packages under packages/. +# Type-check the package sources +typecheck: + uv run --group test --with mypy mypy src + +# Run everything CI runs for this package +check: lint typecheck test 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-http-server/mkdocs.yml b/packages/zarr-http-server/mkdocs.yml new file mode 100644 index 0000000000..7ebfe8c017 --- /dev/null +++ b/packages/zarr-http-server/mkdocs.yml @@ -0,0 +1,100 @@ +site_name: zarr-http-server +# 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-http-server +repo_url: https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server +# 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-http-server/docs/ +site_description: HTTP server for Zarr stores, arrays, and groups. +site_author: Davis Bennett +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr-http-server.readthedocs.io/'] +docs_dir: docs +use_directory_urls: true + +nav: + - index.md + - guide.md + - API Reference: + - api/index.md + - Changelog: https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/CHANGELOG.md + +watch: + - src + +theme: + language: en + name: material + logo: _static/logo_bw.png + favicon: _static/favicon-96x96.png + + palette: + # Light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + font: + text: Roboto + code: Roboto Mono + + features: + - content.code.annotate + - content.code.copy + - navigation.indexes + - navigation.instant + - navigation.tracking + - search.suggest + - search.share + +plugins: + - autorefs + - search + - mkdocstrings: + enable_inventory: true + handlers: + python: + paths: [src] + options: + allow_inspection: true + docstring_section_style: list + docstring_style: numpy + inherited_members: true + line_length: 60 + separate_signature: true + show_root_heading: true + show_signature_annotations: true + show_source: true + show_symbol_type_toc: true + signature_crossrefs: true + show_if_no_docstring: true + extensions: + - griffe_inherited_docstrings + + inventories: + - https://docs.python.org/3/objects.inv + - https://zarr.readthedocs.io/en/stable/objects.inv + +markdown_extensions: + - admonition + - attr_list + - def_list + - footnotes + - md_in_html + - pymdownx.details + - pymdownx.superfences + - toc: + permalink: true + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite diff --git a/packages/zarr-http-server/pyproject.toml b/packages/zarr-http-server/pyproject.toml new file mode 100644 index 0000000000..10db7ae496 --- /dev/null +++ b/packages/zarr-http-server/pyproject.toml @@ -0,0 +1,163 @@ +[build-system] +requires = ["hatchling>=1.29.0", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "zarr-http-server" +dynamic = ["version"] +description = "HTTP server for Zarr stores, arrays, and groups." +readme = "README.md" +requires-python = ">=3.12" +license = "MIT" +license-files = ["LICENSE.txt"] +authors = [ + { name = "Davis Bennett", email = "davis.v.bennett@gmail.com" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "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.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering", + "Topic :: Internet :: WWW/HTTP :: HTTP Servers", + "Typing :: Typed", +] +keywords = ["zarr", "http", "server", "asgi"] +dependencies = [ + "zarr>=3.1", + "starlette>=1.0", + "uvicorn>=0.29", +] + +[project.urls] +Homepage = "https://github.com/zarr-developers/zarr-python" +Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server" +Issues = "https://github.com/zarr-developers/zarr-python/issues" +Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/CHANGELOG.md" +Documentation = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/README.md" + +[dependency-groups] +test = [ + "pytest", + "httpx", + "httpx2", + "hypothesis", + # Executing examples/serve_notebook.ipynb in the suite: nbformat reads it, + # nbclient runs it, ipykernel is the kernel it runs in. + "nbformat", + "nbclient", + "ipykernel", +] +examples = [ + # Optional dependencies to run the README examples. Reading a served + # array back with `zarr.open_array(url)` goes through FsspecStore, which + # needs an HTTP-capable fsspec; `examples/serve.py` uses httpx. + "fsspec[http]", + "httpx", +] +docs = [ + # Pins match the zarr-python docs environment in the repo-root + # pyproject.toml so the two sites render with the same toolchain. + "mkdocs-material==9.7.7", + "mkdocs==1.6.1", + "mkdocstrings==1.0.6", + "mkdocstrings-python==2.0.5", + "griffe-inherited-docstrings==1.1.3", + # mkdocstrings uses ruff to format rendered signatures + "ruff==0.16.0", +] + +# Dev-only: resolve zarr from the repo root so package tests run against +# in-repo zarr. Affects uv resolution only, not published metadata. +[tool.uv.sources] +zarr = { path = "../..", editable = true } + +[tool.hatch.version] +source = "vcs" +tag-pattern = '^zarr_http_server-v(?P.+)$' +# `git_describe_command` ensures we get the zarr_http_server tags instead of latest. +# `local_scheme` strips the git commit info so the appending info is just a counter from latest tag. +# test-pypi doesn't accept git commit info in tags, and the count should be enough to distinguish unique runs. +raw-options = { root = "../..", git_describe_command = "git describe --dirty --tags --long --match zarr_http_server-v*", local_scheme = "no-local-version" } + +[tool.hatch.build.targets.wheel] +packages = ["src/zarr_http_server"] + +# An allowlist, so nothing that merely happens to sit in the package directory +# — a scratch script, a stray notebook — can ride along in a release. With no +# sdist section at all hatchling defaults to "everything not gitignored", which +# is a blocklist by another name. The list keeps an sdist self-testing: +# `tests/test_examples.py` runs `examples/serve.py` and executes every cell of +# `examples/serve_notebook.ipynb`, so those are part of the suite rather than +# decoration, and `/docs` plus `/mkdocs.yml` are a self-contained site. +# `changes/` and `.readthedocs.yaml` are deliberately absent: towncrier +# fragments are consumed into `CHANGELOG.md` at release time, and the RTD +# config only means anything in the repository. `pyproject.toml`, `README.md` +# and `LICENSE.txt` are added by hatchling itself. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/docs", + "/examples", + "/mkdocs.yml", + "/justfile", + "/CHANGELOG.md", +] + +[tool.ruff] +extend = "../../pyproject.toml" +target-version = "py312" + +[tool.pytest.ini_options] +minversion = "7" +testpaths = ["tests"] +xfail_strict = true +addopts = ["-ra", "--strict-config", "--strict-markers"] +filterwarnings = [ + "error", +] + +[tool.mypy] +files = ["src"] +python_version = "3.12" +ignore_missing_imports = true +namespace_packages = false +pretty = true +show_error_code_links = true +show_error_context = true +strict = true +warn_unreachable = true +enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool", "truthy-iterable"] + +[tool.numpydoc_validation] +# Mirrors the root zarr-python config so moved docstrings (written for that +# config) don't trip stricter defaults just because this package has its own +# pyproject.toml. See https://numpydoc.readthedocs.io/en/latest/validation.html#built-in-validation-checks +checks = [ + "GL10", + "SS04", + "PR02", + "PR03", + "PR05", + "PR06", +] + +[tool.towncrier] +# Fragments for this package live alongside the package source, separate +# from the parent zarr-python `changes/` directory, so a PR touching only +# `packages/zarr-http-server/` produces a release note for this package only. +directory = "changes" +filename = "CHANGELOG.md" +package = "zarr_http_server" +underlines = ["", "", ""] +title_format = "## {version} ({project_date})" +issue_format = "[#{issue}](https://github.com/zarr-developers/zarr-python/issues/{issue})" +start_string = "\n" diff --git a/packages/zarr-http-server/src/zarr_http_server/__init__.py b/packages/zarr-http-server/src/zarr_http_server/__init__.py new file mode 100644 index 0000000000..4f4fbd22f8 --- /dev/null +++ b/packages/zarr-http-server/src/zarr_http_server/__init__.py @@ -0,0 +1,38 @@ +"""Zarr-http-server: HTTP server for Zarr stores, arrays, and groups.""" + +from importlib.metadata import version + +from zarr_http_server._serve import ( + AUTO_PORT, + DEFAULT_MAX_BODY_SIZE, + DEFAULT_PORT, + READ_ONLY_HTTP_METHODS, + READ_WRITE_HTTP_METHODS, + BackgroundServer, + CorsOptions, + HTTPMethod, + ReadOnlyHTTPMethod, + node_app, + serve, + serve_background, + store_app, +) + +__version__ = version("zarr-http-server") + +__all__ = [ + "AUTO_PORT", + "DEFAULT_MAX_BODY_SIZE", + "DEFAULT_PORT", + "READ_ONLY_HTTP_METHODS", + "READ_WRITE_HTTP_METHODS", + "BackgroundServer", + "CorsOptions", + "HTTPMethod", + "ReadOnlyHTTPMethod", + "__version__", + "node_app", + "serve", + "serve_background", + "store_app", +] diff --git a/packages/zarr-http-server/src/zarr_http_server/_keys.py b/packages/zarr-http-server/src/zarr_http_server/_keys.py new file mode 100644 index 0000000000..e468cd066d --- /dev/null +++ b/packages/zarr-http-server/src/zarr_http_server/_keys.py @@ -0,0 +1,218 @@ +"""Utilities for determining the set of valid store keys for zarr nodes. + +A zarr node (array or group) implicitly defines a subset of keys in the +underlying store. For an **array** the valid keys are: + +* metadata documents (``zarr.json`` for v3, ``.zarray`` / ``.zattrs`` for v2) +* chunk (or shard) keys whose decoded coordinates fall within the storage grid + +For a **group** the valid keys are: + +* its own metadata documents +* any path ``/`` where ```` is a direct member and + ```` is recursively valid for that child +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +ZARR_JSON = "zarr.json" +ZARRAY_JSON = ".zarray" +ZGROUP_JSON = ".zgroup" +ZATTRS_JSON = ".zattrs" +ZMETADATA_V2_JSON = ".zmetadata" + +if TYPE_CHECKING: + from zarr import Array, Group + +_ARRAY_METADATA_KEYS_V3 = frozenset({ZARR_JSON}) +_ARRAY_METADATA_KEYS_V2 = frozenset({ZARRAY_JSON, ZATTRS_JSON}) +_GROUP_METADATA_KEYS_V3 = frozenset({ZARR_JSON}) +_GROUP_METADATA_KEYS_V2 = frozenset({ZGROUP_JSON, ZATTRS_JSON, ZMETADATA_V2_JSON}) + + +def array_metadata_keys(zarr_format: int) -> frozenset[str]: + """Return the metadata key basenames an array owns, for a zarr format. + + Parameters + ---------- + zarr_format : int + The zarr format version (2 or 3). + + Returns + ------- + frozenset of str + """ + if zarr_format == 3: + return _ARRAY_METADATA_KEYS_V3 + return _ARRAY_METADATA_KEYS_V2 + + +def group_metadata_keys(zarr_format: int) -> frozenset[str]: + """Return the metadata key basenames a group owns, for a zarr format. + + Parameters + ---------- + zarr_format : int + The zarr format version (2 or 3). + + Returns + ------- + frozenset of str + """ + if zarr_format == 3: + return _GROUP_METADATA_KEYS_V3 + return _GROUP_METADATA_KEYS_V2 + + +def decode_chunk_key(array: Array[Any], key: str) -> tuple[int, ...] | None: + """Try to decode *key* into chunk coordinates for *array*. + + Parameters + ---------- + array : Array + The array whose chunk key encoding should be used. + key : str + The candidate chunk key string. + + Returns + ------- + tuple of int, or None + The decoded coordinates, or ``None`` if *key* is not a valid chunk key. + """ + try: + if array.metadata.zarr_format == 2: + coords = tuple(int(p) for p in key.split(array.metadata.dimension_separator)) + # A 0-d v2 array holds its single chunk under "0", which decodes + # to a 1-tuple that no 0-d grid could match. + if len(array.shape) == 0: + return () if coords == (0,) else None + return coords + + # Ask zarr rather than predicting it: the encoding owns its own + # grammar, so a new or third-party chunk key encoding decodes here + # without this package knowing anything about it. + return array.metadata.chunk_key_encoding.decode_chunk_key(key) + except (ValueError, TypeError, NotImplementedError): + return None + + +def _shard_grid_shape(array: Array[Any]) -> tuple[int, ...]: + """Shape of the shard grid, falling back to the chunk grid when unsharded.""" + shard_shape = array.shards if array.shards is not None else array.chunks + return tuple(-(-s // c) for s, c in zip(array.shape, shard_shape, strict=True)) + + +def is_valid_chunk_key(array: Array[Any], key: str) -> bool: + """Check whether *key* is a valid chunk key for *array*. + + Decodes the key, checks that the resulting coordinates fall within the + storage grid (shard grid if sharding is used, chunk grid otherwise), and + requires the key to be spelled exactly as zarr itself would spell it. + + That last check is what makes the accepted key set equal to the set of + keys zarr can actually read. Decoding alone is lenient -- `int` accepts + leading zeros, a leading `+`/`-`, surrounding whitespace, underscore + separators, and non-ASCII decimal digits -- so `c/00/00` and `c/0/0` + decode to the same coordinates while naming *different* store keys. A + write to the non-canonical spelling would be stored under a key no reader + ever looks up: the client sees success and the data is invisible. + + Parameters + ---------- + array : Array + The array to validate against. + key : str + The candidate chunk key string. + + Returns + ------- + bool + """ + coords = decode_chunk_key(array, key) + if coords is None: + return False + grid = _shard_grid_shape(array) + if len(coords) != len(grid): + return False + if not all(0 <= c < g for c, g in zip(coords, grid, strict=True)): + return False + return array.metadata.encode_chunk_key(coords) == key + + +def is_valid_array_key(array: Array[Any], key: str) -> bool: + """Check whether *key* is a valid store key for *array*. + + Valid keys are metadata documents and chunk keys. + + Parameters + ---------- + array : Array + The array to validate against. + key : str + The candidate key, relative to the array's root. + + Returns + ------- + bool + """ + if key in array_metadata_keys(array.metadata.zarr_format): + return True + return is_valid_chunk_key(array, key) + + +def is_valid_node_key(node: Array[Any] | Group, key: str) -> bool: + """Check whether *key* is a valid store key relative to *node*. + + For an ``Array``, valid keys are metadata documents and chunk keys. + + For a ``Group``, valid keys are the group's own metadata documents, or + a path of the form ``/`` where ```` is a direct + member and ```` is recursively valid for that child. + + Parameters + ---------- + node : Array or Group + The zarr node to validate against. + key : str + The candidate key, relative to the node's root. + + Returns + ------- + bool + """ + from zarr import Array + + if isinstance(node, Array): + return is_valid_array_key(node, key) + + # Group + if key in group_metadata_keys(node.metadata.zarr_format): + return True + + # Try to match the first path component against a child member. + if "/" in key: + child_name, remainder = key.split("/", 1) + else: + # A bare name with no slash can't be a valid group-level key — + # groups contain children (which have subkeys), not bare keys. + return False + + try: + child = node[child_name] + except KeyError: + # There is no such member, so no key beneath it can be valid. + # + # Only a missing name is caught here. Anything else -- an I/O error + # reading the child's metadata, unparsable JSON, a codec from a + # plugin this process lacks -- means the key could not be *judged*, + # which is not the same as judging it absent. Reporting those as 404 + # would be a lie with teeth: under the v3 spec an absent chunk is an + # uninitialized one, so a correct reader answers a 404 by silently + # substituting the array's fill value over data that exists. Letting + # them propagate surfaces a 500, which is the honest answer and the + # one a client cannot mistake for data. + return False + + return is_valid_node_key(child, remainder) diff --git a/packages/zarr-http-server/src/zarr_http_server/_serve.py b/packages/zarr-http-server/src/zarr_http_server/_serve.py new file mode 100644 index 0000000000..dce1df6b12 --- /dev/null +++ b/packages/zarr-http-server/src/zarr_http_server/_serve.py @@ -0,0 +1,1170 @@ +from __future__ import annotations + +import asyncio +import errno +import logging +import ntpath +import socket +import sys +import threading +import time +from enum import Enum, auto +from functools import partial +from typing import TYPE_CHECKING, Any, Literal, Self, TypedDict, cast, get_args + +from zarr.abc.store import OffsetByteRequest, RangeByteRequest, SuffixByteRequest +from zarr.buffer import cpu + +from zarr_http_server._keys import array_metadata_keys, group_metadata_keys, is_valid_node_key + +if TYPE_CHECKING: + from collections.abc import Mapping + from collections.abc import Set as AbstractSet + + import uvicorn + from starlette.applications import Starlette + from starlette.requests import Request + from starlette.responses import Response + from zarr import Array, Group + from zarr.abc.store import ByteRequest, Store + +__all__ = [ + "AUTO_PORT", + "DEFAULT_MAX_BODY_SIZE", + "DEFAULT_PORT", + "READ_ONLY_HTTP_METHODS", + "READ_WRITE_HTTP_METHODS", + "BackgroundServer", + "CorsOptions", + "HTTPMethod", + "ReadOnlyHTTPMethod", + "node_app", + "serve", + "serve_background", + "store_app", +] + + +class CorsOptions(TypedDict, total=False): + """Options forwarded to Starlette's `CORSMiddleware`. + + Every parameter the middleware accepts appears here, so configuring CORS + never requires reaching around this package. Keys left out fall back to + the defaults described below; a key that is present is used verbatim, + including an empty list. + + Two defaults differ from Starlette's own, because this server knows + something its caller should not have to. It emits `Content-Range` on + every ranged response, which is *not* a CORS-safelisted response header -- + with Starlette's empty `expose_headers` a browser client can read the + bytes but not learn which bytes it got. And it accepts a `Range` request + header, which Starlette's empty `allow_headers` would reject at preflight. + + * `expose_headers` defaults to `["Content-Range"]` + * `allow_headers` defaults to `["Range"]` + + Everything else defaults to the middleware's own value: no origins, `GET` + only, no credentials, no origin regex, no private-network access, and a + 600-second preflight cache. + """ + + allow_origins: list[str] + allow_methods: list[str] + allow_headers: list[str] + allow_credentials: bool + allow_origin_regex: str | None + allow_private_network: bool + expose_headers: list[str] + max_age: int + + +_CORS_DEFAULTS: CorsOptions = { + "expose_headers": ["Content-Range"], + "allow_headers": ["Range"], +} + + +ReadOnlyHTTPMethod = Literal["GET", "HEAD"] +"""An HTTP method that cannot modify the store. + +Distinguished from `HTTPMethod` in the type domain, not only at runtime, so a +read-only interface can be *declared* rather than merely configured: a +parameter annotated `AbstractSet[ReadOnlyHTTPMethod]` cannot be handed `"PUT"` +without a type error, whatever the value turns out to be at runtime. + +`HEAD` belongs here because Starlette routes it wherever `GET` goes, which is +what RFC 9110 §9.3.2 asks of an origin server. It is answered from the value's +size rather than by building and discarding a body. +""" + +_WriteHTTPMethod = Literal["PUT"] +"""An HTTP method that modifies the store. + +Private because nothing needs to name "the write methods" on its own -- it +exists so `HTTPMethod` can be defined as the union rather than as a third +hand-written list of the same strings. +""" + +HTTPMethod = ReadOnlyHTTPMethod | _WriteHTTPMethod +"""An HTTP method this server implements. + +`GET` and `HEAD` read a key; `PUT` writes one. Other verbs are not accepted: +the handler has no behavior for them, so serving them would silently answer +as if they were `GET`. +""" + +# Derived from the types above rather than restated, so the runtime sets and +# the static types cannot disagree about what this server serves. Adding a +# method to a Literal is then the only edit needed. +READ_ONLY_HTTP_METHODS: frozenset[ReadOnlyHTTPMethod] = frozenset(get_args(ReadOnlyHTTPMethod)) +"""Methods that only read. The default for every app in this package. + +Naming the set makes a read-only deployment say so at the call site, rather +than being the absence of an argument: + + store_app(store, methods=READ_ONLY_HTTP_METHODS) + +Typed as a set of `ReadOnlyHTTPMethod`, so a caller building on it keeps the +static guarantee: adding `"PUT"` to a `frozenset[ReadOnlyHTTPMethod]` is a +type error, not a runtime surprise. + +The stronger guarantee is a read-only store, which holds however `methods` is +configured -- see `store.with_read_only(True)`. +""" + +READ_WRITE_HTTP_METHODS: frozenset[HTTPMethod] = frozenset( + get_args(ReadOnlyHTTPMethod) + get_args(_WriteHTTPMethod) +) +"""Methods that read and write. Serving these grants clients write access. + +Every writable app must name a method set, so this constant is also what makes +writable deployments findable: grepping for `READ_WRITE_HTTP_METHODS` (or for +`methods=` generally) turns up every place that opts in. +""" + +_SUPPORTED_METHODS: frozenset[str] = READ_WRITE_HTTP_METHODS + +_LOGGER = logging.getLogger("uvicorn.error") +"""uvicorn's own logger, so a port fallback appears alongside its startup lines.""" + +DEFAULT_PORT = 8000 +"""Port tried first when `port="auto"`.""" + +AUTO_PORT: Literal["auto"] = "auto" +"""Sentinel for `port`: prefer `DEFAULT_PORT`, but settle for any free port. + +An explicit port is a requirement -- it binds that port or fails -- because a +caller who names one usually has something else expecting the server there. +`"auto"` says the opposite: no particular port is needed, so a collision +should not stop the server from starting. `port=0` keeps its usual meaning of +"any free port", with no preference. +""" + +_STARTUP_TIMEOUT = 5.0 +"""Seconds to wait for a background server to report that it is listening.""" + +_STARTUP_ABANDON_TIMEOUT = 5.0 +"""Seconds to wait for a server that failed to start to stop again.""" + +_SHUTDOWN_JOIN_MARGIN = 1.0 +"""Seconds to wait beyond uvicorn's graceful bound before forcing shutdown. + +uvicorn spends a fixed ~0.2s tearing down (a 0.1s loop tick plus a 0.1s +sleep) before its own `timeout_graceful_shutdown` wait begins, so a join that +merely equals that bound is guaranteed to expire first and escalate to +`force_exit` -- which makes uvicorn skip ASGI lifespan shutdown. +""" + +DEFAULT_MAX_BODY_SIZE = 256 * 1024 * 1024 +"""Default cap on a `PUT` body, in bytes. + +`Store.set` takes a whole `Buffer`, so an accepted body is held in memory in +full; the body is read incrementally and abandoned once it passes this cap, +so one request cannot size the server's memory use. Pass +`max_body_size=None` to lift the cap and read the body whole. +""" + + +class BackgroundServer: + """A running background HTTP server that can be used as a context manager. + + Wraps a ``uvicorn.Server`` running in a daemon thread. When used as a + context manager the server is shut down automatically on exit. + + Parameters + ---------- + server : uvicorn.Server + The running uvicorn server instance. + thread : threading.Thread + The daemon thread running the server. + host : str or None + The host the server was asked to bind, or ``None`` when it is not + listening on a TCP socket. + port : int or None + The port actually bound, or ``None`` when the server is not listening + on a TCP socket. + scheme : str, optional + URL scheme the server is reachable over. Defaults to ``"http"``. + shutdown_timeout : int, optional + Seconds to wait for in-flight requests to finish gracefully during + :meth:`shutdown` before forcing the server closed. Defaults to ``5``. + + Examples + -------- + >>> with serve_background(node_app(arr)) as server: # doctest: +SKIP + ... print(f"Listening on {server.host}:{server.port}") + ... # server is shut down when the block exits + """ + + def __init__( + self, + server: uvicorn.Server, + thread: threading.Thread, + *, + host: str | None, + port: int | None, + scheme: str = "http", + shutdown_timeout: int = 5, + ) -> None: + self._server = server + self._thread = thread + self.host = host + self.port = port + self.scheme = scheme + self._shutdown_timeout = shutdown_timeout + + @property + def url(self) -> str | None: + """The base URL of the running server. + + ``None`` when the server is not listening on a TCP socket -- a unix + socket or an inherited file descriptor has no host and port, and + inventing one would be a URL that connects to nothing. + """ + if self.host is None or self.port is None: + return None + return f"{self.scheme}://{self.host}:{self.port}" + + def shutdown(self) -> None: + """Signal the server to shut down and wait for it to stop. + + Waits for the server thread to exit on its own, then escalates to + ``force_exit`` if it has not, so a request wedged outside uvicorn's + loop cannot block here forever. + + Raises + ------ + RuntimeError + If the thread is still running after both waits. Returning + normally would report success for a server that is still bound to + its port and still serving, which the caller cannot detect any + other way. + """ + self._server.should_exit = True + # Outlast uvicorn's own graceful wait rather than matching it. uvicorn + # spends roughly 0.2s on teardown (a 0.1s loop tick plus a 0.1s sleep) + # *before* its `timeout_graceful_shutdown` wait even begins, so an + # equal bound here always expires first -- escalating to force_exit on + # the path that is supposed to be the orderly one, which makes uvicorn + # skip ASGI lifespan shutdown entirely. + self._thread.join(timeout=self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN) + if self._thread.is_alive(): + self._server.force_exit = True + self._thread.join(timeout=self._shutdown_timeout) + + if self._thread.is_alive(): + raise RuntimeError( + "Server thread did not stop within " + f"{self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN + self._shutdown_timeout:.1f}s, " + "even after force_exit. The server may still be serving and " + "holding its port; a request blocked in a store call cannot be " + "cancelled from here." + ) + + @property + def _graceful_timeout(self) -> float: + """uvicorn's own graceful-shutdown bound, whoever configured it.""" + configured = self._server.config.timeout_graceful_shutdown + return float(configured) if configured is not None else float(self._shutdown_timeout) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: object) -> None: + self.shutdown() + + +class _RangeVerdict(Enum): + """The outcome of a Range header that does not name a readable range.""" + + IGNORE = auto() + """Serve the full representation with 200, as if no Range had been sent.""" + + UNSATISFIABLE = auto() + """Answer 416: the range is well-formed but names nothing readable.""" + + +_MAX_BYTE_POS = sys.maxsize +"""Largest byte position this server will pass to a store. + +Range bounds arrive as arbitrary-precision Python integers, but a store +ultimately turns them into an index-sized `seek`/`read`. Feeding an oversized +value through raises `OverflowError`/`ValueError` from deep inside the store +rather than producing a response, so bounds are clamped or rejected here. +""" + + +def _parse_int(text: str) -> int | None: + """Parse a byte position, accepting only the canonical spelling of one. + + `int` is lenient in ways an HTTP byte position is not -- it accepts + surrounding whitespace, a leading `+`/`-`, underscore separators, and + non-ASCII decimal digits -- so `bytes=+0-1` and `bytes=0_0-1` would parse. + RFC 9110 defines a byte position as 1*DIGIT. + """ + if not text.isascii() or not text.isdigit(): + return None + return int(text) + + +def _parse_range_header(range_header: str) -> ByteRequest | _RangeVerdict: + """Parse an HTTP Range header into a ByteRequest. + + A header this server cannot turn into a single read is *ignored* rather + than rejected. RFC 9110 §14.2 requires a server to ignore a Range whose + unit it does not recognize, and permits ignoring one it cannot parse; in + both cases the correct answer is the full representation, not 416. + Answering 416 would tell a client the object is unreadable when it is + merely the request that was unsupported -- and a client coalescing two + chunk reads into one multi-range request would take that at face value. + + 416 is reserved for a well-formed range that genuinely names nothing. + + Parameters + ---------- + range_header : str + The value of the Range header, e.g. ``"bytes=0-99"`` or ``"bytes=-100"``. + + Returns + ------- + ByteRequest or _RangeVerdict + A ``RangeByteRequest``, ``OffsetByteRequest``, or ``SuffixByteRequest`` + for a readable range, otherwise the verdict to apply. + """ + if not range_header.startswith("bytes="): + # An unrecognized range unit; RFC 9110 §14.2 says MUST ignore. + return _RangeVerdict.IGNORE + range_spec = range_header[len("bytes=") :] + if "," in range_spec: + # A multipart range. Legal to send, and legal to answer with the whole + # representation; this server does not build multipart/byteranges. + return _RangeVerdict.IGNORE + + if range_spec.startswith("-"): + # suffix request: bytes=-N + suffix = _parse_int(range_spec[1:]) + if suffix is None: + return _RangeVerdict.IGNORE + if suffix == 0: + # "the last zero bytes" names nothing. + return _RangeVerdict.UNSATISFIABLE + return SuffixByteRequest(suffix=min(suffix, _MAX_BYTE_POS)) + + parts = range_spec.split("-", 1) + if len(parts) != 2: + return _RangeVerdict.IGNORE + start_str, end_str = parts + start = _parse_int(start_str) + if start is None: + return _RangeVerdict.IGNORE + if start > _MAX_BYTE_POS: + # No object can be this long, so the range starts past every end. + return _RangeVerdict.UNSATISFIABLE + if end_str == "": + # offset request: bytes=N- + return OffsetByteRequest(offset=start) + end_pos = _parse_int(end_str) + if end_pos is None: + return _RangeVerdict.IGNORE + # HTTP end is inclusive, ByteRequest end is exclusive. A last-byte-pos at + # or past the end of the object is satisfiable -- RFC 9110 §14.1.2 says to + # clamp it -- so an oversized bound is capped rather than refused. + end = min(end_pos, _MAX_BYTE_POS - 1) + 1 + if start >= end: + # An inverted range like "bytes=5-2" is unsatisfiable, not a read + # of negative length. + return _RangeVerdict.UNSATISFIABLE + return RangeByteRequest(start=start, end=end) + + +def _is_drive_qualified(path: str) -> bool: + """Whether *path* carries a drive or UNC prefix that would discard a store root. + + A drive-qualified key such as `C:/Windows`, or the drive-relative `a:b`, + replaces the root it is joined to rather than extending it. This is + rejected on every platform, not just Windows: the check is a string-level + gate in front of an arbitrary `Store`, and this package cannot know how a + given implementation resolves keys. + + The cost is that a node whose *first* path segment looks like `:...` + is unreachable -- `ntpath` treats any single character before a colon as + a drive, so there is no safe subset to admit. Such names are legal but + rare, and later segments are unaffected (`sub/a:b` is served normally). + + Parameters + ---------- + path : str + The candidate key, with separators already folded to `/`. + + Returns + ------- + bool + """ + return ntpath.splitdrive(path)[0] != "" + + +def _names_nothing(exc: OSError) -> bool: + """Whether an `OSError` answers about the *name*, rather than reporting failure. + + `ENAMETOOLONG` is the store saying no such name is expressible here. That + is an answer about the key -- nothing can be stored under it, so a miss is + honest -- and it is unreachable for real data, because `encode_chunk_key` + never produces a segment near a filesystem's length limit. Answering 404 + therefore cannot make a reader substitute fill values over a chunk that + exists, and it keeps a client from turning a freely chosen key into a 5xx. + + Every other `errno` describes a failure to complete the operation and must + surface as one. `EINVAL` was accepted here and was the dangerous case: it + is POSIX's catch-all, reachable on a perfectly ordinary short key through + a bad seek or an unsupported filesystem feature. Under the v3 spec an + absent chunk is an uninitialized one, so reporting such a failure as 404 + has a correct reader write fill values over data that is merely + unreadable. When in doubt the store's own signal is the one to trust: + `None` means absent, a raised error means the request could not be + answered. + + Parameters + ---------- + exc : OSError + The error raised by the store. + + Returns + ------- + bool + """ + return exc.errno == errno.ENAMETOOLONG + + +def _content_range(byte_range: RangeByteRequest | OffsetByteRequest, length: int) -> str: + """Build a `Content-Range` value for a 206 response. + + Parameters + ---------- + byte_range : RangeByteRequest or OffsetByteRequest + The range that was served. A suffix request is resolved to an absolute + range before reaching here, because RFC 9110 §15.3.7 requires every + single-part 206 to carry a `Content-Range` and a suffix's first-byte + position is not knowable without the object's size. + length : int + The number of bytes actually returned. + + Returns + ------- + str + A `bytes -/*` value. + """ + start = byte_range.start if isinstance(byte_range, RangeByteRequest) else byte_range.offset + # The total length is unknown here; RFC 9110 permits "*" in its place. + return f"bytes {start}-{start + length - 1}/*" + + +async def _resolve_suffix( + store: Store, path: str, byte_range: SuffixByteRequest +) -> RangeByteRequest | _RangeVerdict: + """Turn a suffix request into an absolute range using the object's size. + + A suffix range names its bytes relative to an end this server does not + otherwise need to know. Resolving it here is what lets the 206 carry a + `Content-Range`, which RFC 9110 requires and which a caller reading a + shard index needs in order to locate what it was given. + """ + try: + size = await store.getsize(path) + except FileNotFoundError: + return _RangeVerdict.UNSATISFIABLE + if size == 0: + return _RangeVerdict.UNSATISFIABLE + # A suffix longer than the object is satisfiable and yields the whole + # object, per RFC 9110 §14.1.2. + return RangeByteRequest(start=max(0, size - byte_range.suffix), end=size) + + +_JSON_BASENAMES = ( + array_metadata_keys(2) + | array_metadata_keys(3) + | group_metadata_keys(2) + | group_metadata_keys(3) +) +"""Metadata documents that are JSON, for every zarr format. + +Derived from the same tables that decide which keys a node owns, so a v2 +array's `.zarray` is typed as JSON rather than as opaque bytes -- and adding a +document in one place cannot leave the media type behind in the other. +""" + + +def content_type_for(path: str) -> str: + """Media type for a store key, chosen by its basename.""" + if path.rsplit("/", 1)[-1] in _JSON_BASENAMES: + return "application/json" + return "application/octet-stream" + + +async def _head_response(store: Store, path: str, content_type: str) -> Response: + """Answer a HEAD without transferring the value. + + A HEAD body is discarded at the wire, so routing HEAD through the GET + handler reads the whole object -- megabytes of chunk or shard -- to report + a length. `Store.getsize` is a `stat` on a filesystem store and an + info/HEAD call on a remote one. + """ + from starlette.responses import Response + + try: + size = await store.getsize(path) + except FileNotFoundError: + return Response(status_code=404) + except OSError as exc: + if not _names_nothing(exc): + raise + return Response(status_code=404) + return Response(status_code=200, media_type=content_type, headers={"Content-Length": str(size)}) + + +async def _get_response( + store: Store, + path: str, + byte_range: RangeByteRequest | OffsetByteRequest | None = None, +) -> Response: + """Fetch a key from the store and return an HTTP response.""" + from starlette.responses import Response + + proto = cpu.buffer_prototype + content_type = content_type_for(path) + + try: + buf = await store.get(path, proto, byte_range=byte_range) + except (MemoryError, OverflowError): + # The client's last-byte-pos is wider than the store can materialize + # -- it sizes its read from the range, not from the object. RFC 9110 + # §14.1.2 makes a last-byte-pos at or past the end of the object + # satisfiable and clamps it to the end, so re-read from the same start + # to EOF, which is what the clamped range denotes. Refusing with 416 + # would deny a request that is merely over-wide, and a client asking + # for "from here to well past the end" is asking a normal question. + if not isinstance(byte_range, RangeByteRequest): + raise + byte_range = OffsetByteRequest(offset=byte_range.start) + buf = await store.get(path, proto, byte_range=byte_range) + except OSError as exc: + if not _names_nothing(exc): + # A real I/O failure, which must not be reported as a miss. Under + # the v3 spec an absent chunk is an uninitialized one, and a + # reader is right to substitute the array's fill value for it -- + # so 404 asserts something about the store's contents. An + # unreadable chunk is not an uninitialized chunk, and answering + # 404 would have a correct client silently materialize fill + # values over data that exists. + raise + return Response(status_code=404) + if buf is None: + return Response(status_code=404) + + if byte_range is None: + return Response(content=buf.to_bytes(), status_code=200, media_type=content_type) + + body = buf.to_bytes() + if len(body) == 0: + # The range lies wholly beyond the end of the object. + return Response(status_code=416) + + headers = {"Content-Range": _content_range(byte_range, len(body))} + return Response(content=body, status_code=206, media_type=content_type, headers=headers) + + +async def _handle_request(request: Request) -> Response: + """Handle a request, optionally filtering by node validity.""" + from starlette.responses import Response + + store: Store = request.app.state.store + node: Array[Any] | Group | None = request.app.state.node + prefix: str = request.app.state.prefix + path = request.path_params.get("path", "") + + # Reject non-canonical / traversal-prone keys before touching the store. + # Starlette percent-decodes path params, so "..%2f" arrives as a literal + # ".." segment and "%2f"-encoded leading slashes arrive as an empty leading + # segment (making the key absolute, which escapes a filesystem store root). + # Backslashes are separators on Windows and drive-qualified or + # root-relative keys discard a filesystem store's root entirely, so fold + # separators before checking segments -- mirroring zarr's normalize_path + # (src/zarr/storage/_utils.py) plus a drive check it doesn't need. Legitimate + # zarr keys never contain empty, ".", or ".." segments, or a drive letter. + segments = path.replace("\\", "/").split("/") + if any(segment in ("", ".", "..") for segment in segments) or _is_drive_qualified(path): + return Response(status_code=404) + + # A NUL can never appear in a store key, and reaches the filesystem layer + # as a raised error rather than a miss. Rejecting it here keeps that out + # of the store, so the store's own errors always mean real I/O trouble. + if "\x00" in path: + return Response(status_code=404) + + # If serving a node, validate the key before touching the store. Group + # validation opens children through zarr's synchronous API, which drives + # the store to completion and would otherwise block the event loop for + # the duration -- serializing every concurrent request behind it, and + # outlasting the shutdown timeout. + if node is not None and not await asyncio.to_thread(is_valid_node_key, node, path): + return Response(status_code=404) + + # Resolve the full store key by prepending the node's prefix. + store_key = f"{prefix}/{path}" if prefix else path + + if request.method == "PUT": + if store.read_only: + # The store will refuse this with a ValueError from deep inside + # `set`, which is a 500 -- a server fault. Refusing to write to a + # read-only store is not a fault, it is the answer. + return Response(status_code=403) + + max_body_size: int | None = request.app.state.max_body_size + if max_body_size is None: + body = await request.body() + else: + declared = request.headers.get("content-length") + if declared is not None and declared.isdigit() and int(declared) > max_body_size: + return Response(status_code=413) + + # Read incrementally and stop at the cap. `request.body()` would + # buffer the whole body first, which a chunked request can use to + # exceed the cap by any amount before it is ever checked. + chunks: list[bytes] = [] + received = 0 + async for chunk in request.stream(): + received += len(chunk) + if received > max_body_size: + return Response(status_code=413) + chunks.append(chunk) + body = b"".join(chunks) + + buf = cpu.buffer_prototype.buffer.from_bytes(body) + try: + await store.set(store_key, buf) + except OSError as exc: + if not _names_nothing(exc): + # A real write failure -- a full disk, a read-only mount, a + # permissions problem. Reporting it as 404 would tell the + # client the write is pointless rather than failed. + raise + return Response(status_code=404) + return Response(status_code=204) + + if request.method == "HEAD": + # A HEAD body is discarded at the wire, so reading the value to build + # one transfers the whole object to answer a question about its size. + # `getsize` is a stat on a filesystem store and a HEAD/info call on a + # remote one. + return await _head_response(store, store_key, content_type_for(path)) + + range_header = request.headers.get("range") + byte_range: RangeByteRequest | OffsetByteRequest | None = None + if range_header is not None: + parsed = _parse_range_header(range_header) + if parsed is _RangeVerdict.UNSATISFIABLE: + return Response(status_code=416) + if isinstance(parsed, SuffixByteRequest): + parsed = await _resolve_suffix(store, store_key, parsed) + if parsed is _RangeVerdict.UNSATISFIABLE: + return Response(status_code=416) + # _RangeVerdict.IGNORE falls through with byte_range still None, which + # serves the full representation with 200. + if not isinstance(parsed, _RangeVerdict): + byte_range = parsed + + return await _get_response(store, store_key, byte_range) + + +def _make_starlette_app( + *, + methods: AbstractSet[HTTPMethod] | None = None, + cors_options: CorsOptions | None = None, +) -> Starlette: + """Create a Starlette app with the request handler. + + Raises + ------ + ValueError + If `methods` contains anything outside `GET`, `PUT`, and `HEAD`. + """ + from starlette.applications import Starlette + from starlette.middleware.cors import CORSMiddleware + from starlette.routing import Route + + if methods is None: + methods = READ_ONLY_HTTP_METHODS + + # An empty set must not reach Starlette: `Route` treats a falsy `methods` + # as "match every method", so asking for no methods would serve them all. + if not methods: + raise ValueError( + "methods must name at least one HTTP method; " + f"accepted methods are {', '.join(sorted(_SUPPORTED_METHODS))}." + ) + + unsupported = sorted(set(methods) - _SUPPORTED_METHODS) + if unsupported: + raise ValueError( + f"Unsupported HTTP method(s): {', '.join(unsupported)}. " + f"Accepted methods are {', '.join(sorted(_SUPPORTED_METHODS))}." + ) + + app = Starlette( + routes=[Route("/{path:path}", _handle_request, methods=list(methods))], + ) + + if cors_options is not None: + # Typed loosely on purpose: unpacking a merged TypedDict loses the + # per-key types, so the looseness is contained to this block rather + # than spread across casts at each use. + merged: dict[str, Any] = {**_CORS_DEFAULTS, **cors_options} + if "allow_methods" in merged: + # Only when the caller said something. Absent, Starlette's own + # `GET`-only default stands: widening it to everything served + # would newly advertise `PUT` cross-origin on a write-enabled app + # that never asked for it. + merged["allow_methods"] = _reconcile_allow_methods( + merged["allow_methods"], served=_served_methods(methods) + ) + app.add_middleware( + CORSMiddleware, + # Our defaults first, so a key the caller supplied wins outright + # rather than being merged into -- an explicit `expose_headers: []` + # means "expose nothing", not "expose our default". + **merged, + ) + return app + + +def _reject_writes_to_a_read_only_store( + store: Store, methods: AbstractSet[HTTPMethod] | None +) -> None: + """Refuse a configuration whose writes can never succeed. + + A store's `read_only` is fixed when it is built, so asking to serve `PUT` + from one is a contradiction that would only reveal itself as a 403 on the + first write a client attempts -- possibly long after deployment, and to + the client rather than to whoever misconfigured it. Saying so at + construction matches how unsupported `methods` and contradictory + `cors_options` are already handled. + + Raises + ------ + ValueError + If `methods` asks for `PUT` on a read-only store. + """ + if methods is not None and "PUT" in methods and store.read_only: + raise ValueError( + "methods asks for PUT, but the store is read-only, so no write " + "could ever succeed. Drop PUT to serve reads, or pass a writable " + "store (`store.with_read_only(False)`)." + ) + + +def _served_methods(methods: AbstractSet[HTTPMethod]) -> frozenset[str]: + """The methods the route will actually answer. + + Starlette adds `HEAD` to any route that serves `GET`, which RFC 9110 + §9.3.2 asks of every origin server, so `HEAD` is served whenever `GET` is + whether or not it was named. + """ + served = set(methods) + if "GET" in served: + served.add("HEAD") + return frozenset(served) + + +def _reconcile_allow_methods(allow_methods: list[str], *, served: frozenset[str]) -> list[str]: + """Check `cors_options["allow_methods"]` against what the route serves. + + An advertised method the route rejects is a promise the server cannot + keep: a browser caches the preflight and every later cross-origin call + fails with 405 after a successful handshake. The reverse is worse -- the + same silence lets `allow_methods=["*"]` on a write-enabled app hand every + origin on the internet write access, which is exactly the footgun the + `methods` validation above exists to prevent. + + `"*"` expands to what is actually served rather than being rejected: it + is the idiomatic spelling of "everything this app does", and the app + cannot do more than it serves. + """ + if "*" in allow_methods: + return sorted(served) + + unserved = sorted(set(allow_methods) - served) + if unserved: + raise ValueError( + f"cors_options['allow_methods'] advertises {', '.join(unserved)}, " + f"which this app does not serve (it serves {', '.join(sorted(served))}). " + "A browser would cache that preflight and every such request would " + "then fail with 405." + ) + return list(allow_methods) + + +def _build_server( + app: Starlette, + *, + host: str, + port: int | Literal["auto"], + shutdown_timeout: int, + uvicorn_options: Mapping[str, object] | None, +) -> tuple[uvicorn.Server, dict[str, object], socket.socket | None]: + """Configure a `uvicorn.Server` for *app*, and report how it will bind. + + Returns the options actually used -- a key from `uvicorn_options` may have + replaced one passed here -- and, for `port="auto"`, the socket already + bound on the caller's behalf, which must be handed to `Server.run`. + """ + import uvicorn + + options: dict[str, object] = { + "host": host, + "port": port, + "timeout_graceful_shutdown": shutdown_timeout, + } + if uvicorn_options is not None: + options.update(uvicorn_options) + + sock: socket.socket | None = None + if options.get("port") == AUTO_PORT: + if _binds_without_a_port(options): + # A uds or fd bind ignores host and port; leave a valid int in + # place of the sentinel so `Config` still type-checks. + options["port"] = DEFAULT_PORT + else: + # Bind here rather than probing and handing uvicorn a port number: + # probing would release the port before uvicorn claimed it, which + # is the bind-then-close race that makes "find a free port" helpers + # flaky. Holding the socket means nothing can take it in between. + sock = _bind_preferred_or_free(str(options["host"]), DEFAULT_PORT) + # Keep Config agreeing with reality, so uvicorn's own "running on + # ..." line names the port it is really serving. + options["port"] = sock.getsockname()[1] + + # uvicorn.Config's parameters are individually typed and there are ~50 of + # them; `Mapping[str, object]` is the honest type for the public argument, + # so the cast is confined to the call itself. + return uvicorn.Server(uvicorn.Config(app, **cast("dict[str, Any]", options))), options, sock + + +def _binds_without_a_port(options: Mapping[str, object]) -> bool: + """Whether these options bind something other than a TCP host and port.""" + return options.get("uds") is not None or options.get("fd") is not None + + +def _bind_preferred_or_free(host: str, preferred: int) -> socket.socket: + """Bind *preferred* on *host* if it is free, otherwise any free port. + + The address family comes from `getaddrinfo` rather than being assumed: + hard-coding `AF_INET` would fail for an IPv6 host such as ``"::1"``. + """ + for candidate in (preferred, 0): + family, socktype, proto, _, sockaddr = socket.getaddrinfo( + host, candidate, type=socket.SOCK_STREAM + )[0] + sock = socket.socket(family, socktype, proto) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.bind(sockaddr) + except OSError: + sock.close() + if candidate == 0: + # Nothing is free, which is a real failure rather than a + # reason to keep looking. + raise + _LOGGER.info( + "port %d is in use; binding a free port instead. Pass an " + "explicit port to require a particular one.", + preferred, + ) + continue + return sock + raise AssertionError("unreachable") # pragma: no cover + + +def serve( + app: Starlette, + *, + host: str = "127.0.0.1", + port: int | Literal["auto"] = AUTO_PORT, + shutdown_timeout: int = 5, + uvicorn_options: Mapping[str, object] | None = None, +) -> None: + """Run an ASGI app under Uvicorn, blocking until it is stopped. + + Returns only when the server stops, so this is the shape for a process + whose job is to serve -- a script, a container entrypoint. Use + :func:`serve_background` when the caller has more to do. + + Build the app first with :func:`store_app` or :func:`node_app`, or compose + several of them; what an app serves is settled when it is built, and this + only decides how it runs. + + .. code-block:: python + + serve(store_app(store), host="0.0.0.0", port=8000) + + Parameters + ---------- + app : Starlette + The ASGI app to run. + host : str, optional + The host to bind to. Defaults to ``"127.0.0.1"``. + port : int, optional + The port to bind to. Defaults to ``8000``. + shutdown_timeout : int, optional + Seconds to wait for in-flight requests to finish gracefully when the + server is shut down, via uvicorn's ``timeout_graceful_shutdown``. + Defaults to ``5``. + uvicorn_options : Mapping[str, object], optional + Extra options passed straight to `uvicorn.Config`, merged over the + ones set here (`host`, `port`, `timeout_graceful_shutdown`), so a + caller key wins. This is the escape hatch for anything uvicorn can do + that this signature does not name -- TLS via `ssl_keyfile` / + `ssl_certfile`, `proxy_headers` and `forwarded_allow_ips` behind a + reverse proxy, `root_path` when mounted under a prefix, `log_level`, + `limit_concurrency`, or a `uds` / `fd` bind. + """ + server, _, sock = _build_server( + app, + host=host, + port=port, + shutdown_timeout=shutdown_timeout, + uvicorn_options=uvicorn_options, + ) + server.run(sockets=[sock] if sock is not None else None) + + +def serve_background( + app: Starlette, + *, + host: str = "127.0.0.1", + port: int | Literal["auto"] = AUTO_PORT, + shutdown_timeout: int = 5, + uvicorn_options: Mapping[str, object] | None = None, +) -> BackgroundServer: + """Start an ASGI app under Uvicorn in a daemon thread and return at once. + + Returns once the socket is listening, so the next statement can use the + server. The returned handle is also a context manager: + + .. code-block:: python + + with serve_background(node_app(array)) as server: + httpx.get(f"{server.url}/zarr.json") + + In a notebook, where the server must outlive the cell that started it, + keep the handle instead and call :meth:`BackgroundServer.shutdown` later. + + Parameters + ---------- + app : Starlette + The ASGI app to run. + host : str, optional + The host to bind to. Defaults to ``"127.0.0.1"``. + port : int, optional + The port to bind to. Defaults to ``0``, which asks the OS for a free + one -- unlike :func:`serve`, whose caller usually needs a port others + already know. A background server is normally reached through + :attr:`BackgroundServer.url`, and a fixed default would make starting + a second one, or re-running a notebook cell, fail on a port collision. + shutdown_timeout : int, optional + Seconds to wait for in-flight requests to finish gracefully, both for + uvicorn's ``timeout_graceful_shutdown`` and for the wait + :meth:`BackgroundServer.shutdown` uses before forcing the thread + closed. Defaults to ``5``. + uvicorn_options : Mapping[str, object], optional + Extra options passed straight to `uvicorn.Config`, merged over the + ones set here so a caller key wins. See :func:`serve`. Binding + somewhere other than a TCP host and port leaves + :attr:`BackgroundServer.url` as ``None``. + + Returns + ------- + BackgroundServer + A handle for the running server. + + Raises + ------ + RuntimeError + If the server does not start -- most often because the port is + already in use. + """ + server, options, sock = _build_server( + app, + host=host, + port=port, + shutdown_timeout=shutdown_timeout, + uvicorn_options=uvicorn_options, + ) + + # uvicorn skips signal-handler installation off the main thread + # (Server.capture_signals), so no workaround is needed here. + thread = threading.Thread( + target=partial(server.run, sockets=[sock] if sock is not None else None), daemon=True + ) + thread.start() + + deadline = time.monotonic() + _STARTUP_TIMEOUT + while not server.started: + if not thread.is_alive(): + # uvicorn logs the underlying error and calls sys.exit, which in a + # thread ends it without surfacing anything to the caller. The + # overwhelmingly common cause is a port already in use. + raise RuntimeError( + f"Server thread exited before startup completed; {host}:{port} " + "may already be in use. See the server log for the cause." + ) + if time.monotonic() > deadline: + # The thread is still alive here, unlike the branch above, and it + # is about to finish starting. Raising without stopping it would + # leave a server bound to the port with no handle to shut it down + # -- a daemon thread serving for the rest of the process, and a + # retry on the same port failing with the other error above. + server.should_exit = True + server.force_exit = True + thread.join(timeout=_STARTUP_ABANDON_TIMEOUT) + raise RuntimeError( + f"Server failed to start within {_STARTUP_TIMEOUT:g} seconds; " + "it has been signalled to stop." + ) + time.sleep(0.01) + + # Report the port the socket actually bound rather than the one asked for, + # so `port=0` ("pick a free port") yields a usable `url`. A unix-socket or + # file-descriptor bind has no host and port at all, so both stay None and + # `url` reports None rather than naming an address nothing is listening on. + bound_port: int | None = None + for bound in server.servers: + for sock in bound.sockets: + sockname = sock.getsockname() + if isinstance(sockname, tuple) and len(sockname) >= 2: + bound_port = int(sockname[1]) + break + break + + # The host is taken from the request rather than the socket: a wildcard + # bind reports "0.0.0.0", which is not an address a client can connect to. + requested_host = options.get("host") + bound_host = ( + str(requested_host) if bound_port is not None and requested_host is not None else None + ) + + return BackgroundServer( + server, + thread, + host=bound_host, + port=bound_port, + scheme="https" if server.config.is_ssl else "http", + shutdown_timeout=shutdown_timeout, + ) + + +def store_app( + store: Store, + *, + methods: AbstractSet[HTTPMethod] | None = None, + cors_options: CorsOptions | None = None, + max_body_size: int | None = DEFAULT_MAX_BODY_SIZE, +) -> Starlette: + """Create a Starlette ASGI app that serves every key in a zarr ``Store``. + + Parameters + ---------- + store : Store + The zarr store to serve. + methods : set of HTTPMethod, optional + The HTTP methods to accept: any of `"GET"`, `"HEAD"`, and `"PUT"`. + Defaults to `{"GET"}`, which also serves `HEAD`. Passing any other + method raises `ValueError`. + cors_options : CorsOptions, optional + If provided, CORS middleware will be added with the given options. + max_body_size : int or None, optional + Largest `PUT` body to accept, in bytes; larger requests get a 413. + `Store.set` takes a whole `Buffer`, so bodies cannot be streamed and + are held in memory in full. Defaults to `DEFAULT_MAX_BODY_SIZE`; + pass `None` to lift the cap. + + Returns + ------- + Starlette + An ASGI application. + """ + _reject_writes_to_a_read_only_store(store, methods) + app = _make_starlette_app(methods=methods, cors_options=cors_options) + app.state.store = store + app.state.node = None + app.state.prefix = "" + app.state.max_body_size = max_body_size + return app + + +def node_app( + node: Array[Any] | Group, + *, + methods: AbstractSet[HTTPMethod] | None = None, + cors_options: CorsOptions | None = None, + max_body_size: int | None = DEFAULT_MAX_BODY_SIZE, +) -> Starlette: + """Create a Starlette ASGI app that serves only the keys belonging to a + zarr ``Array`` or ``Group``. + + For an ``Array``, the served keys are the metadata document(s) and all + chunk (or shard) keys whose coordinates fall within the array's grid. + + For a ``Group``, the served keys are the group's own metadata plus any + path that resolves through the group's members to a valid array metadata + document or chunk key. + + Requests for keys outside this set receive a 404 response, even if the + underlying store contains data at that path. + + Parameters + ---------- + node : Array or Group + The zarr array or group to serve. + methods : set of HTTPMethod, optional + The HTTP methods to accept: any of `"GET"`, `"HEAD"`, and `"PUT"`. + Defaults to `{"GET"}`, which also serves `HEAD`. Passing any other + method raises `ValueError`. + cors_options : CorsOptions, optional + If provided, CORS middleware will be added with the given options. + max_body_size : int or None, optional + Largest `PUT` body to accept, in bytes; larger requests get a 413. + `Store.set` takes a whole `Buffer`, so bodies cannot be streamed and + are held in memory in full. Defaults to `DEFAULT_MAX_BODY_SIZE`; + pass `None` to lift the cap. + + Returns + ------- + Starlette + An ASGI application. + """ + _reject_writes_to_a_read_only_store(node.store_path.store, methods) + app = _make_starlette_app(methods=methods, cors_options=cors_options) + app.state.store = node.store_path.store + app.state.node = node + app.state.prefix = node.store_path.path + app.state.max_body_size = max_body_size + return app diff --git a/packages/zarr-http-server/src/zarr_http_server/py.typed b/packages/zarr-http-server/src/zarr_http_server/py.typed new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-http-server/tests/conftest.py b/packages/zarr-http-server/tests/conftest.py new file mode 100644 index 0000000000..84694b42ba --- /dev/null +++ b/packages/zarr-http-server/tests/conftest.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +import pytest +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from zarr.abc.store import Store + +ZarrFormat = Literal[2, 3] + + +@pytest.fixture +def store(request: pytest.FixtureRequest) -> Store: + """Store fixture resolved via indirect parametrization.""" + if request.param != "memory": + raise ValueError(f"unsupported store param: {request.param!r}") + return MemoryStore() + + +@pytest.fixture(params=(2, 3), ids=["zarr2", "zarr3"]) +def zarr_format(request: pytest.FixtureRequest) -> ZarrFormat: + """Zarr format version fixture, parametrized over v2 and v3.""" + if request.param == 2: + return 2 + elif request.param == 3: + return 3 + msg = f"Invalid zarr format requested. Got {request.param}, expected one of (2, 3)." + raise ValueError(msg) diff --git a/packages/zarr-http-server/tests/test_examples.py b/packages/zarr-http-server/tests/test_examples.py new file mode 100644 index 0000000000..20a5d5b1b0 --- /dev/null +++ b/packages/zarr-http-server/tests/test_examples.py @@ -0,0 +1,60 @@ +"""The shipped examples must keep working. + +An example that has quietly rotted is worse than no example: it is the first +thing a new user copies. These run the real files rather than a paraphrase of +them, so a signature change or a behavior change fails here rather than in +someone's notebook. +""" + +from __future__ import annotations + +import pathlib +import runpy + +import pytest + +EXAMPLES = pathlib.Path(__file__).resolve().parent.parent / "examples" +NOTEBOOK = EXAMPLES / "serve_notebook.ipynb" +SCRIPT = EXAMPLES / "serve.py" + + +@pytest.mark.parametrize("path", [NOTEBOOK, SCRIPT], ids=["notebook", "script"]) +def test_example_exists(path: pathlib.Path) -> None: + """Guards the paths above: a renamed or moved example would otherwise turn + its execution test into a skip, or a no-op, that nobody notices.""" + assert path.is_file(), f"missing example at {path}" + + +def test_serve_script_runs() -> None: + """Run examples/serve.py top to bottom. + + In-process rather than as a subprocess: the script's inline uv metadata + resolves `zarr-http-server` from git, so `uv run` on it would test whatever + is on main instead of the working tree. + """ + runpy.run_path(str(SCRIPT), run_name="__main__") + + +def test_serve_notebook_executes() -> None: + """Run every cell in a real kernel. + + The notebook asserts its own expectations -- status codes, byte ranges, + that a PUT is refused, that the port is closed after `shutdown()` -- so + this is not merely a check that nothing raised. `NotebookClient.execute` + defaults to ``allow_errors=False``, so any failed cell raises + `CellExecutionError` and fails this test with that cell's traceback. + """ + nbformat = pytest.importorskip("nbformat") + nbclient = pytest.importorskip("nbclient") + pytest.importorskip("ipykernel", reason="a kernel is needed to execute the notebook") + + notebook = nbformat.read(NOTEBOOK, as_version=4) + + # Run with the notebook's own directory as cwd, so any relative path it + # uses means the same thing as when a reader opens it. + nbclient.NotebookClient( + notebook, + timeout=300, + kernel_name="python3", + resources={"metadata": {"path": str(EXAMPLES)}}, + ).execute() diff --git a/packages/zarr-http-server/tests/test_properties.py b/packages/zarr-http-server/tests/test_properties.py new file mode 100644 index 0000000000..ff54392dfc --- /dev/null +++ b/packages/zarr-http-server/tests/test_properties.py @@ -0,0 +1,580 @@ +"""Property-based tests driven against a real HTTP endpoint. + +Every test here talks to an actual uvicorn server over a socket, not to an +in-process ASGI client, so the properties cover the parts of the stack that +only exist on the wire: header parsing, method dispatch, and status codes. + +Each property checks **two** things after a request -- the response, and the +state of the backing store. That pairing is the point. A server can answer +correctly and corrupt the store, or refuse a request and write anyway, and a +response-only assertion sees neither. The bug that motivated this module did +exactly that: a `PUT` to a non-canonically spelled chunk key ("c/00/00" +instead of "c/0/0") answered `204 No Content` and stored the body under a key +no reader ever looks up, so the client saw success and the data was invisible. + +The vocabulary below splits keys into two families: + +* **in-band** -- keys the served node genuinely owns: its metadata documents + and the canonical spelling of each chunk key in its grid. These must be + served, and writes to them must be visible to a zarr reader. +* **out-of-band** -- everything else: non-canonical spellings of a valid + chunk key, coordinates outside the grid, traversal attempts, and keys + belonging to a sibling node. These must be refused *and* must leave the + store byte-for-byte unchanged. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal +from urllib.parse import quote + +import httpx +import numpy as np +import pytest +import zarr +from hypothesis import assume, given, settings +from hypothesis import strategies as st +from zarr.buffer import cpu +from zarr.core.sync import sync + +from zarr_http_server import node_app, serve_background, store_app +from zarr_http_server._keys import _shard_grid_shape + +if TYPE_CHECKING: + from collections.abc import Iterator + + from zarr import Array + from zarr.abc.store import Store + +# Real HTTP round trips are slower and jumpier than hypothesis' default +# deadline allows, and a CI runner under load makes that worse. +_HTTP = settings(deadline=None, max_examples=50) + +# An uncompressed array so a chunk's bytes are exactly its raw values: a PUT +# body of the right length is a legitimate chunk, which lets these tests +# assert that a write is readable through a zarr client rather than merely +# present in the store. +_SHAPE = (6, 4) +_CHUNKS = (2, 2) +_DTYPE = "int32" + + +@dataclass(frozen=True) +class Served: + """A running server plus the handles needed to reason about its keys.""" + + url: str + store: Store + array: Array[Any] + kind: Literal["store", "node"] + + http_prefix: str + """Prepended to an array-relative key to form the request path.""" + + store_prefix: str + """Prepended to an array-relative key to form the backing store key.""" + + def path(self, array_relative_key: str) -> str: + return f"{self.http_prefix}{array_relative_key}" + + def store_key(self, array_relative_key: str) -> str: + return f"{self.store_prefix}{array_relative_key}" + + +def _snapshot(store: Store) -> dict[str, bytes]: + """Every key in *store* mapped to its bytes. + + Comparing two snapshots is how these tests assert that a rejected request + changed nothing -- not just that it added no key, but that it modified + none either. + """ + + async def _read() -> dict[str, bytes]: + out: dict[str, bytes] = {} + async for key in store.list(): + buf = await store.get(key, cpu.buffer_prototype) + if buf is not None: + out[key] = buf.to_bytes() + return out + + return sync(_read()) + + +@pytest.fixture( + scope="module", + params=[ + ("store", 2, "memory"), + ("store", 3, "memory"), + ("node", 2, "memory"), + ("node", 3, "memory"), + # LocalStore reads through the filesystem, which sizes its read from + # the range rather than from the object and so raises on an over-wide + # one. MemoryStore just slices a `bytes` and is happy with any bound, + # so a memory-only matrix cannot tell a clamped range from a refused + # one -- the store backend is part of what these properties test. + ("store", 3, "local"), + ("node", 3, "local"), + ], + ids=["store-v2", "store-v3", "node-v2", "node-v3", "store-v3-local", "node-v3-local"], +) +def served( + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory +) -> Iterator[Served]: + """One real server per (app kind, zarr format, store backend). + + Module-scoped because hypothesis drives hundreds of requests per test and + a server per example would dominate the runtime. `port=0` lets the OS + choose the port and `server.url` reports what it actually bound, which + avoids the bind-then-close race of picking a port up front. + """ + kind, zarr_format, backend = request.param + + store: Store + if backend == "local": + root_dir = tmp_path_factory.mktemp(f"{kind}-v{zarr_format}") + store = zarr.storage.LocalStore(root_dir) + else: + store = zarr.storage.MemoryStore() + root = zarr.open_group(store, mode="w", zarr_format=zarr_format) + array = root.create_array( + "inside", shape=_SHAPE, chunks=_CHUNKS, dtype=_DTYPE, compressors=None + ) + array[:] = np.arange(int(np.prod(_SHAPE)), dtype=_DTYPE).reshape(_SHAPE) + # A sibling the node_app must never serve, and whose keys therefore make + # good out-of-band probes. + sibling = root.create_array( + "outside", shape=_CHUNKS, chunks=_CHUNKS, dtype=_DTYPE, compressors=None + ) + sibling[:] = 1 + + if kind == "node": + server = serve_background(node_app(array, methods={"GET", "PUT"}), host="127.0.0.1", port=0) + http_prefix = "" + else: + server = serve_background( + store_app(store, methods={"GET", "PUT"}), host="127.0.0.1", port=0 + ) + http_prefix = "inside/" + assert server is not None + + try: + yield Served( + url=server.url, + store=store, + array=array, + kind=kind, + http_prefix=http_prefix, + store_prefix="inside/", + ) + finally: + server.shutdown() + + +def _grid(array: Array[Any]) -> tuple[int, ...]: + return _shard_grid_shape(array) + + +@st.composite +def chunk_coords(draw: st.DrawFn, array: Array[Any]) -> tuple[int, ...]: + """Coordinates of a chunk that exists in *array*'s storage grid.""" + return tuple(draw(st.integers(min_value=0, max_value=g - 1)) for g in _grid(array)) + + +@st.composite +def out_of_grid_coords(draw: st.DrawFn, array: Array[Any]) -> tuple[int, ...]: + """Coordinates outside the grid, so the key is well-formed but names nothing.""" + grid = _grid(array) + axis = draw(st.integers(min_value=0, max_value=len(grid) - 1)) + coords = list(draw(chunk_coords(array))) + coords[axis] = draw(st.integers(min_value=grid[axis], max_value=grid[axis] + 50)) + return tuple(coords) + + +# The confusability with ASCII digits is the point: `int()` accepts these as +# decimal digits, so they name a different store key while decoding to the +# same coordinate. That is the defect these strategies probe for. +_ARABIC_INDIC = "٠١٢٣٤٥٦٧٨٩" +_FULLWIDTH = "0123456789" # noqa: RUF001 + + +def _respellings(digits: str) -> list[str]: + """Strings `int()` maps to the same value as *digits*, spelled differently. + + These are exactly the spellings that make decode-only validation unsafe: + each names a *different* store key while decoding to the same coordinate. + """ + value = int(digits) + return [ + f"0{digits}", + f"00{digits}", + f"+{digits}", + f" {digits}", + f"{digits} ", + f"\t{digits}", + "".join(_ARABIC_INDIC[int(d)] for d in digits), + "".join(_FULLWIDTH[int(d)] for d in digits), + *([f"-{digits}"] if value == 0 else []), + ] + + +@st.composite +def non_canonical_chunk_keys(draw: st.DrawFn, array: Array[Any]) -> str: + """A chunk key that decodes into the grid but is not zarr's own spelling. + + Built by taking the canonical key and re-spelling one of its digit runs, + which keeps this strategy independent of the chunk key encoding's grammar. + """ + coords = draw(chunk_coords(array)) + canonical = array.metadata.encode_chunk_key(coords) + runs = list(re.finditer(r"\d+", canonical)) + assume(runs) + run = draw(st.sampled_from(runs)) + replacement = draw(st.sampled_from(_respellings(run.group()))) + key = canonical[: run.start()] + replacement + canonical[run.end() :] + assume(key != canonical) + return key + + +TRAVERSAL_KEYS = [ + # Percent-encoded on purpose. An HTTP client resolves dot-segments before + # it sends -- httpx turns "../secret" into "/secret" and ".." into "/" per + # RFC 3986 §5.2.4 -- so a literal "../" probe never reaches the server as + # traversal and asserts nothing. Encoded, it survives the client intact + # and Starlette decodes it back into a real ".." segment on arrival, which + # is the form the server's own guard has to catch. + "..%2Fsecret", + "%2e%2e%2Fsecret", + "%2e%2e%2F%2e%2e%2Fetc%2Fpasswd", + "%2e%2e", + "%2e", + "%2e%2Fzarr.json", + "a%2F..%2F..%2Fb", + "%2Fabsolute", + "sub%2F%2Fempty", + "C%3A%2Fwindows", + "..%5Cwindows", + "a%5C..%5C..%5Cb", + "%00nul", +] + + +def _chunk_payload(array: Array[Any]) -> bytes: + """Bytes of a full, uncompressed chunk for *array*.""" + return np.zeros(_CHUNKS, dtype=array.dtype).tobytes() + + +def _url(served: Served, array_relative_key: str) -> str: + """Request URL for a key, percent-encoded so it survives the wire verbatim. + + Generated keys contain characters a URL cannot carry literally -- a tab + makes httpx raise `InvalidURL`, and a space or a non-ASCII digit would be + re-encoded on the way out anyway. Encoding here means Starlette decodes + the path param back to exactly the key the strategy produced, so the + property really is "for any key K, a request for K is refused" rather than + "for any key the URL parser happened to leave alone". + """ + return f"{served.url}/{quote(served.path(array_relative_key), safe='/')}" + + +def _require_node_scope(served: Served) -> None: + """Skip a property that only a node-scoped app can satisfy. + + `store_app` proxies the store's raw key space and has no array semantics + to validate against, so every syntactically acceptable key is in-band for + it by contract -- including a non-canonical chunk spelling. Only + `node_app` claims to serve exactly one node's keys, so only `node_app` can + be held to what that set contains. + """ + if served.kind != "node": + pytest.skip("store_app serves the raw key space; node scoping does not apply") + + +class TestInBandRequests: + """Keys the node owns are served, and writes to them are visible.""" + + @given(data=st.data()) + @_HTTP + def test_get_of_a_canonical_key_returns_the_stored_bytes( + self, served: Served, data: st.DataObject + ) -> None: + """A GET of an in-band key returns exactly what the store holds, and + reading never changes the store.""" + coords = data.draw(chunk_coords(served.array)) + relative = served.array.metadata.encode_chunk_key(coords) + + before = _snapshot(served.store) + response = httpx.get(_url(served, relative), timeout=30) + + expected = before.get(served.store_key(relative)) + if expected is None: + assert response.status_code == 404 + else: + assert response.status_code == 200 + assert response.content == expected + assert _snapshot(served.store) == before + + @given(data=st.data()) + @_HTTP + def test_put_of_a_canonical_key_is_stored_and_readable( + self, served: Served, data: st.DataObject + ) -> None: + """The headline property: a PUT that reports success must be visible. + + Success means three things at once -- a 2xx, the bytes landing under + the key the client named, and a zarr client subsequently reading back + the values that were written. The original defect satisfied the first + and failed the other two. + """ + coords = data.draw(chunk_coords(served.array)) + fill = data.draw(st.integers(min_value=-(2**31), max_value=2**31 - 1)) + relative = served.array.metadata.encode_chunk_key(coords) + payload = np.full(_CHUNKS, fill, dtype=served.array.dtype).tobytes() + + before = _snapshot(served.store) + response = httpx.put(_url(served, relative), content=payload, timeout=30) + assert response.status_code == 204 + + after = _snapshot(served.store) + key = served.store_key(relative) + assert after[key] == payload, "the body did not land under the key the client named" + assert set(after) - set(before) <= {key}, "the write touched a key the client did not name" + + # The write is not merely present, it is legible: reopen the array and + # read the chunk the coordinates address. + reread = zarr.open_array(served.store, path="inside") + block = tuple(slice(c * s, (c + 1) * s) for c, s in zip(coords, _CHUNKS, strict=True)) + assert np.array_equal(reread[block], np.full(_CHUNKS, fill, dtype=served.array.dtype)) + + @given(data=st.data()) + @_HTTP + def test_range_of_a_stored_key_returns_the_matching_slice( + self, served: Served, data: st.DataObject + ) -> None: + """A satisfiable range returns exactly the bytes it names, and says so + in Content-Range.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + key = served.store_key(relative) + before = _snapshot(served.store) + assume(key in before) + body = before[key] + + start = data.draw(st.integers(min_value=0, max_value=len(body) - 1)) + end = data.draw(st.integers(min_value=start, max_value=len(body) - 1)) + + response = httpx.get( + _url(served, relative), headers={"Range": f"bytes={start}-{end}"}, timeout=30 + ) + + assert response.status_code == 206 + assert response.content == body[start : end + 1] + # RFC 9110 §15.3.7: a single-part 206 must carry Content-Range, and it + # must describe the bytes actually returned. + content_range = response.headers["content-range"] + assert content_range.startswith(f"bytes {start}-{start + len(response.content) - 1}/") + assert _snapshot(served.store) == before + + @given(suffix=st.integers(min_value=1, max_value=200)) + @_HTTP + def test_suffix_range_returns_the_tail_and_locates_it( + self, served: Served, suffix: int + ) -> None: + """A suffix range must report where in the object its bytes came from. + + Zarr's sharding codec reads a shard index this way, so a 206 without + Content-Range leaves the reader unable to tell a clamped whole-object + read from the tail it asked for. + """ + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + key = served.store_key(relative) + before = _snapshot(served.store) + assume(key in before) + body = before[key] + + response = httpx.get( + _url(served, relative), headers={"Range": f"bytes=-{suffix}"}, timeout=30 + ) + + assert response.status_code == 206 + expected = body[-suffix:] if suffix <= len(body) else body + assert response.content == expected + first = len(body) - len(expected) + assert response.headers["content-range"].startswith(f"bytes {first}-{len(body) - 1}/") + assert _snapshot(served.store) == before + + +class TestOutOfBandRequests: + """Keys the node does not own are refused, and change nothing.""" + + @given(data=st.data()) + @_HTTP + def test_non_canonical_chunk_key_is_refused_and_writes_nothing( + self, served: Served, data: st.DataObject + ) -> None: + """The regression that motivated this module. + + A key that decodes into the grid but is spelled differently from + zarr's own rendering names a store key no reader consults. Accepting a + write to it reports success and loses the data, so it must be refused + and the store must be untouched. + """ + _require_node_scope(served) + relative = data.draw(non_canonical_chunk_keys(served.array)) + payload = _chunk_payload(served.array) + + before = _snapshot(served.store) + put = httpx.put(_url(served, relative), content=payload, timeout=30) + assert put.status_code == 404 + assert _snapshot(served.store) == before, "a refused write still modified the store" + + get = httpx.get(_url(served, relative), timeout=30) + assert get.status_code == 404 + assert _snapshot(served.store) == before + + @given(data=st.data()) + @_HTTP + def test_out_of_grid_chunk_key_is_refused_and_writes_nothing( + self, served: Served, data: st.DataObject + ) -> None: + """Coordinates past the end of the grid address no chunk of this array.""" + _require_node_scope(served) + coords = data.draw(out_of_grid_coords(served.array)) + relative = served.array.metadata.encode_chunk_key(coords) + + before = _snapshot(served.store) + put = httpx.put(_url(served, relative), content=_chunk_payload(served.array), timeout=30) + get = httpx.get(_url(served, relative), timeout=30) + + assert put.status_code == 404 + assert get.status_code == 404 + assert _snapshot(served.store) == before + + @given(key=st.sampled_from(TRAVERSAL_KEYS)) + @_HTTP + def test_traversal_key_is_refused_and_writes_nothing(self, served: Served, key: str) -> None: + """Nothing that tries to leave the served scope may be served or written.""" + before = _snapshot(served.store) + put = httpx.put(f"{served.url}/{key}", content=b"payload", timeout=30) + get = httpx.get(f"{served.url}/{key}", timeout=30) + + assert put.status_code in (403, 404, 405), f"{key!r} was accepted for writing" + assert get.status_code in (403, 404, 405), f"{key!r} was served" + assert _snapshot(served.store) == before + + @given(data=st.data()) + @_HTTP + def test_node_app_never_serves_a_sibling(self, served: Served, data: st.DataObject) -> None: + """A node_app is scoped to one node, so a sibling's keys are invisible + even though they exist in the same store.""" + if served.kind != "node": + pytest.skip("store_app deliberately serves the whole store") + + coords = data.draw(chunk_coords(served.array)) + chunk = served.array.metadata.encode_chunk_key(coords) + relative = data.draw( + st.sampled_from( + [ + f"outside/{chunk}", + "outside/zarr.json", + "outside/.zarray", + f"../outside/{chunk}", + ] + ) + ) + + before = _snapshot(served.store) + get = httpx.get(f"{served.url}/{relative}", timeout=30) + put = httpx.put(f"{served.url}/{relative}", content=b"payload", timeout=30) + + assert get.status_code == 404 + assert put.status_code == 404 + assert _snapshot(served.store) == before + + +class TestMethodsAndRanges: + """Transport-level invariants that hold for every key.""" + + @given( + method=st.sampled_from(["DELETE", "POST", "PATCH", "OPTIONS"]), + data=st.data(), + ) + @_HTTP + def test_unconfigured_method_is_refused_and_writes_nothing( + self, served: Served, method: str, data: st.DataObject + ) -> None: + """Only the methods the app was configured with may reach the store.""" + coords = data.draw(chunk_coords(served.array)) + relative = served.array.metadata.encode_chunk_key(coords) + + before = _snapshot(served.store) + response = httpx.request(method, _url(served, relative), content=b"payload", timeout=30) + + assert response.status_code == 405 + assert _snapshot(served.store) == before + + @given( + header=st.sampled_from( + [ + "bytes=abc-def", + "bytes=0-1,4-5", + "chars=0-7", + "bytes=", + "nonsense", + "bytes=+0-1", + ] + ) + ) + @_HTTP + def test_unusable_range_serves_the_whole_object(self, served: Served, header: str) -> None: + """RFC 9110 §14.2: a Range the server cannot use is ignored, not refused.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + before = _snapshot(served.store) + key = served.store_key(relative) + assume(key in before) + + response = httpx.get(_url(served, relative), headers={"Range": header}, timeout=30) + + assert response.status_code == 200 + assert response.content == before[key] + assert "content-range" not in response.headers + + @given( + header=st.sampled_from( + [ + "bytes=5-2", + "bytes=-0", + "bytes=99999999999999999999-", + "bytes=100000-100001", + ] + ) + ) + @_HTTP + def test_unsatisfiable_range_is_refused(self, served: Served, header: str) -> None: + """A well-formed range that names nothing readable is a 416.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + before = _snapshot(served.store) + assume(served.store_key(relative) in before) + + response = httpx.get(_url(served, relative), headers={"Range": header}, timeout=30) + + assert response.status_code == 416 + assert _snapshot(served.store) == before + + @given(end=st.integers(min_value=10**19, max_value=10**30)) + @_HTTP + def test_absurdly_wide_range_is_clamped_not_refused(self, served: Served, end: int) -> None: + """RFC 9110 §14.1.2 clamps a last-byte-pos past the end of the object, + so an over-wide range reads to EOF rather than erroring.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + key = served.store_key(relative) + before = _snapshot(served.store) + assume(key in before) + + response = httpx.get( + _url(served, relative), headers={"Range": f"bytes=0-{end}"}, timeout=30 + ) + + assert response.status_code == 206 + assert response.content == before[key] + assert _snapshot(served.store) == before diff --git a/packages/zarr-http-server/tests/test_serve.py b/packages/zarr-http-server/tests/test_serve.py new file mode 100644 index 0000000000..8db6752ba1 --- /dev/null +++ b/packages/zarr-http-server/tests/test_serve.py @@ -0,0 +1,1831 @@ +from __future__ import annotations + +import asyncio +import errno +import os +import socket +from typing import TYPE_CHECKING, Any, Literal, get_args + +import numpy as np +import pytest +import zarr +from starlette.applications import Starlette +from starlette.routing import Mount +from starlette.testclient import TestClient +from zarr.buffer import cpu +from zarr.storage import LocalStore, MemoryStore + +from zarr_http_server._serve import ( + _SHUTDOWN_JOIN_MARGIN, + READ_ONLY_HTTP_METHODS, + READ_WRITE_HTTP_METHODS, + CorsOptions, + ReadOnlyHTTPMethod, + _bind_preferred_or_free, + _parse_range_header, + _RangeVerdict, + node_app, + serve_background, + store_app, +) + +if TYPE_CHECKING: + import pathlib + from collections.abc import Coroutine, Iterator + + from zarr.abc.store import Store + +ZarrFormat = Literal[2, 3] + +SHUTDOWN_TIMEOUT = 1 +"""shutdown_timeout used by the bounded-shutdown test.""" + +SLOW_HANDLER_SECONDS = 5 +"""How long that test's handler sleeps -- far longer than the shutdown bound, +so an unbounded join would be obvious.""" + + +def sync[T](coro: Coroutine[Any, Any, T]) -> T: + """Run a store coroutine to completion (tests use MemoryStore only).""" + return asyncio.run(coro) + + +@pytest.fixture +def group_with_arrays(store: Store) -> zarr.Group: + """Create a group containing a regular array and a sharded array.""" + root = zarr.open_group(store, mode="w") + zarr.create_array(root.store_path / "regular", shape=(4, 4), chunks=(2, 2), dtype="f8") + zarr.create_array( + root.store_path / "sharded", + shape=(8, 8), + chunks=(2, 2), + shards=(4, 4), + dtype="i4", + ) + return root + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeAppDoesNotExposeNonZarrKeys: + """node_app must never expose keys that are not part of the zarr hierarchy.""" + + def test_non_zarr_key_returns_404(self, store: Store, group_with_arrays: zarr.Group) -> None: + """A key that is not valid zarr metadata or a valid chunk key should return 404, + even if the underlying store contains data at that path.""" + non_zarr_buf = cpu.buffer_prototype.buffer.from_bytes(b"secret data") + sync(store.set("secret.txt", non_zarr_buf)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + # The non-zarr key must not be accessible. + response = client.get("/secret.txt") + assert response.status_code == 404 + + def test_non_zarr_key_nested_returns_404( + self, store: Store, group_with_arrays: zarr.Group + ) -> None: + """A non-zarr key nested under a real array's path should return 404, + even though the path prefix matches a valid zarr node.""" + non_zarr_buf = cpu.buffer_prototype.buffer.from_bytes(b"not a chunk") + sync(store.set("regular/notes.txt", non_zarr_buf)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/regular/notes.txt") + assert response.status_code == 404 + + def test_valid_metadata_is_accessible(self, group_with_arrays: zarr.Group) -> None: + """Zarr metadata keys (zarr.json) for both the root group and child arrays + should be served with a 200 status.""" + app = node_app(group_with_arrays) + client = TestClient(app) + + # Root group metadata + response = client.get("/zarr.json") + assert response.status_code == 200 + + # Array metadata + response = client.get("/regular/zarr.json") + assert response.status_code == 200 + + def test_valid_chunk_is_accessible(self, group_with_arrays: zarr.Group) -> None: + """A valid, in-bounds chunk key for an array with written data should + be served with a 200 status.""" + arr = group_with_arrays["regular"] + assert isinstance(arr, zarr.Array) + arr[:] = np.ones((4, 4)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + # c/0/0 is a valid chunk key for a (4,4) array with (2,2) chunks. + response = client.get("/regular/c/0/0") + assert response.status_code == 200 + + def test_out_of_bounds_chunk_key_returns_404( + self, store: Store, group_with_arrays: zarr.Group + ) -> None: + """A chunk key that is syntactically valid but references indices beyond + the array's chunk grid should return 404.""" + arr = group_with_arrays["regular"] + assert isinstance(arr, zarr.Array) + arr[:] = np.ones((4, 4)) + + # Put real data at the out-of-grid key, so that a 404 can only come + # from the bounds check -- not from the key merely being absent. + planted = cpu.buffer_prototype.buffer.from_bytes(b"out of grid") + sync(store.set("regular/c/99/99", planted)) + assert sync(store.get("regular/c/99/99", cpu.buffer_prototype)) is not None + + app = node_app(group_with_arrays) + client = TestClient(app) + + # (4,4) array with (2,2) chunks has grid shape (2,2), so c/99/99 is + # syntactically valid but out of bounds. + response = client.get("/regular/c/99/99") + assert response.status_code == 404 + + def test_empty_path_returns_404(self, group_with_arrays: zarr.Group) -> None: + """A request to the root path '/' should return 404 because an empty + string is not a valid zarr key.""" + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestShardedArrayByteRangeReads: + """Byte-range reads against a sharded array served via node_app.""" + + def test_range_read_returns_206(self, group_with_arrays: zarr.Group) -> None: + """A Range header requesting a specific byte range (e.g. bytes=0-7) should + return 206 Partial Content with exactly those bytes.""" + arr = group_with_arrays["sharded"] + assert isinstance(arr, zarr.Array) + arr[:] = np.arange(64, dtype="i4").reshape((8, 8)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + # c/0/0 is the first shard key for an (8,8) array with (4,4) shards. + full_response = client.get("/sharded/c/0/0") + assert full_response.status_code == 200 + full_body = full_response.content + + # Request the first 8 bytes. + range_response = client.get("/sharded/c/0/0", headers={"Range": "bytes=0-7"}) + assert range_response.status_code == 206 + assert range_response.content == full_body[:8] + + def test_suffix_range_read(self, group_with_arrays: zarr.Group) -> None: + """A suffix byte range (e.g. bytes=-4) should return the last N bytes + of the resource with a 206 status.""" + arr = group_with_arrays["sharded"] + assert isinstance(arr, zarr.Array) + arr[:] = np.arange(64, dtype="i4").reshape((8, 8)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + full_response = client.get("/sharded/c/0/0") + full_body = full_response.content + + # Request the last 4 bytes. + range_response = client.get("/sharded/c/0/0", headers={"Range": "bytes=-4"}) + assert range_response.status_code == 206 + assert range_response.content == full_body[-4:] + + def test_offset_range_read(self, group_with_arrays: zarr.Group) -> None: + """An offset byte range (e.g. bytes=4-) should return all bytes from + the given offset to the end, with a 206 status.""" + arr = group_with_arrays["sharded"] + assert isinstance(arr, zarr.Array) + arr[:] = np.arange(64, dtype="i4").reshape((8, 8)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + full_response = client.get("/sharded/c/0/0") + full_body = full_response.content + + # Request everything from byte 4 onward. + range_response = client.get("/sharded/c/0/0", headers={"Range": "bytes=4-"}) + assert range_response.status_code == 206 + assert range_response.content == full_body[4:] + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestUnusableRangeHeadersAreIgnored: + """A Range this server cannot turn into a read is ignored, not refused. + + RFC 9110 §14.2 requires ignoring a Range whose unit is unrecognized and + permits ignoring one that will not parse; either way the answer is 200 + with the full representation. Refusing with 416 would tell a client the + object is unreadable when only the request shape was unsupported -- and + a multi-range request, which is legal to send and which proxies and + download accelerators do send, would take that at face value. + """ + + @pytest.mark.parametrize( + "header", + [ + "bytes=abc-def", + "bytes=-abc", + "bytes=abc-", + "bytes=0-7,10-20", + "chars=0-7", + "bytes=", + "bytes=+0-1", + ], + ) + def test_unusable_range_serves_full_representation(self, store: Store, header: str) -> None: + """Non-numeric bounds, multi-range, a non-'bytes' unit, an empty spec + and a non-canonical byte position all fall back to a plain 200.""" + body = b"some data here" + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(body))) + + client = TestClient(store_app(store), raise_server_exceptions=False) + + response = client.get("/key", headers={"Range": header}) + assert response.status_code == 200 + assert response.content == body + assert "content-range" not in response.headers + + +class TestParseRangeHeader: + """Unit tests for _parse_range_header.""" + + def test_parser_rejects_an_inverted_range(self) -> None: + """Pin the parser itself: on a MemoryStore an unguarded inverted range + happens to return b"" and still yields 416, so the status code alone + cannot tell whether the guard is present.""" + assert _parse_range_header("bytes=5-2") is _RangeVerdict.UNSATISFIABLE + assert _parse_range_header("bytes=0-0") is not _RangeVerdict.UNSATISFIABLE + + def test_valid_range(self) -> None: + """'bytes=0-99' should parse into a RangeByteRequest with start=0 and + end=100 (end is exclusive, so the inclusive HTTP end is incremented).""" + from zarr.abc.store import RangeByteRequest + + result = _parse_range_header("bytes=0-99") + assert result == RangeByteRequest(start=0, end=100) + + def test_valid_suffix(self) -> None: + """'bytes=-50' should parse into a SuffixByteRequest requesting the + last 50 bytes of the resource.""" + from zarr.abc.store import SuffixByteRequest + + result = _parse_range_header("bytes=-50") + assert result == SuffixByteRequest(suffix=50) + + def test_valid_offset(self) -> None: + """'bytes=10-' should parse into an OffsetByteRequest starting at + byte 10 and reading to the end of the resource.""" + from zarr.abc.store import OffsetByteRequest + + result = _parse_range_header("bytes=10-") + assert result == OffsetByteRequest(offset=10) + + def test_non_bytes_unit(self) -> None: + """An unrecognized range unit must be ignored, per RFC 9110 §14.2.""" + assert _parse_range_header("chars=0-7") is _RangeVerdict.IGNORE + + def test_garbage_values(self) -> None: + """Non-numeric bounds are ignored rather than raising a ValueError.""" + assert _parse_range_header("bytes=abc-def") is _RangeVerdict.IGNORE + + def test_multi_range(self) -> None: + """Multi-range requests (e.g. bytes=0-7,10-20) are legal to send; this + server does not build multipart/byteranges, so it serves the whole + representation instead of refusing.""" + assert _parse_range_header("bytes=0-7,10-20") is _RangeVerdict.IGNORE + + def test_empty_spec(self) -> None: + """A Range header with no range specifier after 'bytes=' is ignored.""" + assert _parse_range_header("bytes=") is _RangeVerdict.IGNORE + + def test_non_canonical_byte_position(self) -> None: + """`int` would accept these; RFC 9110 defines a byte position as + 1*DIGIT, so they are not ranges and the header is ignored.""" + assert _parse_range_header("bytes=+0-1") is _RangeVerdict.IGNORE + assert _parse_range_header("bytes= 0-1") is _RangeVerdict.IGNORE + assert _parse_range_header("bytes=0_0-1") is _RangeVerdict.IGNORE + + def test_oversized_start_is_unsatisfiable(self) -> None: + """A first-byte-pos past any possible object names nothing.""" + assert _parse_range_header("bytes=99999999999999999999-") is _RangeVerdict.UNSATISFIABLE + + def test_zero_length_suffix_is_unsatisfiable(self) -> None: + """ "The last zero bytes" names nothing.""" + assert _parse_range_header("bytes=-0") is _RangeVerdict.UNSATISFIABLE + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestWriteViaPut: + """store_app and node_app can be configured to accept PUT writes.""" + + def test_put_writes_to_store(self, store: Store) -> None: + """A PUT request to store_app with PUT enabled should write the + request body into the store at the given key.""" + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + payload = b"hello zarr" + response = client.put("/some/key", content=payload) + assert response.status_code == 204 + + # Verify the data landed in the store. + buf = sync(store.get("some/key", cpu.buffer_prototype)) + assert buf is not None + assert buf.to_bytes() == payload + + def test_put_then_get_roundtrip(self, store: Store) -> None: + """Data written via PUT should be retrievable via a subsequent GET + at the same key.""" + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + payload = b"\x00\x01\x02\x03" + client.put("/data/blob", content=payload) + + response = client.get("/data/blob") + assert response.status_code == 200 + assert response.content == payload + + def test_put_rejected_when_not_configured(self, store: Store) -> None: + """PUT requests should return 405 Method Not Allowed when the server + is created with the default methods (GET only).""" + app = store_app(store) + client = TestClient(app) + + response = client.put("/some/key", content=b"data") + assert response.status_code == 405 + + def test_put_on_node_validates_key(self, store: Store, group_with_arrays: zarr.Group) -> None: + """PUT requests via node_app should be rejected with 404 when the + target key is not a valid zarr key (metadata or chunk).""" + app = node_app(group_with_arrays, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.put("/not_a_zarr_key.bin", content=b"data") + assert response.status_code == 404 + + def test_put_to_valid_chunk_key_succeeds(self, group_with_arrays: zarr.Group) -> None: + """PUT requests via node_app to a valid chunk key should succeed + with 204, and the written data should be retrievable via GET.""" + app = node_app(group_with_arrays, methods={"GET", "PUT"}) + client = TestClient(app) + + payload = b"\x00" * 32 + response = client.put("/regular/c/0/0", content=payload) + assert response.status_code == 204 + + # Confirm it round-trips. + get_response = client.get("/regular/c/0/0") + assert get_response.status_code == 200 + assert get_response.content == payload + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestMethodValidation: + """Only the methods the handler implements may be served.""" + + def test_supported_methods_are_served(self, store: Store) -> None: + """GET, PUT and HEAD each behave as their verb implies.""" + app = store_app(store, methods={"GET", "PUT", "HEAD"}) + client = TestClient(app) + + assert client.put("/zarr.json", content=b'{"a":1}').status_code == 204 + assert client.get("/zarr.json").content == b'{"a":1}' + + # HEAD reports the same status as GET but carries no body. + head = client.head("/zarr.json") + assert head.status_code == 200 + assert head.content == b"" + + def test_empty_method_set_raises(self, store: Store) -> None: + """Asking for no methods must be rejected rather than producing a + server that answers every verb, including writes: Starlette treats a + falsy `methods` on a Route as "match anything".""" + for build in ( + lambda: store_app(store, methods=set()), + lambda: node_app(zarr.open_group(store, mode="a"), methods=set()), + ): + with pytest.raises(ValueError, match="at least one"): + build() + + @pytest.mark.parametrize("method", ["DELETE", "POST", "PATCH", "OPTIONS", "TRACE"]) + def test_unsupported_method_raises(self, store: Store, method: str) -> None: + """A verb the handler cannot implement is rejected when the app is + built, rather than silently answering as if it were a GET.""" + for build in ( + lambda: store_app(store, methods={"GET", method}), # type: ignore[arg-type] + lambda: node_app(zarr.open_group(store, mode="a"), methods={"GET", method}), # type: ignore[arg-type] + ): + with pytest.raises(ValueError, match=method): + build() + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestStoreAppEdgeCases: + """Edge cases for store_app.""" + + def test_get_nonexistent_key_returns_404(self, store: Store) -> None: + """GET for a key that does not exist in the store should return 404.""" + app = store_app(store) + client = TestClient(app) + + response = client.get("/no/such/key") + assert response.status_code == 404 + + def test_empty_path_returns_404(self, store: Store) -> None: + """GET to the root path '/' (empty key) should return 404 because + an empty string is not a valid store key.""" + app = store_app(store) + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeAppDirectArray: + """Serve a single array directly (not through a group).""" + + def test_serve_nested_array_directly(self, store: Store) -> None: + """When node_app is given a nested array (not a group), requests + should use keys relative to that array's path. Metadata and in-bounds + chunks should return 200, and out-of-bounds chunks should return 404.""" + root = zarr.open_group(store, mode="w") + arr = zarr.create_array( + root.store_path / "sub/nested", + shape=(4,), + chunks=(2,), + dtype="f8", + ) + arr[:] = np.arange(4, dtype="f8") + + # Serve the array directly — its prefix is "sub/nested". + app = node_app(arr) + client = TestClient(app) + + # Metadata should be accessible at the array root. + response = client.get("/zarr.json") + assert response.status_code == 200 + + # Chunk keys are relative to the array. + response = client.get("/c/0") + assert response.status_code == 200 + + response = client.get("/c/1") + assert response.status_code == 200 + + # Out of bounds. + response = client.get("/c/99") + assert response.status_code == 404 + + def test_serve_root_array(self, store: Store) -> None: + """When node_app is given an array stored at the root of a store + (empty prefix), metadata and chunk keys should be accessible at + their natural paths.""" + arr = zarr.create_array( + store, + shape=(6,), + chunks=(3,), + dtype="i4", + ) + arr[:] = np.arange(6, dtype="i4") + + # Root-level array has prefix = "". + app = node_app(arr) + client = TestClient(app) + + response = client.get("/zarr.json") + assert response.status_code == 200 + + response = client.get("/c/0") + assert response.status_code == 200 + + response = client.get("/c/1") + assert response.status_code == 200 + + response = client.get("/c/2") + assert response.status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestContentType: + """Responses should have the correct Content-Type.""" + + def test_metadata_has_json_content_type(self, group_with_arrays: zarr.Group) -> None: + """Zarr metadata files (zarr.json) should be served with + Content-Type: application/json.""" + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/zarr.json") + assert response.status_code == 200 + assert response.headers["content-type"] == "application/json" + + def test_chunk_has_octet_stream_content_type(self, group_with_arrays: zarr.Group) -> None: + """Chunk data should be served with Content-Type: application/octet-stream + since it is binary data.""" + arr = group_with_arrays["regular"] + assert isinstance(arr, zarr.Array) + arr[:] = np.ones((4, 4)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/regular/c/0/0") + assert response.status_code == 200 + assert response.headers["content-type"] == "application/octet-stream" + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestCorsMiddleware: + """CORS middleware should add the expected headers.""" + + def test_cors_headers_present(self, store: Store) -> None: + """When cors_options are provided, responses should include the + Access-Control-Allow-Origin header matching the request origin.""" + buf = cpu.buffer_prototype.buffer.from_bytes(b"data") + sync(store.set("key", buf)) + + cors = CorsOptions(allow_origins=["https://example.com"], allow_methods=["GET"]) + app = store_app(store, cors_options=cors) + client = TestClient(app) + + response = client.get("/key", headers={"Origin": "https://example.com"}) + assert response.status_code == 200 + assert response.headers["access-control-allow-origin"] == "https://example.com" + + def test_cors_preflight(self, store: Store) -> None: + """CORS preflight OPTIONS requests should return 200 with the + Access-Control-Allow-Origin header when CORS is configured.""" + cors = CorsOptions(allow_origins=["*"], allow_methods=["GET", "PUT"]) + app = store_app(store, methods={"GET", "PUT"}, cors_options=cors) + client = TestClient(app) + + response = client.options( + "/any/path", + headers={ + "Origin": "https://example.com", + "Access-Control-Request-Method": "PUT", + }, + ) + assert response.status_code == 200 + assert "access-control-allow-origin" in response.headers + + def test_no_cors_headers_without_option(self, store: Store) -> None: + """When no cors_options are provided, responses should not include + any CORS headers, even if the request includes an Origin header.""" + buf = cpu.buffer_prototype.buffer.from_bytes(b"data") + sync(store.set("key", buf)) + + app = store_app(store) + client = TestClient(app) + + response = client.get("/key", headers={"Origin": "https://example.com"}) + assert response.status_code == 200 + assert "access-control-allow-origin" not in response.headers + + +def _metadata_key(zarr_format: ZarrFormat) -> str: + """Return the metadata key for the given zarr format.""" + return "zarr.json" if zarr_format == 3 else ".zarray" + + +def _chunk_key(zarr_format: ZarrFormat, coords: str) -> str: + """Return a chunk key for the given format. + + *coords* is a dot-separated string like ``"0.0"``. For v3 this becomes + ``"c/0/0"``; for v2 it is returned unchanged. + """ + if zarr_format == 3: + return "c/" + coords.replace(".", "/") + return coords + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeAppV2AndV3: + """Test node_app with both v2 and v3 arrays side by side.""" + + def test_metadata_accessible(self, store: Store, zarr_format: ZarrFormat) -> None: + """The format-appropriate metadata key should be served with 200.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + app = node_app(arr) + client = TestClient(app) + + response = client.get(f"/{_metadata_key(zarr_format)}") + assert response.status_code == 200 + + def test_chunk_accessible(self, store: Store, zarr_format: ZarrFormat) -> None: + """An in-bounds chunk key should be served with 200 for both formats.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + arr[:] = np.ones(4) + + app = node_app(arr) + client = TestClient(app) + + response = client.get(f"/{_chunk_key(zarr_format, '0')}") + assert response.status_code == 200 + + def test_out_of_bounds_chunk_returns_404(self, store: Store, zarr_format: ZarrFormat) -> None: + """An out-of-bounds chunk key should return 404 for both formats.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + arr[:] = np.ones(4) + + # Plant data at the out-of-grid key so the 404 must come from the + # bounds check rather than from the key being absent. + key = _chunk_key(zarr_format, "99") + sync(store.set(key, cpu.buffer_prototype.buffer.from_bytes(b"out of grid"))) + assert sync(store.get(key, cpu.buffer_prototype)) is not None + + app = node_app(arr) + client = TestClient(app) + + response = client.get(f"/{key}") + assert response.status_code == 404 + + def test_non_zarr_key_returns_404(self, store: Store, zarr_format: ZarrFormat) -> None: + """A non-zarr key should return 404 regardless of format.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + non_zarr_buf = cpu.buffer_prototype.buffer.from_bytes(b"secret") + sync(store.set("secret.txt", non_zarr_buf)) + + app = node_app(arr) + client = TestClient(app) + + response = client.get("/secret.txt") + assert response.status_code == 404 + + def test_data_roundtrip(self, store: Store, zarr_format: ZarrFormat) -> None: + """Data written to an array should be readable via store_app for + both formats.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + arr[:] = np.arange(4, dtype="f8") + + app = store_app(store) + client = TestClient(app) + + # Metadata should be accessible. + response = client.get(f"/{_metadata_key(zarr_format)}") + assert response.status_code == 200 + + # First chunk should be accessible. + response = client.get(f"/{_chunk_key(zarr_format, '0')}") + assert response.status_code == 200 + assert len(response.content) > 0 + + +class TestPathTraversalProtection: + """store_app and node_app must reject path-traversal attempts before + touching the store, regardless of URL-encoding tricks.""" + + def test_get_traversal_outside_store_root_returns_404(self, tmp_path: Any) -> None: + """A GET for a percent-encoded '../secret.txt' must not escape the + store root and read a file outside it.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + secret = tmp_path / "secret.txt" + secret.write_text("top secret contents") + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.get("/..%2fsecret.txt") + assert response.status_code == 404 + assert b"top secret" not in response.content + + def test_put_traversal_outside_store_root_returns_404(self, tmp_path: Any) -> None: + """A PUT to a percent-encoded '../pwned.txt' must not escape the + store root and write a file outside it.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + pwned = tmp_path / "pwned.txt" + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.put("/..%2fpwned.txt", content=b"pwned") + assert response.status_code == 404 + assert not pwned.exists() + + @pytest.mark.parametrize( + ("encoded_path", "climb_depth"), + [ + ("/..%2fsecret.txt", 1), + ("/%2e%2e/secret.txt", 1), + ("/..%2f..%2fsecret.txt", 2), + ], + ) + def test_encoded_traversal_variants_return_404( + self, tmp_path: Any, encoded_path: str, climb_depth: int + ) -> None: + """Various percent-encoded traversal spellings must all be rejected. + + The store root is nested exactly ``climb_depth`` directories below + ``tmp_path`` and the secret lives at ``tmp_path/secret.txt`` -- the + exact location each traversal's ".." segments resolve to -- so a + case with a missing or deleted guard would actually reach the + secret instead of just returning 404 for an unrelated reason (e.g. + a two-level climb landing on a directory that happens to be empty). + """ + from zarr.storage import LocalStore + + parts = [f"level{i}" for i in range(climb_depth - 1)] + ["store_root"] + root = tmp_path.joinpath(*parts) + root.mkdir(parents=True) + secret = tmp_path / "secret.txt" + secret.write_text("top secret contents") + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.get(encoded_path) + assert response.status_code == 404 + assert b"top secret" not in response.content + + def test_get_absolute_key_bypass_returns_404(self, tmp_path: Any) -> None: + """A percent-encoded leading slash decodes to an ABSOLUTE path param + (e.g. request '/%2fetc%2fhostname' -> path param '/etc/hostname'). + '/etc/hostname'.split('/') -> ['', 'etc', 'hostname'] has no '.' or + '..' segment, so the two-element guard misses it, but LocalStore + resolves an absolute key by discarding its root entirely -- an + arbitrary-file read. The empty leading segment must be rejected.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + secret = tmp_path / "secret_abs.txt" + secret.write_text("top secret absolute contents") + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + # Mirror the exploit: percent-encode every "/" (including the + # leading one) in the absolute secret path as "%2f". + encoded_path = "/" + str(secret).replace("/", "%2f") + + response = client.get(encoded_path) + assert response.status_code == 404 + assert b"top secret absolute" not in response.content + assert secret.read_text() == "top secret absolute contents" + + def test_put_absolute_key_bypass_returns_404(self, tmp_path: Any) -> None: + """Same absolute-key vector as above, but for PUT: a percent-encoded + leading slash must not allow writing a file outside the store root.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + pwned = tmp_path / "pwned_abs.txt" + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + encoded_path = "/" + str(pwned).replace("/", "%2f") + + response = client.put(encoded_path, content=b"pwned") + assert response.status_code == 404 + assert not pwned.exists() + + @pytest.mark.parametrize( + "encoded_path", + [ + "/..%5C..%5Cwin.ini", + "/%5CWindows%5Cwin.ini", + "/C:/Windows/win.ini", + "/C:%5CWindows", + "/%5C%5Chost%5Cshare%5Cx", + ], + ) + def test_backslash_and_drive_traversal_variants_return_404(self, encoded_path: str) -> None: + """Backslash is a path separator on Windows, and a drive-qualified or + root-relative key discards a filesystem store's root entirely on + Windows, even though POSIX only ever treats '/' as a separator. The + guard must reject these purely from the string, before the store is + ever touched -- verified here by making the store raise if called.""" + from unittest.mock import AsyncMock + + from zarr.storage import MemoryStore + + store = MemoryStore() + store.get = AsyncMock(side_effect=AssertionError("store.get should not be called")) # type: ignore[method-assign] + store.set = AsyncMock(side_effect=AssertionError("store.set should not be called")) # type: ignore[method-assign] + + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.get(encoded_path) + assert response.status_code == 404 + + def test_put_backslash_traversal_returns_404(self) -> None: + """A PUT to a backslash-encoded '..\\..\\pwned.txt' must be rejected + before the store is touched, mirroring the GET case above.""" + from unittest.mock import AsyncMock + + from zarr.storage import MemoryStore + + store = MemoryStore() + store.set = AsyncMock(side_effect=AssertionError("store.set should not be called")) # type: ignore[method-assign] + + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.put("/..%5C..%5Cpwned.txt", content=b"pwned") + assert response.status_code == 404 + + +def _get_free_port() -> int: + """Return an unused TCP port on localhost.""" + import socket + + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port: int = s.getsockname()[1] + return port + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestServeBackground: + """Test serve_background with store- and node-scoped apps.""" + + def test_background_server_over_a_store_app(self, store: Store) -> None: + """serve_background over a store app should return a BackgroundServer + that responds to HTTP requests and can be used as a context manager.""" + import httpx + + from zarr_http_server import serve_background + + buf = cpu.buffer_prototype.buffer.from_bytes(b"hello") + sync(store.set("key", buf)) + + port = _get_free_port() + with serve_background(store_app(store), host="127.0.0.1", port=port) as server: + assert server.host == "127.0.0.1" + assert server.port == port + assert server.url == f"http://127.0.0.1:{port}" + + response = httpx.get(f"{server.url}/key") + assert response.status_code == 200 + assert response.content == b"hello" + + def test_background_server_over_a_node_app(self, store: Store) -> None: + """serve_background over a node app should return a BackgroundServer + that responds to HTTP requests and can be used as a context manager.""" + import httpx + + from zarr_http_server import serve_background + + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8") + arr[:] = np.arange(4, dtype="f8") + + port = _get_free_port() + with serve_background(node_app(arr), host="127.0.0.1", port=port) as server: + response = httpx.get(f"{server.url}/zarr.json") + assert response.status_code == 200 + + +class TestStoreFailuresAreNotReportedAsMisses: + """Under the v3 spec an absent chunk is an uninitialized one, and a reader + is right to substitute the array's fill value for it. A 404 therefore + asserts something about the store's contents, and an I/O failure must not + borrow it -- that would have a correct client materialize fill values over + data that exists.""" + + @pytest.mark.skipif(os.geteuid() == 0, reason="root bypasses the permission bits under test") + def test_unreadable_key_is_a_server_error(self, tmp_path: pathlib.Path) -> None: + root = tmp_path / "root" + root.mkdir() + (root / "key").write_bytes(b"real data") + os.chmod(root / "key", 0o000) + + client = TestClient(store_app(LocalStore(str(root))), raise_server_exceptions=False) + try: + assert client.get("/key").status_code >= 500 + finally: + os.chmod(root / "key", 0o600) + + @pytest.mark.skipif(os.geteuid() == 0, reason="root bypasses the permission bits under test") + def test_unwritable_store_is_a_server_error(self, tmp_path: pathlib.Path) -> None: + root = tmp_path / "ro" + root.mkdir() + os.chmod(root, 0o500) + + client = TestClient( + store_app(LocalStore(str(root)), methods={"GET", "PUT"}), + raise_server_exceptions=False, + ) + try: + assert client.put("/key", content=b"data").status_code >= 500 + finally: + os.chmod(root, 0o700) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestShardGridBounds: + """A sharded array's storage grid is its shard grid, not its chunk grid.""" + + def test_out_of_shard_grid_key_returns_404(self, store: Store) -> None: + arr = zarr.create_array(store, shape=(8, 8), chunks=(2, 2), shards=(4, 4), dtype="i4") + arr[:] = np.arange(64, dtype="i4").reshape(8, 8) + + # (8,8) with (4,4) shards has a 2x2 shard grid, so c/3/3 is out of it. + # Plant data there so the 404 must come from the bounds check. + sync(store.set("c/3/3", cpu.buffer_prototype.buffer.from_bytes(b"PLANTED"))) + assert sync(store.get("c/3/3", cpu.buffer_prototype)) is not None + + client = TestClient(node_app(arr)) + assert client.get("/c/0/0").status_code == 200 + assert client.get("/c/3/3").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestWrongArityChunkKeys: + """A chunk key with the wrong number of coordinates is invalid, and must + not reach the grid comparison -- zip(strict=True) would raise there.""" + + @pytest.mark.parametrize("key", ["c/0", "c/0/0/0", "c/0/0/0/0"]) + def test_wrong_arity_returns_404(self, store: Store, key: str) -> None: + arr = zarr.create_array(store, shape=(4, 4), chunks=(2, 2), dtype="f8") + arr[:] = np.ones((4, 4)) + + sync(store.set(key, cpu.buffer_prototype.buffer.from_bytes(b"PLANTED"))) + + client = TestClient(node_app(arr), raise_server_exceptions=False) + assert client.get(f"/{key}").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeNamesContainingAColon: + """A leading `:` is a drive reference to `ntpath`, so the guard rejects + it on every platform to keep it a pure string gate in front of any store. + The documented cost is that such a name is unreachable in the first + segment -- but only there.""" + + def test_colon_named_node_in_a_later_segment_is_served(self, store: Store) -> None: + root = zarr.open_group(store, mode="w") + sub = root.create_group("sub") + sub.create_array("a:b", shape=(2,), chunks=(2,), dtype="f8") + + client = TestClient(node_app(root)) + assert client.get("/sub/a:b/zarr.json").status_code == 200 + + def test_colon_named_node_in_the_first_segment_is_rejected(self, store: Store) -> None: + root = zarr.open_group(store, mode="w") + root.create_array("a:b", shape=(2,), chunks=(2,), dtype="f8") + + client = TestClient(node_app(root)) + assert client.get("/a:b/zarr.json").status_code == 404 + + +class TestChunkedBodyIsCapped: + """A chunked request carries no Content-Length, so the cap has to hold + while the body is being read rather than after it is buffered.""" + + def test_chunked_body_over_cap_is_rejected(self, tmp_path: pathlib.Path) -> None: + store = LocalStore(str(tmp_path / "root")) + client = TestClient( + store_app(store, methods={"GET", "PUT"}, max_body_size=64), + raise_server_exceptions=False, + ) + + def body() -> Iterator[bytes]: + for _ in range(20): + yield b"x" * 32 + + # httpx sends an iterator body with Transfer-Encoding: chunked. + assert client.put("/key", content=body()).status_code == 413 + assert not (tmp_path / "root" / "key").exists() + + +class TestHostileKeysAreNotServerErrors: + """A key the store cannot express is a miss, not a server fault: the + server must never answer 5xx for input a client can choose freely. + + This needs a filesystem-backed store -- a `MemoryStore` accepts any key + as a dict key, so only `LocalStore` surfaces the underlying errors (an + embedded NUL, a name longer than the filesystem allows). + """ + + @pytest.mark.parametrize( + "path", ["/x%00y", "/ok.txt%00", "/" + "a" * 3000, "/" + "b" * 3000 + "/zarr.json"] + ) + def test_unexpressable_key_returns_404_not_500(self, tmp_path: pathlib.Path, path: str) -> None: + store = LocalStore(str(tmp_path / "root")) + client = TestClient(store_app(store, methods={"GET", "PUT"})) + + assert client.get(path).status_code == 404 + assert client.put(path, content=b"x").status_code == 404 + + +class TestGenericStoreFailuresAreNotMisses: + """Only an error that answers about the *name* may become a 404. + + `ENAMETOOLONG` says no such name is expressible, which is an answer about + the key. `EINVAL` is POSIX's catch-all and is reachable on a perfectly + ordinary short key -- a bad seek, an unsupported filesystem feature -- so + reporting it as absence would have a v3 reader write fill values over a + chunk that exists but could not be read. + """ + + @staticmethod + def _store_failing_with(code: int) -> Store: + class Failing(MemoryStore): + async def get(self, key: str, prototype: Any, byte_range: Any = None) -> Any: + raise OSError(code, os.strerror(code)) + + async def set(self, key: str, value: Any) -> None: + raise OSError(code, os.strerror(code)) + + return Failing() + + def test_einval_is_not_reported_as_absent(self) -> None: + """The regression this class exists for.""" + client = TestClient( + store_app(self._store_failing_with(errno.EINVAL), methods={"GET", "PUT"}), + raise_server_exceptions=False, + ) + + assert client.get("/c/0/0").status_code >= 500 + assert client.put("/c/0/0", content=b"data").status_code >= 500 + + def test_enametoolong_is_still_a_miss(self) -> None: + """A name the store cannot express holds nothing, so 404 is honest.""" + client = TestClient( + store_app(self._store_failing_with(errno.ENAMETOOLONG), methods={"GET", "PUT"}), + raise_server_exceptions=False, + ) + + assert client.get("/c/0/0").status_code == 404 + assert client.put("/c/0/0", content=b"data").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestPutBodyLimit: + """`Store.set` takes a whole buffer, so an unbounded body would let one + request size the server's memory use.""" + + def test_body_over_the_limit_is_rejected(self, store: Store) -> None: + client = TestClient(store_app(store, methods={"GET", "PUT"}, max_body_size=64)) + + assert client.put("/key", content=b"x" * 65).status_code == 413 + # Nothing was written. + assert sync(store.get("key", cpu.buffer_prototype)) is None + # A body within the limit still succeeds. + assert client.put("/key", content=b"x" * 64).status_code == 204 + + def test_limit_can_be_lifted(self, store: Store) -> None: + client = TestClient(store_app(store, methods={"GET", "PUT"}, max_body_size=None)) + assert client.put("/key", content=b"x" * 5000).status_code == 204 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestRangeResponseCorrectness: + """A 206 must describe which bytes it carries, and a range that cannot be + satisfied must say so rather than returning an empty 206.""" + + def test_206_carries_content_range(self, store: Store) -> None: + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = TestClient(store_app(store)) + + response = client.get("/key", headers={"Range": "bytes=2-5"}) + assert response.status_code == 206 + assert response.content == b"2345" + assert response.headers["Content-Range"] == "bytes 2-5/*" + + def test_range_beyond_end_is_416(self, store: Store) -> None: + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = TestClient(store_app(store)) + + assert client.get("/key", headers={"Range": "bytes=1000-2000"}).status_code == 416 + + def test_inverted_range_is_416(self, store: Store) -> None: + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = TestClient(store_app(store)) + + assert client.get("/key", headers={"Range": "bytes=5-2"}).status_code == 416 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestZeroDimensionalArray: + """A 0-d array has exactly one chunk, spelled `0` in v2 and `c` in v3.""" + + @pytest.mark.parametrize("zarr_format", [2, 3]) + def test_sole_chunk_is_served(self, store: Store, zarr_format: ZarrFormat) -> None: + arr = zarr.create_array(store, shape=(), dtype="i4", zarr_format=zarr_format) + arr[...] = 7 + + client = TestClient(node_app(arr)) + chunk_key = "0" if zarr_format == 2 else "c" + + assert client.get(f"/{chunk_key}").status_code == 200 + # A 1-d coordinate is not valid for a 0-d grid. + assert client.get("/0/0").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestGroupAndArrayMetadataKeysAreDistinct: + """A v2 group owns `.zgroup`; `.zarray` belongs to arrays, and vice versa.""" + + def test_node_does_not_claim_the_other_kind_of_metadata(self, store: Store) -> None: + root = zarr.open_group(store, mode="w", zarr_format=2) + arr = root.create_array("a", shape=(2,), chunks=(2,), dtype="f8") + + # Plant both documents so a 404 reflects the key set, not absence. + sync(store.set(".zarray", cpu.buffer_prototype.buffer.from_bytes(b"{}"))) + sync(store.set("a/.zgroup", cpu.buffer_prototype.buffer.from_bytes(b"{}"))) + + assert TestClient(node_app(root)).get("/.zarray").status_code == 404 + assert TestClient(node_app(arr)).get("/.zgroup").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestBackgroundServerReportsBoundPort: + """`port=0` asks the OS for a free port, so the server must report the + port it actually bound rather than the zero it was asked for.""" + + def test_port_zero_reports_the_bound_port(self, store: Store) -> None: + import httpx + + from zarr_http_server import serve_background + + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"hello"))) + + with serve_background(store_app(store), host="127.0.0.1", port=0) as server: + assert server.port != 0 + assert server.url == f"http://127.0.0.1:{server.port}" + # The reported URL is the one that actually serves the data. + assert httpx.get(f"{server.url}/key").content == b"hello" + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestUnopenableChildIsAnError: + """A child that cannot be *judged* must not be reported as absent. + + 404 is a claim about the store's contents, and under the v3 spec an + absent chunk is an uninitialized one -- so a correct reader answers 404 + by silently substituting the array's fill value. Returning it for a child + whose metadata could not be read would materialize zeros over data that + exists. Only a genuinely missing member is a 404; corrupt metadata, an + I/O error, or a codec this process lacks all surface as 5xx. + """ + + def test_child_with_unparseable_metadata_is_not_reported_as_missing(self, store: Store) -> None: + """A corrupt child metadata document must not yield 404.""" + root = zarr.open_group(store, mode="w") + root.create_array("good", shape=(2,), chunks=(2,), dtype="f8") + sync(store.set("junk/zarr.json", cpu.buffer_prototype.buffer.from_bytes(b"not json"))) + + client = TestClient(node_app(root), raise_server_exceptions=False) + + assert client.get("/good/zarr.json").status_code == 200 + assert client.get("/junk/zarr.json").status_code >= 500 + assert client.get("/junk/c/0").status_code >= 500 + + def test_absent_child_is_reported_as_missing(self, store: Store) -> None: + """A member that simply is not there is still a plain 404.""" + root = zarr.open_group(store, mode="w") + root.create_array("good", shape=(2,), chunks=(2,), dtype="f8") + + client = TestClient(node_app(root), raise_server_exceptions=False) + + assert client.get("/nope/zarr.json").status_code == 404 + assert client.get("/junk/c/0").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestReadBackWithZarrClient: + """The round-trip the README leads with: serve an array, then open it + with a zarr client over HTTP. + + This needs an HTTP-capable fsspec, which is a client-side concern that + `zarr-http-server` deliberately does not depend on -- it lives in the `docs` + dependency group, alongside the other deps the README examples need. + """ + + def test_served_array_reads_back_identically(self, store: Store) -> None: + """`zarr.open_array(server.url)` should return the same data that was + served, so the README's headline example stays true.""" + pytest.importorskip("fsspec") + pytest.importorskip("aiohttp") + + from zarr_http_server import serve_background + + expected = np.arange(100, dtype="uint8").reshape(10, 10) + arr = zarr.create_array(store, data=expected, chunks=(5, 5), write_data=True) + + port = _get_free_port() + with serve_background(node_app(arr), host="127.0.0.1", port=port) as server: + remote = zarr.open_array(server.url, mode="r") + np.testing.assert_array_equal(remote[:], expected) + + +class TestBackgroundServerBoundedShutdown: + """BackgroundServer.shutdown() must not hang forever on a slow or stuck + in-flight request.""" + + def test_shutdown_returns_promptly_with_slow_inflight_request(self) -> None: + """A request that takes far longer than shutdown_timeout must not + prevent shutdown() from returning within roughly shutdown_timeout, + via uvicorn's force_exit rather than an unbounded thread join.""" + import asyncio + import threading + import time + + import httpx + from starlette.applications import Starlette + from starlette.responses import Response + from starlette.routing import Route + + async def slow(request: Any) -> Response: + # Sleeps far longer than shutdown_timeout below, so a correct + # implementation must force the connection closed rather than + # wait for this to finish. + await asyncio.sleep(SLOW_HANDLER_SECONDS) + return Response(status_code=204) + + app = Starlette(routes=[Route("/slow", slow, methods=["GET"])]) + port = _get_free_port() + server = serve_background( + app, host="127.0.0.1", port=port, shutdown_timeout=SHUTDOWN_TIMEOUT + ) + assert server is not None + + request_errors: list[BaseException] = [] + + def make_slow_request() -> None: + try: + httpx.get(f"http://127.0.0.1:{port}/slow", timeout=10) + except Exception as exc: # noqa: BLE001 -- connection drop when the server force-closes is expected + request_errors.append(exc) + + request_thread = threading.Thread(target=make_slow_request, daemon=True) + request_thread.start() + time.sleep(0.2) # give the request time to actually start + + start = time.monotonic() + server.shutdown() + elapsed = time.monotonic() - start + + # The property is that shutdown is *bounded*, not that it hits a + # particular wall-clock number. Derive the bound from the timeouts + # that produce it rather than hard-coding one: shutdown() waits + # `shutdown_timeout + _SHUTDOWN_JOIN_MARGIN` for a graceful stop, then + # `shutdown_timeout` more after force_exit. A literal here silently + # loses its headroom whenever one of those constants changes -- which + # is what happened when the margin was introduced. + bound = (SHUTDOWN_TIMEOUT + _SHUTDOWN_JOIN_MARGIN) + SHUTDOWN_TIMEOUT + 1.0 + assert elapsed < bound, f"shutdown() took {elapsed:.2f}s, expected under {bound:.1f}s" + # ...and the point of it all: far less than the handler's own sleep, + # which an unbounded join would have waited out in full. + assert elapsed < SLOW_HANDLER_SECONDS + + request_thread.join(timeout=10) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestCorsOptionsCoverTheMiddleware: + """`CorsOptions` exposes every `CORSMiddleware` parameter, with our own + defaults only for the two the server knows about.""" + + _ORIGIN = "https://viewer.example" + + def _client(self, store: Store, cors: CorsOptions) -> TestClient: + return TestClient(store_app(store, methods={"GET"}, cors_options=cors)) + + def test_ranged_response_is_readable_cross_origin(self, store: Store) -> None: + """`Content-Range` is not CORS-safelisted, so without `expose_headers` + a browser reads the bytes but cannot learn which bytes it got.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = self._client(store, {"allow_origins": [self._ORIGIN], "allow_methods": ["GET"]}) + + response = client.get("/k", headers={"Origin": self._ORIGIN, "Range": "bytes=0-3"}) + + assert response.status_code == 206 + assert response.headers["access-control-expose-headers"] == "Content-Range" + + def test_range_survives_a_preflight(self, store: Store) -> None: + """A preflight naming `Range` must be allowed, not answered 400.""" + client = self._client(store, {"allow_origins": [self._ORIGIN], "allow_methods": ["GET"]}) + + preflight = client.options( + "/k", + headers={ + "Origin": self._ORIGIN, + "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": "range", + }, + ) + + assert preflight.status_code == 200 + assert "Range" in preflight.headers["access-control-allow-headers"] + + def test_caller_value_replaces_the_default(self, store: Store) -> None: + """Our defaults apply only to absent keys; a supplied key wins outright + so `expose_headers: []` means "expose nothing", not "expose ours".""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + base: CorsOptions = {"allow_origins": [self._ORIGIN], "allow_methods": ["GET"]} + + empty = self._client(store, {**base, "expose_headers": []}) + assert ( + "access-control-expose-headers" + not in empty.get("/k", headers={"Origin": self._ORIGIN}).headers + ) + + custom = self._client(store, {**base, "expose_headers": ["X-Custom"]}) + assert ( + custom.get("/k", headers={"Origin": self._ORIGIN}).headers[ + "access-control-expose-headers" + ] + == "X-Custom" + ) + + def test_parameters_beyond_the_original_two_are_reachable(self, store: Store) -> None: + """The regression this class exists for: `CorsOptions` used to carry + only `allow_origins` and `allow_methods`, sealing the rest away.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + client = self._client( + store, + { + "allow_origin_regex": r"https://.*\.example", + "allow_credentials": True, + "max_age": 30, + }, + ) + origin = "https://sub.example" + + response = client.get("/k", headers={"Origin": origin}) + assert response.headers["access-control-allow-origin"] == origin + assert response.headers["access-control-allow-credentials"] == "true" + + preflight = client.options( + "/k", headers={"Origin": origin, "Access-Control-Request-Method": "GET"} + ) + assert preflight.headers["access-control-max-age"] == "30" + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestUvicornOptionsAreNotSealedOff: + """`uvicorn.Config` takes ~50 parameters; naming four of them and dropping + the rest would put TLS, proxy headers, `root_path` and log level out of + reach entirely.""" + + def test_options_reach_uvicorn_config(self, store: Store) -> None: + """A key this signature does not name still lands on the Config.""" + from zarr_http_server import serve_background + + server = serve_background( + store_app(store), + host="127.0.0.1", + port=0, + uvicorn_options={"root_path": "/api", "log_level": "warning"}, + ) + assert server is not None + try: + config = server._server.config + assert config.root_path == "/api" + assert config.log_level == "warning" + # Ours still apply where the caller did not override them. + assert config.timeout_graceful_shutdown == 5 + finally: + server.shutdown() + + def test_caller_options_win_over_ours(self, store: Store) -> None: + """The merge order is ours-then-theirs, so a caller can override even + an option this signature sets itself.""" + from zarr_http_server import serve_background + + server = serve_background( + store_app(store), + host="127.0.0.1", + port=0, + shutdown_timeout=5, + uvicorn_options={"timeout_graceful_shutdown": 11}, + ) + assert server is not None + try: + assert server._server.config.timeout_graceful_shutdown == 11 + finally: + server.shutdown() + + @pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="needs unix domain sockets") + def test_non_tcp_bind_reports_no_url(self, store: Store, tmp_path: pathlib.Path) -> None: + """A unix-socket bind has no host and port, so `url` must say so rather + than naming an address nothing is listening on.""" + import httpx + + from zarr_http_server import serve_background + + sock = str(tmp_path / "s.sock") + server = serve_background(store_app(store), uvicorn_options={"uds": sock}) + assert server is not None + try: + assert server.url is None + assert server.host is None + assert server.port is None + # ...and it really is serving, just not over TCP. + with httpx.Client(transport=httpx.HTTPTransport(uds=sock)) as client: + response = client.get("http://localhost/zarr.json", timeout=10) + assert response.status_code in (200, 404) + finally: + server.shutdown() + + +class TestHeadDoesNotTransferTheBody: + """A HEAD body is discarded at the wire, so building one is pure waste.""" + + def test_head_does_not_read_the_value(self, tmp_path: pathlib.Path) -> None: + """The regression this class exists for: HEAD used to fall through to + the GET handler and pull the whole object to report its length.""" + read = {"bytes": 0} + + class CountingLocal(LocalStore): + async def get(self, key: str, prototype: Any, byte_range: Any = None) -> Any: + buf = await super().get(key, prototype, byte_range) + if buf is not None: + read["bytes"] += len(buf) + return buf + + store = CountingLocal(str(tmp_path / "root")) + payload = b"x" * 100_000 + sync(store.set("big", cpu.buffer_prototype.buffer.from_bytes(payload))) + client = TestClient(store_app(store)) + + read["bytes"] = 0 + response = client.head("/big") + + assert response.status_code == 200 + assert response.headers["content-length"] == str(len(payload)) + assert read["bytes"] == 0, "HEAD read the value to report its length" + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_head_of_a_missing_key_is_404(self, store: Store) -> None: + client = TestClient(store_app(store)) + assert client.head("/nope").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestMetadataContentType: + """Metadata documents are JSON in every zarr format, not just v3.""" + + @pytest.mark.parametrize( + ("zarr_format", "key"), [(3, "zarr.json"), (2, ".zarray"), (2, ".zattrs")] + ) + def test_metadata_is_served_as_json( + self, store: Store, zarr_format: ZarrFormat, key: str + ) -> None: + zarr.create_array( + store, name="a", shape=(4,), chunks=(2,), dtype="i4", zarr_format=zarr_format + ) + sync(store.set(f"a/{key}", cpu.buffer_prototype.buffer.from_bytes(b"{}"))) + + response = TestClient(store_app(store)).get(f"/a/{key}") + + assert response.status_code == 200 + assert response.headers["content-type"].startswith("application/json") + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestCorsAllowMethodsMatchTheRoute: + """Advertising a method the route rejects is a promise the server cannot + keep: the browser caches the preflight and every later call 405s.""" + + def test_wildcard_expands_to_what_is_served(self, store: Store) -> None: + """`"*"` is the idiomatic "everything this app does", so it expands to + exactly that rather than to every verb Starlette knows.""" + app = store_app( + store, methods={"GET"}, cors_options={"allow_origins": ["*"], "allow_methods": ["*"]} + ) + + preflight = TestClient(app).options( + "/k", headers={"Origin": "https://e.test", "Access-Control-Request-Method": "GET"} + ) + + advertised = preflight.headers["access-control-allow-methods"] + assert set(advertised.replace(" ", "").split(",")) == {"GET", "HEAD"} + + def test_advertising_an_unserved_method_is_rejected(self, store: Store) -> None: + with pytest.raises(ValueError, match="does not serve"): + store_app( + store, + methods={"GET"}, + cors_options={"allow_origins": ["*"], "allow_methods": ["GET", "DELETE"]}, + ) + + def test_head_counts_as_served_when_get_is(self, store: Store) -> None: + """Starlette routes HEAD wherever GET goes, so naming it is not an error.""" + store_app( + store, + methods={"GET"}, + cors_options={"allow_origins": ["*"], "allow_methods": ["GET", "HEAD"]}, + ) + + def test_absent_allow_methods_is_left_alone(self, store: Store) -> None: + """Starlette's GET-only default stands; widening it to everything + served would newly advertise PUT on a write-enabled app.""" + app = store_app(store, methods={"GET", "PUT"}, cors_options={"allow_origins": ["*"]}) + + preflight = TestClient(app).options( + "/k", headers={"Origin": "https://e.test", "Access-Control-Request-Method": "GET"} + ) + + assert "PUT" not in preflight.headers["access-control-allow-methods"] + + +class TestReadOnlyServing: + """The guarantees a read-only deployment rests on. + + Two independent layers: `methods` decides what the route answers, and the + store decides whether a write could succeed at all. The second is the one + that survives a misconfiguration of the first, so both are pinned here. + """ + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + @pytest.mark.parametrize("method", ["PUT", "POST", "DELETE", "PATCH"]) + def test_default_app_refuses_every_mutating_method(self, store: Store, method: str) -> None: + """The default is read-only: no argument is needed to get there, and + nothing a client sends can write.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + before = sync(store.get("k", cpu.buffer_prototype)).to_bytes() + client = TestClient(store_app(store), raise_server_exceptions=False) + + response = client.request(method, "/k", content=b"overwritten") + + assert response.status_code == 405 + assert sync(store.get("k", cpu.buffer_prototype)).to_bytes() == before + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_post_can_never_be_enabled(self, store: Store) -> None: + """POST is not merely unrouted, it is unconfigurable: there is no + handler behavior for it, so asking is an error rather than a no-op.""" + with pytest.raises(ValueError, match="Unsupported HTTP method"): + store_app(store, methods={"GET", "POST"}) # type: ignore[arg-type] + + def test_read_only_store_refuses_writes_independently_of_methods( + self, tmp_path: pathlib.Path + ) -> None: + """The layer that survives getting `methods` wrong. + + Constructed through the private builder because the public entry + points now reject this combination outright; the handler check stays + as the backstop for a store whose `read_only` is not fixed. + """ + from zarr_http_server._serve import _make_starlette_app + + writable = LocalStore(str(tmp_path / "root")) + sync(writable.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + + app = _make_starlette_app(methods={"GET", "PUT"}) + app.state.store = writable.with_read_only(True) + app.state.node = None + app.state.prefix = "" + app.state.max_body_size = None + + response = TestClient(app, raise_server_exceptions=False).put("/k", content=b"x") + + assert response.status_code == 403 + assert sync(writable.get("k", cpu.buffer_prototype)).to_bytes() == b"data" + + def test_put_on_a_read_only_store_is_rejected_at_construction( + self, tmp_path: pathlib.Path + ) -> None: + """A write that could never succeed is a configuration error, not a + runtime 403 delivered to whoever happens to try first.""" + store = LocalStore(str(tmp_path / "root")).with_read_only(True) + + with pytest.raises(ValueError, match="store is read-only"): + store_app(store, methods={"GET", "PUT"}) + + def test_read_only_node_is_rejected_at_construction(self, tmp_path: pathlib.Path) -> None: + """The same check applies to a node, whose store it inherits.""" + store = LocalStore(str(tmp_path / "root")) + zarr.create_array(store, shape=(4,), chunks=(2,), dtype="i4", compressors=None) + read_only_array = zarr.open_array(store, mode="r") + + with pytest.raises(ValueError, match="store is read-only"): + node_app(read_only_array, methods={"GET", "PUT"}) + + +class TestMethodSetConstants: + """Named method sets let a call site state its intent, and make writable + deployments findable: every writable app must name one.""" + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_read_only_constant_matches_the_default(self, store: Store) -> None: + """Passing it explicitly and omitting `methods` are the same server, so + saying so out loud costs nothing.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + + default = TestClient(store_app(store), raise_server_exceptions=False) + named = TestClient( + store_app(store, methods=READ_ONLY_HTTP_METHODS), raise_server_exceptions=False + ) + + for method in ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]: + assert default.request(method, "/k").status_code == ( + named.request(method, "/k").status_code + ) + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + @pytest.mark.parametrize("method", ["PUT", "POST", "DELETE", "PATCH"]) + def test_read_only_constant_refuses_writes(self, store: Store, method: str) -> None: + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + client = TestClient( + store_app(store, methods=READ_ONLY_HTTP_METHODS), raise_server_exceptions=False + ) + + assert client.request(method, "/k", content=b"x").status_code == 405 + assert sync(store.get("k", cpu.buffer_prototype)).to_bytes() == b"data" + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_read_write_constant_permits_exactly_put(self, store: Store) -> None: + """It grants writes -- and still not POST, which has no handler.""" + client = TestClient( + store_app(store, methods=READ_WRITE_HTTP_METHODS), raise_server_exceptions=False + ) + + assert client.put("/k", content=b"data").status_code == 204 + assert client.post("/k", content=b"data").status_code == 405 + assert sync(store.get("k", cpu.buffer_prototype)).to_bytes() == b"data" + + def test_constants_cannot_be_mutated_by_a_caller(self) -> None: + """Frozen, so one caller cannot widen the default for every other.""" + assert isinstance(READ_ONLY_HTTP_METHODS, frozenset) + assert isinstance(READ_WRITE_HTTP_METHODS, frozenset) + assert "PUT" not in READ_ONLY_HTTP_METHODS + + def test_constants_match_the_types_they_model(self) -> None: + """The sets are derived from the Literals, so they cannot disagree + about what this server serves. Pinning the contents here makes + widening either type a deliberate, visible edit.""" + assert frozenset(get_args(ReadOnlyHTTPMethod)) == READ_ONLY_HTTP_METHODS + assert set(READ_ONLY_HTTP_METHODS) == {"GET", "HEAD"} + assert set(READ_WRITE_HTTP_METHODS) == {"GET", "HEAD", "PUT"} + # Read-only is a strict subset: the only difference is the write verb. + assert READ_ONLY_HTTP_METHODS < READ_WRITE_HTTP_METHODS + assert {"PUT"} == READ_WRITE_HTTP_METHODS - READ_ONLY_HTTP_METHODS + + +class TestServeAnyApp: + """`serve` runs whatever ASGI app it is handed, which is what makes + several nodes on one port possible.""" + + @staticmethod + def _two_mounted_arrays() -> tuple[Starlette, bytes, bytes]: + """Two arrays in *separate* stores, so no common parent exists and + mounting is the only way to serve both from one server.""" + first, second = MemoryStore(), MemoryStore() + one = zarr.create_array(first, shape=(4,), chunks=(2,), dtype="i4", compressors=None) + other = zarr.create_array(second, shape=(4,), chunks=(2,), dtype="i4", compressors=None) + one[:] = 7 + other[:] = 9 + + app = Starlette( + routes=[Mount("/first", app=node_app(one)), Mount("/second", app=node_app(other))] + ) + return app, np.full(2, 7, dtype="i4").tobytes(), np.full(2, 9, dtype="i4").tobytes() + + def test_mounted_apps_each_serve_their_own_node(self) -> None: + app, first_chunk, second_chunk = self._two_mounted_arrays() + client = TestClient(app, raise_server_exceptions=False) + + assert client.get("/first/zarr.json").status_code == 200 + assert client.get("/second/zarr.json").status_code == 200 + assert client.get("/first/c/0").content == first_chunk + assert client.get("/second/c/0").content == second_chunk + + @pytest.mark.parametrize( + "path", + [ + "/first/%2e%2e/second/zarr.json", + "/first/..%2f..%2fsecond/zarr.json", + "/first/%2e%2e%2fsecond/c/0", + "/first/%2fsecond/zarr.json", + ], + ) + def test_one_mount_cannot_reach_another(self, path: str) -> None: + """Per-node validation runs inside each mount, so composing apps does + not widen what any of them serves.""" + app, _, _ = self._two_mounted_arrays() + + assert TestClient(app, raise_server_exceptions=False).get(path).status_code == 404 + + def test_serve_runs_a_composed_app_in_the_background(self) -> None: + """The gap `serve` closes: a composed app previously had no way to use + the background-server ergonomics, only a blocking `uvicorn.run`.""" + import httpx + + app, first_chunk, second_chunk = self._two_mounted_arrays() + + server = serve_background(app, host="127.0.0.1", port=0) + try: + assert server.url is not None + assert httpx.get(f"{server.url}/first/c/0", timeout=30).content == first_chunk + assert httpx.get(f"{server.url}/second/c/0", timeout=30).content == second_chunk + finally: + server.shutdown() + + +class TestPortSelection: + """`port="auto"` prefers a predictable port but never fails over one. + + An explicit port means the opposite -- bind exactly that or fail -- because + a caller who names one usually has something else expecting the server + there, and silently moving would break it while looking healthy. + """ + + @staticmethod + def _free_port() -> int: + """A port that was free a moment ago. Only ever used as the *preferred* + port, never bound afterwards, so the usual bind-then-close race does + not apply: if something takes it, that is the case under test.""" + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + def test_preferred_port_is_used_when_free(self) -> None: + preferred = self._free_port() + + sock = _bind_preferred_or_free("127.0.0.1", preferred) + try: + assert sock.getsockname()[1] == preferred + finally: + sock.close() + + def test_falls_back_when_the_preferred_port_is_taken(self) -> None: + with socket.socket() as squatter: + squatter.bind(("127.0.0.1", 0)) + squatter.listen() + taken = int(squatter.getsockname()[1]) + + sock = _bind_preferred_or_free("127.0.0.1", taken) + try: + assert sock.getsockname()[1] != taken + finally: + sock.close() + + def test_address_family_follows_the_host(self) -> None: + """Hard-coding AF_INET would bind the wrong family for an IPv6 host.""" + try: + sock = _bind_preferred_or_free("::1", 0) + except OSError: # pragma: no cover - depends on the host's networking + pytest.skip("no IPv6 loopback available") + try: + assert sock.family == socket.AF_INET6 + finally: + sock.close() + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_auto_produces_a_working_server(self, store: Store) -> None: + """Whichever port it lands on, `url` names it and the server answers.""" + import httpx + + server = serve_background(store_app(store)) + try: + assert server.url is not None + assert server.port is not None + assert httpx.get(f"{server.url}/nope", timeout=30).status_code == 404 + finally: + server.shutdown() + + # uvicorn answers a failed bind with `sys.exit` on its own thread, which + # pytest reports as an unhandled thread exception -- and this package turns + # warnings into errors. That exit is exactly what the RuntimeError below + # reports to the caller, so it is expected here rather than a defect. + @pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_an_explicit_port_that_is_taken_fails(self, store: Store) -> None: + """The regression this class exists for: `auto` must not leak into the + explicit case, where a collision has to be loud.""" + with socket.socket() as squatter: + squatter.bind(("127.0.0.1", 0)) + squatter.listen() + taken = int(squatter.getsockname()[1]) + + with pytest.raises(RuntimeError, match="may already be in use"): + serve_background(store_app(store), port=taken) + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_port_zero_still_means_any_free_port(self, store: Store) -> None: + """`0` keeps its OS meaning rather than being folded into `auto`.""" + server = serve_background(store_app(store), port=0) + try: + assert server.port not in (0, None) + finally: + server.shutdown() diff --git a/packages/zarr-http-server/uv.lock b/packages/zarr-http-server/uv.lock new file mode 100644 index 0000000000..946da90503 --- /dev/null +++ b/packages/zarr-http-server/uv.lock @@ -0,0 +1,2212 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/d9/22ce5786ac0c1653ae8b6c23bded02c1686d11f0dbb45b31ce128e0df985/aiohttp-3.14.3.tar.gz", hash = "sha256:9491196535a88924a60afd5b5f434b5b203b6cc616250878dbdb223a8f7844bc", size = 7971213, upload-time = "2026-07-23T01:57:27.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/d4/eb96299230e20acf2efae207cb8d69051f1f68e357e5ea5e479bf6fb097a/aiohttp-3.14.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:39aded8c7f3b935b54aab1d8d73c70ec0ee2d3ec3b943e0e86611bc150ba47f5", size = 754690, upload-time = "2026-07-23T01:53:47.332Z" }, + { url = "https://files.pythonhosted.org/packages/88/11/e7a70a209eb9a067c0d3212b518a0134e3484f5178c7533878b6b514d469/aiohttp-3.14.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5bcb6ff3fdab1258a192679ff1a05d44f59626430aa05cd1a9d2447423599228", size = 509484, upload-time = "2026-07-23T01:53:51.159Z" }, + { url = "https://files.pythonhosted.org/packages/30/07/4bbc222cc8dbe31d4c3e8a5baad2286e4d42026ac0c570027b89afce6344/aiohttp-3.14.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:617105e2c3018ee38d0c8ce5ee3c84f621a6d8b9f723202aacaff28449ca91ee", size = 511949, upload-time = "2026-07-23T01:53:55.083Z" }, + { url = "https://files.pythonhosted.org/packages/54/b9/42e74c46b7b7c794b995bbc1f573fb48950c38b19d8600c62a6804ee2d67/aiohttp-3.14.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f631fe87a6f30df5fbe6d79640b25e4cffb38c31c7fb6f10871517b84b0f8c1a", size = 1765282, upload-time = "2026-07-23T01:53:59.662Z" }, + { url = "https://files.pythonhosted.org/packages/6b/ed/62bc4d74363ad346d518e0720363a949f63e2e23439a79eb5813d4d29bb3/aiohttp-3.14.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a94dbaae5ae27bd849c93570669bff91e0510f33a80805738e3de72a7be0447b", size = 1741511, upload-time = "2026-07-23T01:54:04.063Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9f/181e8a8bc79e47d13c7fc4540bd7a3b729d9505609c61f392a8dd2fbfe55/aiohttp-3.14.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8f2f1c4c032c7cedd7d8da6f54c97b70266c6570c3108d3fdffee7188bb70529", size = 1810680, upload-time = "2026-07-23T01:54:09.882Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9a/dec94d6ad694552fe3424e3f1928d7a606a5d9d9433a04e7ecdd9d38ae7f/aiohttp-3.14.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ea05e1f97ceea523942d9b2a7d7c0359d781d683d6b043f5943a602b14da4787", size = 1905646, upload-time = "2026-07-23T01:54:13.475Z" }, + { url = "https://files.pythonhosted.org/packages/52/b7/7cd31f29d6055bd711ae6e669367fba6f5ae9de463910a793e30556a8db7/aiohttp-3.14.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:543906c127fb1d929b95076db19b83fa2d46751006ff1e23b093aa5ac4d8db42", size = 1792122, upload-time = "2026-07-23T01:54:15.752Z" }, + { url = "https://files.pythonhosted.org/packages/66/73/10b1ef93afa61f4963c746257b70ced619cf31a4798671de5fdb2608501d/aiohttp-3.14.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0a5ff2dfbb9ce645fa5b8ef3e02c6c0b9cc3f6030ff863d0c51fffc50cb5541b", size = 1591127, upload-time = "2026-07-23T01:54:19.489Z" }, + { url = "https://files.pythonhosted.org/packages/49/ed/3b203fa6de1b338c14acdc06bf6ca9b043b7944f005966958c2ced932cde/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:041badb8f84396357c4d3ad26de6afd7a32b112f43d3c63045c0c8278cfd2043", size = 1725210, upload-time = "2026-07-23T01:54:24.129Z" }, + { url = "https://files.pythonhosted.org/packages/28/b7/1c2aab8c706436dcc28598452488ac9cd7c409da815237c28c27d58993e6/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:530125ee1163c4219af35dc3aa1206e541e7b31b6efc1a3f93b70a136f65d427", size = 1764848, upload-time = "2026-07-23T01:54:27.973Z" }, + { url = "https://files.pythonhosted.org/packages/54/50/94c28f08b131c4bf10984ea2c7a536c9920608bb2d6e7f95642c30cc87b7/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c8653fd547c93a61aadc612007790f5555cdd18946fa48cf45e26d8ea4ea473d", size = 1777102, upload-time = "2026-07-23T01:54:31.775Z" }, + { url = "https://files.pythonhosted.org/packages/13/d4/e7d09ba7d345fb2d74440fd2fa033c5e079fac05552927705986f41a364f/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:89176250f686cb9853c0fb7ead90e639e915b84a6f43eedc2a4e7ec21f1037f0", size = 1580205, upload-time = "2026-07-23T01:54:34.518Z" }, + { url = "https://files.pythonhosted.org/packages/a3/84/072a91d68e1e1eb587985b54baab94221277f877e8ef274fc213a0ceae28/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3a26434dafe408229ff3403458ca58de24fb51936504decac49ce6755f77e59d", size = 1797219, upload-time = "2026-07-23T01:54:36.995Z" }, + { url = "https://files.pythonhosted.org/packages/e0/eb/aad34e897e668424d6e995da5dff8a4a09af93363d3392488772957a63aa/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d1558173930a5a8d3069cee5c92fc91c87c4dbcb099debbb3622053717145a19", size = 1768629, upload-time = "2026-07-23T01:54:40.103Z" }, + { url = "https://files.pythonhosted.org/packages/b6/2b/6bb88ddba0fecd9122aa3ebcad25996cf6c083a4a7040dbb3a4f97972af6/aiohttp-3.14.3-cp312-cp312-win32.whl", hash = "sha256:16100ad3ab8d649fdfbee87602d9d2dcdca9df0b9eda8a1b5fdc0d41f96da559", size = 451481, upload-time = "2026-07-23T01:54:42.547Z" }, + { url = "https://files.pythonhosted.org/packages/76/9b/f2f8f108da17ecef2cc3efc424e8b7ad3782b1a8360f7b8eae8ced84f6ea/aiohttp-3.14.3-cp312-cp312-win_amd64.whl", hash = "sha256:33a2d7c28d33797a2e99923dffa63f83d908a19b6bf26cfe80fa790aa5e1a75a", size = 476845, upload-time = "2026-07-23T01:54:44.853Z" }, + { url = "https://files.pythonhosted.org/packages/3e/44/28dac80a8941b604f4da10ce21097614ca1bf905ce93dca28d8d7de9c1e7/aiohttp-3.14.3-cp312-cp312-win_arm64.whl", hash = "sha256:362a3fd481769cac1a824514bcd86fda51c65e8fe6e051099e008fddde6db17c", size = 448050, upload-time = "2026-07-23T01:54:47.087Z" }, + { url = "https://files.pythonhosted.org/packages/57/be/5afd201cc0ab139029aadb75392efe85a293403d9dd3a3226161c21ce00c/aiohttp-3.14.3-cp313-cp313-android_21_arm64_v8a.whl", hash = "sha256:2e9878ae68e4a5f1c0abe4dd497dbc3d51946f5837b56759e2a02e78fa90ef86", size = 506269, upload-time = "2026-07-23T01:54:49.075Z" }, + { url = "https://files.pythonhosted.org/packages/22/09/dec8189d62b45ade009f6792a2264b942a90cb88aeaf181239933cd72c3c/aiohttp-3.14.3-cp313-cp313-android_21_x86_64.whl", hash = "sha256:f3d2669fe7dec7fc359ecdb5984b29b50d85d5d00f8c1cb61de4f4a24ee42627", size = 515166, upload-time = "2026-07-23T01:54:51.894Z" }, + { url = "https://files.pythonhosted.org/packages/28/24/2854869d29ed8a8b19d74f9ec6629515f7e04d02dd329d9d179201e58e47/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:cc7cb243a68167172f48c1fd43cee91ec4b1d40cefd190edd43369d1a6bc9c82", size = 486263, upload-time = "2026-07-23T01:54:54.223Z" }, + { url = "https://files.pythonhosted.org/packages/d4/dd/57187c8be2a35aea65eaee3bd2c3dcbbcf0204f5106c89637e3610380cd1/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:78253b573e6ffab5028924fc98bc281aae05445969982a10864bc360dea2016c", size = 492299, upload-time = "2026-07-23T01:54:56.236Z" }, + { url = "https://files.pythonhosted.org/packages/b9/11/06ae6ed8f0d414edf4068861e233d8fe23ee699bfd4b3ceb8663db948a62/aiohttp-3.14.3-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7041d52c3a7fa20c9e8c182b534704abb19502c8bdcbde7ab23bfda6f642394f", size = 502235, upload-time = "2026-07-23T01:54:58.377Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a3/559639c34a345d2cf7c52dff6838119f2eaf29eb508227b5b83f573af813/aiohttp-3.14.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ac74facc01463f138b0da5580329cfcc82818dea5656e83ddcd11268fc12ff80", size = 750883, upload-time = "2026-07-23T01:55:00.65Z" }, + { url = "https://files.pythonhosted.org/packages/91/cd/41e131f13afd1e7b0172a9d9eda085ef90eb8439f41f0d279db81ed3ae60/aiohttp-3.14.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d6218d92e450824e9b4881f44e8c09f1853b490f9a64130801024a4793b1b3b0", size = 508473, upload-time = "2026-07-23T01:55:02.945Z" }, + { url = "https://files.pythonhosted.org/packages/bc/6b/e7f13410d391c6e55b4c007a8de024355389d7d459e3d64c42b2d33617e5/aiohttp-3.14.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:11fb37ef075669eee52ab1928fbf6e1741fada40409fa309ebde9607a962aebf", size = 509190, upload-time = "2026-07-23T01:55:05.173Z" }, + { url = "https://files.pythonhosted.org/packages/97/21/6464573e53d69672cc1eada3e5c5cb2d2efa82701e8305a0f2047a576967/aiohttp-3.14.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55bdcc472aafe2de4a253045cc128007a64f1e0264fb675791e132ea5edaa3bd", size = 1761478, upload-time = "2026-07-23T01:55:07.383Z" }, + { url = "https://files.pythonhosted.org/packages/1a/81/d217043a4c17fbce360905e3b2bdd20139ebc9a2de836d035d179c4da006/aiohttp-3.14.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c39846c3aad97a8530c89d7a3869a8f8e9e3762c6ac0504481e5c80948f7e807", size = 1735092, upload-time = "2026-07-23T01:55:09.803Z" }, + { url = "https://files.pythonhosted.org/packages/a1/66/e13a02d0eeb1a9a502402a977abb4e4abff9fe4051c26f80558c57a7c975/aiohttp-3.14.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5895ef58c4620afe02fa16044f023dc4dafec08158f9d08874a46a7dbc0341b8", size = 1800546, upload-time = "2026-07-23T01:55:12.012Z" }, + { url = "https://files.pythonhosted.org/packages/26/5e/57d42fca1d18cb5acc1cad945d017fabc5d6ae71d8a08ad66be8dc3ee544/aiohttp-3.14.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa9467a8113aa69d3d7c55a70ef0b7c636010a40993f3df9d9d0d73b3eb7ef24", size = 1895250, upload-time = "2026-07-23T01:55:14.357Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1c/7da8d08e74d56f00070822f9638ff3f1c563f8ad87d1efa996c87bfc8644/aiohttp-3.14.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7d2deec16eeedf55f2c7cf75b521ea3856a5177e123844f8fd0f114ce252cb5", size = 1789289, upload-time = "2026-07-23T01:55:16.668Z" }, + { url = "https://files.pythonhosted.org/packages/cd/0f/cf16bcf56896981c1a0319f5d5db9337994b5165730c48a8fa07e9b34be6/aiohttp-3.14.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dd54d0e8717de95939766febac482ac0474d8ac3b048115f9f2b1d23a16e7db4", size = 1586706, upload-time = "2026-07-23T01:55:18.913Z" }, + { url = "https://files.pythonhosted.org/packages/fe/6f/76eac12a7f2480e1e304f842efdb07db33256b0d9165b866b6ef0806c202/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df82f3787c940c94986b34222d59c9e38843fba85139f36e85255a82ad5355a9", size = 1724652, upload-time = "2026-07-23T01:55:21.296Z" }, + { url = "https://files.pythonhosted.org/packages/39/b6/19c8c592baeeb94b75f966547d40c02ac7590902306ec5863d5c027cf506/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:42a67efc36300d052fb4508a53e8b6901b9284b599ae63945c377569c5fcc1e1", size = 1756239, upload-time = "2026-07-23T01:55:23.705Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c9/4e9383150296f97f873b680c4de8fb2cd88608fb9f48c79edcb111611abc/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7a75aa63cbf9b21cfaf60dc2657e19df2c2867d91707d653fee171ffeedd1371", size = 1769161, upload-time = "2026-07-23T01:55:26.082Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1e/147bdc6cc5de5f3ab011be8bf5d6e786633249f22c20bae06f85e45f5387/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e92eb8acc45eb6a9f4935071a77edf5b85cc6f8dfad5cd99e97653c26593cdde", size = 1578759, upload-time = "2026-07-23T01:55:28.846Z" }, + { url = "https://files.pythonhosted.org/packages/fd/31/78388a9d6040ece2e11df62ea229a822cf5e52d238374b220ae9975b2623/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b014a6ed7cf912e787149fdc529166d3ceabac23f26efeea3158c9aba2354e7e", size = 1792025, upload-time = "2026-07-23T01:55:31.457Z" }, + { url = "https://files.pythonhosted.org/packages/03/51/a3d29fdf2c25d796746af8ad6fe56a45d6256c38b0a8a2ed752e1160b3a2/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3d4f72af88ac2474bb5bca640030320e3d38a0163a1d7533500e87be458eef71", size = 1768477, upload-time = "2026-07-23T01:55:33.87Z" }, + { url = "https://files.pythonhosted.org/packages/29/a6/442e18b5afeade534d877a2dc3c3e392aff8d49787890b0cf84790410267/aiohttp-3.14.3-cp313-cp313-win32.whl", hash = "sha256:5f08ec777f35ee70720233b8b9811d3bb5d728137f30ac91b7457709c3261ac0", size = 451069, upload-time = "2026-07-23T01:55:36.121Z" }, + { url = "https://files.pythonhosted.org/packages/9d/69/3d876ac02659f271cf7f6769f14a8e3de5b6e888ed8b5a7e998086a4cec8/aiohttp-3.14.3-cp313-cp313-win_amd64.whl", hash = "sha256:dff9461ec275f22135650d5ba4b4931a11f3958df7dfbb8db630000d4dee0883", size = 476518, upload-time = "2026-07-23T01:55:38.303Z" }, + { url = "https://files.pythonhosted.org/packages/b2/0e/50d6e6471cd31edce8b282bdec59375a3a69124d8a989a0b1313355cae52/aiohttp-3.14.3-cp313-cp313-win_arm64.whl", hash = "sha256:ddcac3c6b382e81f1dd0499199d4136b877beb4cb5ef770bbbfba56c4b8f55d2", size = 447676, upload-time = "2026-07-23T01:55:40.451Z" }, + { url = "https://files.pythonhosted.org/packages/c8/20/887fdcf832326571b370ffc347b3e70abe101096f3720126aac161b1d872/aiohttp-3.14.3-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:49f7325beb0f85ef4aef5f48f490269575f83e6e2acad00a1d80b807eb027062", size = 509067, upload-time = "2026-07-23T01:55:42.618Z" }, + { url = "https://files.pythonhosted.org/packages/ad/a3/92cec936f78cc4bf0fa5554ebe593b73459d94e3c62303e1902a4cccb6f7/aiohttp-3.14.3-cp314-cp314-android_24_x86_64.whl", hash = "sha256:e3be98a7c30b8c25d573dafba7171d66dfb05ee6a9070fc46535464ff97700a6", size = 514774, upload-time = "2026-07-23T01:55:44.937Z" }, + { url = "https://files.pythonhosted.org/packages/29/ba/2a0c38df3fc557620b6a5acd98364af050053b6285b4dc7ee74100c63c18/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:614c61d478b83953e261d02bb2df750f17227cd33ef8002945bf5aebbde21919", size = 488134, upload-time = "2026-07-23T01:55:47.135Z" }, + { url = "https://files.pythonhosted.org/packages/48/d6/d51b7d4bf309af3693940d8ffd2b9ed0b682434ef85959b7c9c137f60cf8/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:1caa7b0d05f3e3a36f87788c59e970a7ee1cefcfcbb924a9f138c4a6551c9cb7", size = 494201, upload-time = "2026-07-23T01:55:49.451Z" }, + { url = "https://files.pythonhosted.org/packages/3f/5a/8f624384e5f1efabb5229b94157eb966b021e97bdb188c62860c2ae243c2/aiohttp-3.14.3-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:dfa68deb2a443bdaa3ea5297b0699c1464f08aef3812b486d1348eee61b07dc0", size = 502766, upload-time = "2026-07-23T01:55:51.656Z" }, + { url = "https://files.pythonhosted.org/packages/a6/26/4ff0164370deec18fb19254ee4ab10b7a73304ac0c860b13f5f84663759b/aiohttp-3.14.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:e72ee89e28d907a18f46959b4eb0bb06701cc7f8cf4366e00029e2ccfaaf5924", size = 756557, upload-time = "2026-07-23T01:55:53.964Z" }, + { url = "https://files.pythonhosted.org/packages/97/a3/7056b86dc0d9ec709ea9777eae3b0161428f943372f8b98c01c11593b682/aiohttp-3.14.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ad4c8b7488d745d2ca4838ebd8ae5ba9b56341d30b1da43640e4ce87f9f49646", size = 510168, upload-time = "2026-07-23T01:55:56.22Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/0357a015892fd68058bf2d39d3fd1958e459b997a7db30aaa6aaa434ae96/aiohttp-3.14.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:db332af25642007330fca8be5c4d194caf2bea7a7fc84415aff3497af5dfee6b", size = 512957, upload-time = "2026-07-23T01:55:58.437Z" }, + { url = "https://files.pythonhosted.org/packages/47/d1/8aba53f15ccb2238405f5e9d30e2a8ca44f93878c26e7165ade00d374b1c/aiohttp-3.14.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:25bd2708db6bdf6a6630dd37bdcdfcb47c4434d22ac69c64665b802910140b30", size = 1750149, upload-time = "2026-07-23T01:56:00.856Z" }, + { url = "https://files.pythonhosted.org/packages/49/bd/40c3fee327529284375c6701cbb0fa4600cc2e8432af1378f897e2ef7d3a/aiohttp-3.14.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:cef89a58e628c4efcac3275c2d68083f82426dcdc89c1492a6f654f9f7ea6ab9", size = 1707685, upload-time = "2026-07-23T01:56:03.371Z" }, + { url = "https://files.pythonhosted.org/packages/2a/a3/ca0cc6724cca8114b05694abd916060758c79894c3aa5b012cdadc1bc28e/aiohttp-3.14.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c23ec8ee9d5ab2f5421f9c7fffce208435607af27fd46d4a44e031954352838f", size = 1803911, upload-time = "2026-07-23T01:56:05.817Z" }, + { url = "https://files.pythonhosted.org/packages/95/b5/85b099c299c3ffd38ad9b3e43694c8a346934e4a30c88c4fd5a841234f77/aiohttp-3.14.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e2667f0bbe7eb6c74eae5e9691441ad186e5845ca3cff63230fc09c4e7514f5d", size = 1876929, upload-time = "2026-07-23T01:56:08.413Z" }, + { url = "https://files.pythonhosted.org/packages/d5/b7/1da684a04175473fa4cddbf9a2f572e79514c3fd27a74597f43057d4f3da/aiohttp-3.14.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18cb43369747b2ae007bd2655fb8e63a099c2ff1d207962943636dac989b3147", size = 1761112, upload-time = "2026-07-23T01:56:10.918Z" }, + { url = "https://files.pythonhosted.org/packages/d1/16/bc4b55e3e5cb175fd69c53c90d60d2f47797cb343da5106e23863dc4dba4/aiohttp-3.14.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d77640cc618c1d99fc4f8589c0f24a730adfa54eb1e57ef7bf0c8dfb78da898c", size = 1583500, upload-time = "2026-07-23T01:56:13.613Z" }, + { url = "https://files.pythonhosted.org/packages/2a/e8/13a9d957a1ee40837f46aa30f0f4c657e673ad86a2e6362a9f9be20d26d9/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:53e5179d8abb5710f8e83ba207c41c8d1261fcffd4616500e15ca2b7a33be10a", size = 1713940, upload-time = "2026-07-23T01:56:15.969Z" }, + { url = "https://files.pythonhosted.org/packages/38/05/d33c680c1bcf1c7e130f9cbfc1fc02fe8bb0c4af2a94a53dd5fb56131e5c/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:cd817772b2fcf2b8c0905795318485f9ec16eae60b29feb7f4c77085311637f0", size = 1724413, upload-time = "2026-07-23T01:56:18.591Z" }, + { url = "https://files.pythonhosted.org/packages/85/1d/af798d306f7a74b6a632dbcabcf62a4c91391b7582d2a8c6d7712e2cc54e/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:4e3ac92d90e92773b2362d506068e9a948192bd553e743c5b2429e28527c8661", size = 1770748, upload-time = "2026-07-23T01:56:21.074Z" }, + { url = "https://files.pythonhosted.org/packages/a8/92/ad720d472556a995049206867765e9410969684f86ee09423ff9969044c1/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:3f42e9b78301f11c8f861746175d8b9c1ccef713fcad9eab396e2f6db8ed4a22", size = 1577564, upload-time = "2026-07-23T01:56:23.475Z" }, + { url = "https://files.pythonhosted.org/packages/60/ad/0ed7586cbef7a884e23a752fa2bb987a122e6a5dd50dab109258d0a95193/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:9d9edccfe496b476db5f398d97b865e9a6752bcf8aec4eef8390ce20fb64bb41", size = 1782080, upload-time = "2026-07-23T01:56:25.994Z" }, + { url = "https://files.pythonhosted.org/packages/97/ea/dbaed0d73e8a69aad653b045dab451c67c2454bb731a37b45a86593e9422/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:1c5ec8fb1bcc31a8466f74aaf26c345d5c386fa4bd08a3f0eb9c7a4a3fe8b5bf", size = 1745813, upload-time = "2026-07-23T01:56:28.604Z" }, + { url = "https://files.pythonhosted.org/packages/81/1b/6893d4bc57e434fc93a6c9217c637d967a0b651d989f6e3265179375754a/aiohttp-3.14.3-cp314-cp314-win32.whl", hash = "sha256:38901a84da3ce22249f6e860bf8f90d141bcab7da090cc398f8bb58c0e44b7da", size = 455872, upload-time = "2026-07-23T01:56:31.031Z" }, + { url = "https://files.pythonhosted.org/packages/f5/8b/c7baa1ba1eda4db6989baefe5de6d99834921b84ebd7918624febcb9f290/aiohttp-3.14.3-cp314-cp314-win_amd64.whl", hash = "sha256:8b3b60de05f3dcb6f6a00f818bb2ec781cee4de0645f59ccaf99b1d1823b6100", size = 481030, upload-time = "2026-07-23T01:56:33.365Z" }, + { url = "https://files.pythonhosted.org/packages/22/8c/c29d067df825a2df88ca432db848aa2fe8199598359cc06c12b09320cac9/aiohttp-3.14.3-cp314-cp314-win_arm64.whl", hash = "sha256:1576145bdceeb92382d899751e12743a3a5b8e460a841e3e50543859e54864dc", size = 453669, upload-time = "2026-07-23T01:56:35.731Z" }, + { url = "https://files.pythonhosted.org/packages/6a/a4/9c033beb355d39b6147980597ec9645e4729243f686ee4dc73945de72030/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:8800c996b01c2772a783e3e46f3e1abd5823029adca0df54231960de9bfefa5b", size = 791403, upload-time = "2026-07-23T01:56:37.972Z" }, + { url = "https://files.pythonhosted.org/packages/80/ca/87c32a0a7704583cfc49660bd817889bae5b830bf53b5dcb4e92145ac2da/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ebe8e504f058fe91223351cecd2d9d6946c9d241bb0250d898ffbdf584cc72b0", size = 526413, upload-time = "2026-07-23T01:56:40.523Z" }, + { url = "https://files.pythonhosted.org/packages/9e/d8/8ec0e471248c500acdce2be3f46db8fb62b5eb60efef072529cc85ee1d26/aiohttp-3.14.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:30402d03a7c0ff52bce290b57e564e9079fd9d0cb545c8aba73f86a103162d2e", size = 532135, upload-time = "2026-07-23T01:56:42.876Z" }, + { url = "https://files.pythonhosted.org/packages/fe/45/f8919fd936e8b79fcd9bda7b6d8e62613462a713f4f17987fd7c34399142/aiohttp-3.14.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9fc7b5bfec6573f3ae844f457fdde5adeb713f8b8e4a81ad64fc207b49383716", size = 1922742, upload-time = "2026-07-23T01:56:45.528Z" }, + { url = "https://files.pythonhosted.org/packages/f6/ec/9ca76b28a27525b0cc53e20842e0228b022f301ce1f436b7d814b4aaf2df/aiohttp-3.14.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8a5fd34f7f7410d1730d5c2ba873cacb2eed3fede366feb268a70ba22581ed8f", size = 1787371, upload-time = "2026-07-23T01:56:48.045Z" }, + { url = "https://files.pythonhosted.org/packages/b1/04/6acdbf17315f7b55f1937e3387acb89a3cddeb4995689553d064af8e92ab/aiohttp-3.14.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:270d3dace9ca2f10f0da5d8ebe519b7a310fc6112ed916e32df5866df0888553", size = 1912623, upload-time = "2026-07-23T01:56:50.605Z" }, + { url = "https://files.pythonhosted.org/packages/86/e6/438b0c79ca6f45eb9fd9817dd4c01a91919a38c0de5ee9e05e2b4dc0ece7/aiohttp-3.14.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3ae5b3a59436d089b5395d910121a390feed4d00578eb95a0fd1a329fe963100", size = 2005515, upload-time = "2026-07-23T01:56:53.153Z" }, + { url = "https://files.pythonhosted.org/packages/bb/6b/62cbd6577758699525f5c712d1ddef57d9875fbab0ae8d5f5a202fd598f8/aiohttp-3.14.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2498f0fe69ead802f9675beca44a7c21c62fdaa4ec5145ea1c3ad6edbee29f85", size = 1879906, upload-time = "2026-07-23T01:56:55.818Z" }, + { url = "https://files.pythonhosted.org/packages/00/95/18bcbf830a21dc3aae24d8f6b6feaf3db1d2090242d00a7868db2ffb0b67/aiohttp-3.14.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a0dc483c00da8b673abbb367eb6f8d8f4bcec30eb58529ea13cb42e7fd2dfa33", size = 1675849, upload-time = "2026-07-23T01:56:58.861Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/47f4968659c5e23606c3790c80fc624e691c153d036148449ee84d31b287/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c7d3a97c678d34fc5b59da671ee9cd630096ddc643e7b5a30d54a2a6f3574d3f", size = 1843496, upload-time = "2026-07-23T01:57:01.591Z" }, + { url = "https://files.pythonhosted.org/packages/64/af/38c33c4dd82fddcb4e56c4653b6f1072a8edbc6b7fa15809f14932c41e2d/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:f8fb78a83c9e5f741ca3a68cfb455c1f5bb83b4e7249a3848b3cd78d0a8563b0", size = 1827746, upload-time = "2026-07-23T01:57:05.131Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9d/0537cda4885ac8f5b7053d164dd06312f4c483a4edcb8ee5b8aaf2a989bf/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:74ab5b6a9fb13e873e5a90946588baecaf488745e1db1a4a5c433f971f035098", size = 1853810, upload-time = "2026-07-23T01:57:08.043Z" }, + { url = "https://files.pythonhosted.org/packages/19/fe/26f9c5e6458385aa86497836b0dea6fb2f027827d63f37c7856cce9286ee/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:bd52f811e65f6fb634b1047159657c98f52b407f8efec907bcfc09da9a4c0a25", size = 1668895, upload-time = "2026-07-23T01:57:10.837Z" }, + { url = "https://files.pythonhosted.org/packages/ec/4c/618b1db9b9ba079b8875d2cdf78e7c4a3bf72903bd5850fee7dd9544600a/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:f0f177d1b195b9e06376cfd7d308d8a1b920909a609d03ac82a8c73bbb16d3b9", size = 1883833, upload-time = "2026-07-23T01:57:13.672Z" }, + { url = "https://files.pythonhosted.org/packages/94/c6/bd959bd1e4771f9fd944e9e436224c48c77b018b73b519b5aad346335bcc/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:498c6c623134f8e09a3c4e60bcd607a0b4590dd7dbf08dd40851b27cbb520ccb", size = 1844251, upload-time = "2026-07-23T01:57:16.593Z" }, + { url = "https://files.pythonhosted.org/packages/5e/19/08d41839658bdd44a0ed2480f3891705ecb487ce28c0dde62c9040c997e0/aiohttp-3.14.3-cp314-cp314t-win32.whl", hash = "sha256:b304db572b4368edd8dda8a2274f73156fe15558fca4a917cb8a09fc47af5963", size = 474180, upload-time = "2026-07-23T01:57:19.306Z" }, + { url = "https://files.pythonhosted.org/packages/99/5d/3cd6ef0a2b2851f7ab913b5b079334781bd50ff56a323e4454063377a080/aiohttp-3.14.3-cp314-cp314t-win_amd64.whl", hash = "sha256:b20032766aedf6261c7a566585a40867d092ac03a0d81592d5370ef9b054f99b", size = 500528, upload-time = "2026-07-23T01:57:21.762Z" }, + { url = "https://files.pythonhosted.org/packages/a4/37/cfd1ed540a4d318da025590d96b728e63713c09e9377950fc655dadeb856/aiohttp-3.14.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2e1161602f45a54de2ce0905243a95f58cb42dcd378402f3697f5e0b21e9d2e7", size = 469280, upload-time = "2026-07-23T01:57:24.241Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "anyio" +version = "4.14.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, +] + +[[package]] +name = "appnope" +version = "0.1.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/35/5d/752690df9ef5b76e169e68d6a129fa6d08a7100ca7f754c89495db3c6019/appnope-0.1.4.tar.gz", hash = "sha256:1de3860566df9caf38f01f86f65e0e13e379af54f9e4bee1e66b48f2efffd1ee", size = 4170, upload-time = "2024-02-06T09:43:11.258Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/29/5ecc3a15d5a33e31b26c11426c45c501e439cb865d0bff96315d86443b78/appnope-0.1.4-py2.py3-none-any.whl", hash = "sha256:502575ee11cd7a28c0205f379b525beefebab9d161b7c964670864014ed7213c", size = 4321, upload-time = "2024-02-06T09:43:09.663Z" }, +] + +[[package]] +name = "asttokens" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "babel" +version = "2.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/b2/51899539b6ceeeb420d40ed3cd4b7a40519404f9baf3d4ac99dc413a834b/babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d", size = 9959554, upload-time = "2026-02-01T12:30:56.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, +] + +[[package]] +name = "backrefs" +version = "8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/56/4744bcd0c82184e80c52b0ac4076c261a8ffa1f1b343ff2f6e89ce0e1cef/backrefs-8.0.tar.gz", hash = "sha256:b556cd7d36c3a3a2f256b89590b176b8eddfb73bcfaee3a3ddd84ea66d21ce50", size = 7013081, upload-time = "2026-07-26T19:54:24.638Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/fd/9bf53b6a6f6f519ffaac765df2f2a25e5c2fc6d32cfd2b2747099e72c911/backrefs-8.0-py310-none-any.whl", hash = "sha256:4a627b817fd2dce43b79ab48da63613340509381cd8ce0897078a0bce79a2ab8", size = 380377, upload-time = "2026-07-26T19:54:17.457Z" }, + { url = "https://files.pythonhosted.org/packages/e1/29/4bd7ae72a2634da00379c2b3bcc5439e7c94620235c6afea8af15229a973/backrefs-8.0-py311-none-any.whl", hash = "sha256:f0c35cf0102ba6b6070c12a492be3c1c1d3f5839529784b9a9565d6d04569a01", size = 392169, upload-time = "2026-07-26T19:54:18.782Z" }, + { url = "https://files.pythonhosted.org/packages/29/13/232505664e8e2a0c7a2eb0c505cfade9d715538f89a5d62bc4c272968f62/backrefs-8.0-py312-none-any.whl", hash = "sha256:87f0fae8c5f207fe9f4b2887efc71d42f4900ac78faa1af08d675ef303692dc5", size = 398084, upload-time = "2026-07-26T19:54:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/8a/69/47a3dc20abc4fa5486655fde681bd55e63211b46c886d8c02223d6468431/backrefs-8.0-py313-none-any.whl", hash = "sha256:601ce68ca12385dbda06ce264406b4c4210cf5b79fd0fd627592365c92f29a88", size = 400040, upload-time = "2026-07-26T19:54:21.194Z" }, + { url = "https://files.pythonhosted.org/packages/1c/cf/e5f9b68a5b0e939a2fb933a66c20180d0c9241bf8927f7a47fa48c1675e9/backrefs-8.0-py314-none-any.whl", hash = "sha256:9ec96efa080938be92323e8e730e57718c9c88eb15ad70bbef4e1766df591408", size = 411903, upload-time = "2026-07-26T19:54:23.221Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, + { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, + { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, + { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, + { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bd/2a/23f34ec9d04624958e137efdc394888716353190e75f25dd22c7a2c7a8aa/charset_normalizer-3.4.9.tar.gz", hash = "sha256:673611bbd43f0810bec0b0f028ddeaaa501190339cac411f347ac76917c3ae7b", size = 152439, upload-time = "2026-07-07T14:34:58.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/4a/ecbd131485c07fcdfad54e28946d513e3da22ef3b4bd854dcafae54ec739/charset_normalizer-3.4.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:45b0cc4e3556cd875e09102988d1ab8356c998b596c9fced84547c8138b487a0", size = 319300, upload-time = "2026-07-07T14:33:15.666Z" }, + { url = "https://files.pythonhosted.org/packages/ec/96/5d9364e3342d69f3a045e1777bc47c85c383e6e9466d561b33fdb419d1f9/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b2aff1c7b3884512b9512c3eaadd9bab39fb45042ffaaa1dd08ff2b9f8109d9", size = 215802, upload-time = "2026-07-07T14:33:17.031Z" }, + { url = "https://files.pythonhosted.org/packages/4b/4c/5361f9aa7f2cb58d94f2ab831b3d493f69efb1d239654b4744e3c09527cb/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9104ed0bd76a429d46f9ec0dbc9b08ad1d2dcdf2b00a5a0daa1c145329b35b44", size = 237171, upload-time = "2026-07-07T14:33:18.576Z" }, + { url = "https://files.pythonhosted.org/packages/50/78/ce342ca4ff30b2eb49fe6d9578df85974f90c67d294113e94efdd9664cbd/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7b86a2b16095d250c6f58b3d9b2eee6f4147754344f3dab0922f7c9bf7d226c9", size = 233075, upload-time = "2026-07-07T14:33:20.084Z" }, + { url = "https://files.pythonhosted.org/packages/01/c4/4fa4c8b3097a11f3c5f09a35b72ed6855fb1d332469504962ab7bafcc702/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e226f6218febc71f6c1fc2fafb91c226f75bdc1d8fb12d66823716e891608fd", size = 224256, upload-time = "2026-07-07T14:33:21.747Z" }, + { url = "https://files.pythonhosted.org/packages/87/3a/ad914516df7e358a81aae018caa5e0470ba827fa6d763b1d2e87d920a5f6/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:90c44bc373b7687f6948b693cceaea1348ae0975d7474746559494468e3c1d84", size = 208784, upload-time = "2026-07-07T14:33:23.313Z" }, + { url = "https://files.pythonhosted.org/packages/d7/74/3c12f9755717dfe5c5c87da63f35d765fa0c00382ec26bf23f7fae34f2ba/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9cdef90ae47919cae358d8ab15797a800ed41da7aba5d72419fb510729e2ed4b", size = 219928, upload-time = "2026-07-07T14:33:24.814Z" }, + { url = "https://files.pythonhosted.org/packages/33/9a/895095b83e7907abd6d3d99aad3a38ad0d9686cc186cb0c94c24320fe63e/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:60f44ade2cf573dad7a277e6f8ca9a51a21dda572b13bd7d8539bb3cd5dbedde", size = 218489, upload-time = "2026-07-07T14:33:26.42Z" }, + { url = "https://files.pythonhosted.org/packages/a1/34/ef5c05f412f42520d7709b7d3784d19640839eb7366ded1755511585429f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a1786910334ed46ab1dd73222f2cd1e05c2c3bb39f6dddb4f8b36fc382058a39", size = 210267, upload-time = "2026-07-07T14:33:27.952Z" }, + { url = "https://files.pythonhosted.org/packages/83/dc/9b29fa4412b318bf3bfea985c35d67eb55e04b59a7c3f2237168b0e0be6f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:03d07803992c6c7bbc976327f34b18b6160327fc81cb82c9d504720ac0be3b62", size = 226030, upload-time = "2026-07-07T14:33:29.397Z" }, + { url = "https://files.pythonhosted.org/packages/0e/42/6dbc00b8cd16011691203e33570fa42ed5746599a2e878112d16eab403a3/charset_normalizer-3.4.9-cp312-cp312-win32.whl", hash = "sha256:78841cccf1af7b40f6f716338d50c0902dbe88d9f800b3c973b7a9a0a693a642", size = 151185, upload-time = "2026-07-07T14:33:30.781Z" }, + { url = "https://files.pythonhosted.org/packages/80/cc/f920afd1a23c58ccd53c1d36085a71893a4737ff5e66e0371efab6809850/charset_normalizer-3.4.9-cp312-cp312-win_amd64.whl", hash = "sha256:4b3dac63058cc36820b0dd072f89898604e2d39686fe05321729d00d8ac185a0", size = 162557, upload-time = "2026-07-07T14:33:32.176Z" }, + { url = "https://files.pythonhosted.org/packages/f0/e6/0386d43a261ff4e4b30c5857af7df877254b46bec7b9d1b74b6bf969a90b/charset_normalizer-3.4.9-cp312-cp312-win_arm64.whl", hash = "sha256:78fa18e436a1a0e58dbd7e02fc4473f3f32cceb12df9dfca542d075961c307d2", size = 152665, upload-time = "2026-07-07T14:33:33.711Z" }, + { url = "https://files.pythonhosted.org/packages/b2/06/97ec2aeae780b31d742b6352218b43841a6871e2564578ca522dce4a45c3/charset_normalizer-3.4.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:440eede837960000d74978f0eba527be106b5b9aee0daf779d395276ed0b0614", size = 317688, upload-time = "2026-07-07T14:33:35.408Z" }, + { url = "https://files.pythonhosted.org/packages/d0/39/8ff066c672434225f8d25f8b739f992af250944392173dcc88362681c9bf/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e764fd1e70b6a3e205a0e46f3051701f98a8cb3fad66eeb80e48bb502f8698", size = 214982, upload-time = "2026-07-07T14:33:36.996Z" }, + { url = "https://files.pythonhosted.org/packages/92/8f/3a47a3667c83c2df9483d91644c6c107de3bf8874aa1793da9d3012eb986/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e4fd89cc178bced6ad29cb3e6dd4aa63fa5017c3524dbd0b25998fb64a87cc8b", size = 236460, upload-time = "2026-07-07T14:33:38.536Z" }, + { url = "https://files.pythonhosted.org/packages/f1/60/b22cdbee7e4013dab8b0d7647fc6181120fbbbc8f7025c226d15bd5a47fc/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bd47ba7fc3ca94896759ea0109775132d3e7ab921fbf54038e1bab2e46c313c9", size = 232003, upload-time = "2026-07-07T14:33:40.059Z" }, + { url = "https://files.pythonhosted.org/packages/ea/f8/72eb13dcabe7257035cea8aefd922caad2f110d252bf9f67c4c2ca763aee/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84fd18bcc17526fc2b3c1af7d2b9217d32c9c04448c16ec693b9b4f1985c3d33", size = 223149, upload-time = "2026-07-07T14:33:41.631Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3e/faee8f9de92b14ee1198e9163252bb15efee7301b31256a3b6d9ebfdd0dd/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:5b10cd92fc5c498b35a8635df6d5a100207f88b63a4dc1de7ef9a548e1e2cd63", size = 207901, upload-time = "2026-07-07T14:33:43.209Z" }, + { url = "https://files.pythonhosted.org/packages/3a/25/45f30093ae27dd7b92a793b61882a38685f993700113ca36e0c9c14965e1/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a4fbdde9dd4a9ce5fd52c2b3a347bb50cc89483ef783f1cb00d408c13f7a96c0", size = 219176, upload-time = "2026-07-07T14:33:44.725Z" }, + { url = "https://files.pythonhosted.org/packages/48/18/c8f397329c35e32f6a837e488986f4ae03bd2abebc453b48714991630c2f/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:416c229f77e5ea25b3dfd4b582f8d73d7e43c22320302b9ab128a2d3a0b38efe", size = 217356, upload-time = "2026-07-07T14:33:46.192Z" }, + { url = "https://files.pythonhosted.org/packages/86/7e/5ce0bba863470fd1902d5e5843968951bddf38abe4742fc97116ef4598b3/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:75286256590a6320cf106a0d28970d3560aad9ee09aa7b34fb40524792436d35", size = 209614, upload-time = "2026-07-07T14:33:47.705Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ef/2473d3c4d869155be4af1191111d59c4d5c4e0173026f7e85b176e23bf65/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:69b157c5d3292bcd443faca052f3096f637f1e074b98212a933c074ae23dc3b8", size = 224991, upload-time = "2026-07-07T14:33:49.238Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a3/53ddae3db108a088156aa8ddfafd411ebbc1340f48c5573f697b27f69a39/charset_normalizer-3.4.9-cp313-cp313-win32.whl", hash = "sha256:51307f5c71007673a2bf8232ad973483d281e74cb99c8c5a990af1eefa6277d9", size = 150622, upload-time = "2026-07-07T14:33:50.711Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ef/6953a77c7cf2c2ff9998e6f575ab3e380119f100223381565a4f94c1f836/charset_normalizer-3.4.9-cp313-cp313-win_amd64.whl", hash = "sha256:fe2c7201c642b7c308f1675355ad7ff7b66acfe3541625efe5a3ad38f29d6115", size = 161947, upload-time = "2026-07-07T14:33:52.197Z" }, + { url = "https://files.pythonhosted.org/packages/6e/fb/d560d1d1555debbfe7849d9cac6145c1b537709d79576bf22557ed803b82/charset_normalizer-3.4.9-cp313-cp313-win_arm64.whl", hash = "sha256:611057cc5d5c0afc743ba8be6bd828c17e0aaa8643f9d0a9b9bb7dea80eb8012", size = 152594, upload-time = "2026-07-07T14:33:53.486Z" }, + { url = "https://files.pythonhosted.org/packages/7e/8d/496817fa0944239ecae662dd57ea765cfeaec6a735f9f025d4b7b72e7143/charset_normalizer-3.4.9-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0327fcd59a935777d83410750c50600ee9571af2846f71ce40f25b13da1ef380", size = 317253, upload-time = "2026-07-07T14:33:54.994Z" }, + { url = "https://files.pythonhosted.org/packages/2b/f9/ef4a69ea338ad3c0deceea0f5f7d2380ae8b52132b06d652cb0d2cd86706/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a79d9f4d8001473a30c163556b3c3bfebec837495a412dde78b51672f6134f9", size = 215898, upload-time = "2026-07-07T14:33:56.334Z" }, + { url = "https://files.pythonhosted.org/packages/8c/e7/5ddfd76fc061eb52de219658a4aa431cbacadf0a0219c8854f00da50d289/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:33bdcc2a32c0a0e861f60841a512c8acc658c87c2ac59d89e3a46dacf7d866e4", size = 236718, upload-time = "2026-07-07T14:33:57.9Z" }, + { url = "https://files.pythonhosted.org/packages/49/ba/768fa3f36048d81c477a0ce61f813bc1454d80917ccfe550abd9f44f5e24/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f840ed6d8ecba8255df8c42b87fadeda98ddfc6eeec05e2dc66e26d46dd6f58a", size = 232519, upload-time = "2026-07-07T14:33:59.811Z" }, + { url = "https://files.pythonhosted.org/packages/f4/c4/b3e049d2aa3766180c78507110543d9d50894cc97f57de543f1be521dcdc/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c25fe15c70c59eb7c5ce8c06a1f3fa1da0ecc5ea1e7a5922c40fd2fa9b0d5046", size = 223143, upload-time = "2026-07-07T14:34:01.517Z" }, + { url = "https://files.pythonhosted.org/packages/19/79/55c32d06d76ae4feafe053f061f3e3ab70bcf19f4007797ce8c3efda7830/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:f7fb7d750cfa0a070d2c24e831fd3481019a60dd317ea2b39acbcebc08b6ed81", size = 206742, upload-time = "2026-07-07T14:34:03.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/e0/47c079dd82d217c807479cd59ffd30af56307ea31c108b75758970459ad3/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d1c96a7a18b9690a4d46df09e3e3382406ae3213727cd1019ebade1c4a81917", size = 219191, upload-time = "2026-07-07T14:34:04.657Z" }, + { url = "https://files.pythonhosted.org/packages/42/ab/b9bc2e77d6b44a7e46ef62ec5cac1c9a6ba7b9135a5d560f002696ec9995/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a4cfde78a9f2880208d16a93b795726a3017d5977e08d1e162a7a31322479c41", size = 218328, upload-time = "2026-07-07T14:34:06.115Z" }, + { url = "https://files.pythonhosted.org/packages/f1/78/c9c71d599f5aa2d42bcdd35cbbd46d7f535351a57e40ff7d8e5a7e219401/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:d4d6fcde76f94f5cb9e43e9e9a61f16dacefd228cbbf6f1a09bd9b219a92f1a1", size = 207406, upload-time = "2026-07-07T14:34:07.554Z" }, + { url = "https://files.pythonhosted.org/packages/f6/39/c914445c321a845097ce4f6ac7de9a18228a77b766272125a1ce00d851eb/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:898f0e9068ca27d37f8e83a5b962821df851532e6c4a7d615c1c033f9da6eedf", size = 225157, upload-time = "2026-07-07T14:34:09.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f2/c0d4b8508565a36bc5c624e88ed297f5b0b1095011034d7f5b83a69908b5/charset_normalizer-3.4.9-cp314-cp314-win32.whl", hash = "sha256:c1c948747b03be832dceed96ca815cef7360de9aa19d37c730f8e3f6101aca48", size = 151095, upload-time = "2026-07-07T14:34:10.901Z" }, + { url = "https://files.pythonhosted.org/packages/49/fd/a1d26144398c67486422a72bf5812cda22cb4ccfcd95a290fb41ceb4b8e2/charset_normalizer-3.4.9-cp314-cp314-win_amd64.whl", hash = "sha256:16b65ea0f2465b6fb52aa22de5eca612aa964ddfec00a912e26f4656cbef890b", size = 162796, upload-time = "2026-07-07T14:34:12.47Z" }, + { url = "https://files.pythonhosted.org/packages/20/95/d75e82f8ce9fd323ebf059c16c9aadefb22a1ecde13b7840b35835e4886c/charset_normalizer-3.4.9-cp314-cp314-win_arm64.whl", hash = "sha256:40a126142a56b2dfc0aacbad1de8310cbf60da7656db0e6b16eebd48e3e93519", size = 153334, upload-time = "2026-07-07T14:34:14.044Z" }, + { url = "https://files.pythonhosted.org/packages/00/5e/17398df3a139985ba9d11ed072531986f408c8fca952835ef1ab1820c02b/charset_normalizer-3.4.9-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:609b3ba8fcc0fb5ab7af00719d0fb6ad0cb518e48e7712d12fd68f1327951198", size = 338848, upload-time = "2026-07-07T14:34:15.688Z" }, + { url = "https://files.pythonhosted.org/packages/cd/91/7253a32e86b7e1d1239b1b36ba6dd0f021a21107ab33054b53119cc083b9/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51447e9aa2684679af07ca5021c3db526e0284347ebf4ffcec1154c3350cfe32", size = 223022, upload-time = "2026-07-07T14:34:17.248Z" }, + { url = "https://files.pythonhosted.org/packages/cb/32/2e64bd2be10e89c61e57ebe6a93fd98ae88eb7ebe414b5121f22c96c69eb/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cc1b0fff8ead343dae06305f954eb8468ba0ec1a97881f42489d198e4ce3c632", size = 241590, upload-time = "2026-07-07T14:34:18.813Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ef/d96ec496cfea0c21db43b0ad03891308b02388d054cc902cf0e5a1ad6a88/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa36ec09ef71d158186bc79e359ff5fdd6e7996fe8ab638f00d6b93139ba4fcf", size = 239584, upload-time = "2026-07-07T14:34:20.52Z" }, + { url = "https://files.pythonhosted.org/packages/d4/ce/9af95f7876194bd7a14e3dfe4a4de2e0bff02666a3910d72beafd06cc297/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df115d4d83168fdf2cae48ef1ff6d1cb4c466364e30861b37121de0f3bf1b990", size = 230224, upload-time = "2026-07-07T14:34:22.189Z" }, + { url = "https://files.pythonhosted.org/packages/52/94/af74dde74a3996bd959c350709bfe50e297823d70a8c1cbd54b838880863/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f86c6358749bd4fda175388691e3ba8c46e24c5347d0afd20f9b7edfc9faf07d", size = 212667, upload-time = "2026-07-07T14:34:23.857Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f0/f1c4fe746c395922961b5916ed1d7d6e7d4c84851d19ed43cc89980ec953/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:32286a2c8d167e897177b673176c1e3e00d4057caf5d2b64eef9a3666b03018e", size = 227179, upload-time = "2026-07-07T14:34:25.586Z" }, + { url = "https://files.pythonhosted.org/packages/e4/56/6c745619ac397e8871e2bcd3cea1eec86b877488f33888b3aef5c3ed506e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:83aed2c10721ddd90f68140685391b50811a880af20654c59af6b6c66c40513c", size = 225372, upload-time = "2026-07-07T14:34:27.212Z" }, + { url = "https://files.pythonhosted.org/packages/78/ad/98aae8630ac71f16711968e38a5acfecce41b778bf2f0312851020f565a8/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cd6c3d4b783c556fa00bf540854e42f135e2f256abd29669fcd0da0f2dec79c2", size = 215222, upload-time = "2026-07-07T14:34:28.774Z" }, + { url = "https://files.pythonhosted.org/packages/f7/40/9593d54209765207a7f11073c06494c1721e4ca4a0a426c597679bf7f91e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ee2f2a527e3c1a6e6411eb4209642e138b544a2d72fe5d0d76daf77b24063534", size = 231958, upload-time = "2026-07-07T14:34:30.345Z" }, + { url = "https://files.pythonhosted.org/packages/b1/27/693ee5e8a18191eb38647360c51cd505013e2bd3b366aa43fd5344c21e3c/charset_normalizer-3.4.9-cp314-cp314t-win32.whl", hash = "sha256:0d861473f743244d349b50f850d10eb87aeb22bbdcc8e64f79273c94af5a8226", size = 155580, upload-time = "2026-07-07T14:34:31.884Z" }, + { url = "https://files.pythonhosted.org/packages/80/3f/bd97d3d9c613013d07cb7733d299385b41df37f0471310f5a73dc359f0b8/charset_normalizer-3.4.9-cp314-cp314t-win_amd64.whl", hash = "sha256:9b8e0f3107e2200b76f6054de99016eac3ee6762713587b36baaa7e4bd2ae177", size = 167620, upload-time = "2026-07-07T14:34:33.438Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c6/eee9dca4439b1061f76373f06ea855678cc4a64c1c3c90b50e479edbb8eb/charset_normalizer-3.4.9-cp314-cp314t-win_arm64.whl", hash = "sha256:19ac87f93086ce37b86e098888555c4b4bc48102279bae3350098c0ed664b501", size = 158037, upload-time = "2026-07-07T14:34:35.018Z" }, + { url = "https://files.pythonhosted.org/packages/98/2b/f97f1c193fb855c345d678f5077d6926034db0722df74c8f057020e05a25/charset_normalizer-3.4.9-py3-none-any.whl", hash = "sha256:68e5f26a1ad57ded6d1cfb85331d1c1a195314756471d97758c48498bb4dcdf5", size = 64538, upload-time = "2026-07-07T14:34:56.993Z" }, +] + +[[package]] +name = "click" +version = "8.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" }, +] + +[[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 = "comm" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4c/13/7d740c5849255756bc17888787313b61fd38a0a8304fc4f073dfc46122aa/comm-0.2.3.tar.gz", hash = "sha256:2dc8048c10962d55d7ad693be1e7045d891b7ce8d999c97963a5e3e99c055971", size = 6319, upload-time = "2025-07-25T14:02:04.452Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" }, +] + +[[package]] +name = "debugpy" +version = "1.8.21" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f2/aa/12037145b7a56eaa5b29b41872f7a21b538e807e13f32c4d3c46e59be084/debugpy-1.8.21.tar.gz", hash = "sha256:a3c53278e84c94e11bd87c53970ec391d1a67396c8b22609fcac576520e611a6", size = 1697577, upload-time = "2026-06-01T19:30:35.156Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/df/bf625547431a9cadc9f4cbfeda38866e2b17f6aed147b625377e87834449/debugpy-1.8.21-cp312-cp312-macosx_15_0_universal2.whl", hash = "sha256:9f96713896f39c3dff0ee841f47320c3f2983d33c341e009361bb0ebc79adc4e", size = 2483609, upload-time = "2026-06-01T19:30:50.794Z" }, + { url = "https://files.pythonhosted.org/packages/bf/09/59324b903599031ff9faaec1758292409f6561a0ec2492fe4b703327705a/debugpy-1.8.21-cp312-cp312-manylinux_2_34_x86_64.whl", hash = "sha256:c193d474f0a211191f2b4449d2d06157c689013035bd952f3b617e0ef422b176", size = 3968900, upload-time = "2026-06-01T19:30:52.341Z" }, + { url = "https://files.pythonhosted.org/packages/14/cd/27f65b805d7fe005c44e1a36b9183ecdfbcdbf9d3e721a5115d461ecc7ee/debugpy-1.8.21-cp312-cp312-win32.whl", hash = "sha256:4743373c1cac7f9e74a1b9915bf1dbe0e900eca657ffb170ae07ac8363205ae9", size = 5336340, upload-time = "2026-06-01T19:30:54.047Z" }, + { url = "https://files.pythonhosted.org/packages/77/1d/c84e30c0c674184948b66f076ab271c01d940618a2824c23cd035a27bc20/debugpy-1.8.21-cp312-cp312-win_amd64.whl", hash = "sha256:bd7ba9dd3daa7c2f942c6ca8d4695a16bf9ac16b63615261c7982bc74f7ed20c", size = 5374751, upload-time = "2026-06-01T19:30:55.891Z" }, + { url = "https://files.pythonhosted.org/packages/77/6b/d817e1f8cc77aa055d37fba092e0febfdff40fe652d8d53d4cd7a86ad98d/debugpy-1.8.21-cp313-cp313-macosx_15_0_universal2.whl", hash = "sha256:13678151fc401e2d68c9880b91e28714f797d40422994572b24560ef80910a88", size = 2477398, upload-time = "2026-06-01T19:30:57.644Z" }, + { url = "https://files.pythonhosted.org/packages/48/57/412421516afc3055fa577516f00beec3d663f9b0ab330639547ae6c57720/debugpy-1.8.21-cp313-cp313-manylinux_2_34_x86_64.whl", hash = "sha256:ecbd158386c31ffe71d46f72d44d56e66331ab9b16cad649156d514368f23ab2", size = 3962096, upload-time = "2026-06-01T19:30:59.235Z" }, + { url = "https://files.pythonhosted.org/packages/c1/62/2c616337cf6ba7b07ebbc97f02c6c945a8e2f76b365e33ee809c32ee36d1/debugpy-1.8.21-cp313-cp313-win32.whl", hash = "sha256:2c2ae706dec41d99a9ca1f7ebc987a83e65578363be6f6b3ac9067504917fae1", size = 5336288, upload-time = "2026-06-01T19:31:00.79Z" }, + { url = "https://files.pythonhosted.org/packages/f8/99/9175103392f84c4b1bf7622888cdc68da07f0ff7d9e581266428f6776033/debugpy-1.8.21-cp313-cp313-win_amd64.whl", hash = "sha256:aa648733047443eb1d07682c4ef287d36a54507b643ffdf38b09a3ef002c72a0", size = 5376567, upload-time = "2026-06-01T19:31:02.56Z" }, + { url = "https://files.pythonhosted.org/packages/ce/3d/f4bbb323a548bfab2af3d6b4ffd9bf22636e55956a1285d317a1de643aad/debugpy-1.8.21-cp314-cp314-macosx_15_0_universal2.whl", hash = "sha256:9bb2a685287a2ac9b181cde89edcec64845cb51de7faaa75badb9a698bc24782", size = 2477209, upload-time = "2026-06-01T19:31:04.157Z" }, + { url = "https://files.pythonhosted.org/packages/8c/2d/6e7ec524984a1702777868de49a4c53202bddac2a432a76a093469587750/debugpy-1.8.21-cp314-cp314-manylinux_2_34_x86_64.whl", hash = "sha256:3d6922439bf33fd38a3e2c447869ebc7b97da5cd3d329ff1ef9bc06c4903437e", size = 3927115, upload-time = "2026-06-01T19:31:05.863Z" }, + { url = "https://files.pythonhosted.org/packages/97/47/d1aa6d64005a98a9144647d99306b419396f9ad7bf1d73c119e17a81fb4d/debugpy-1.8.21-cp314-cp314-win32.whl", hash = "sha256:15d4963bd5ffa48f0da0947fd06757fa7621945048a14ad7705431566d3c0e7c", size = 5336724, upload-time = "2026-06-01T19:31:07.711Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/b905b90d163af11878c1af8abafa4a25206335e112e284e413454543a6da/debugpy-1.8.21-cp314-cp314-win_amd64.whl", hash = "sha256:fe0744a12353406de0ae8ccff0d0a4a666f00801a3db8fd04e7a5f761cd520e8", size = 5373803, upload-time = "2026-06-01T19:31:09.469Z" }, + { url = "https://files.pythonhosted.org/packages/95/51/67e7cf11a53e40694f720457d5b3a1cdaaa3d5a9a633e482f225456b93ff/debugpy-1.8.21-py2.py3-none-any.whl", hash = "sha256:b1e37d333663c8851516a47364ef473da127f9caebe4417e6df6f5825a7e9a92", size = 5352888, upload-time = "2026-06-01T19:31:25.186Z" }, +] + +[[package]] +name = "donfig" +version = "0.8.1.post1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/25/71/80cc718ff6d7abfbabacb1f57aaa42e9c1552bfdd01e64ddd704e4a03638/donfig-0.8.1.post1.tar.gz", hash = "sha256:3bef3413a4c1c601b585e8d297256d0c1470ea012afa6e8461dc28bfb7c23f52", size = 19506, upload-time = "2024-05-23T14:14:31.513Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/d5/c5db1ea3394c6e1732fb3286b3bd878b59507a8f77d32a2cebda7d7b7cd4/donfig-0.8.1.post1-py3-none-any.whl", hash = "sha256:2a3175ce74a06109ff9307d90a230f81215cbac9a751f4d1c6194644b8204f9d", size = 21592, upload-time = "2024-05-23T14:13:55.283Z" }, +] + +[[package]] +name = "executing" +version = "2.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cc/28/c14e053b6762b1044f34a13aab6859bbf40456d37d23aa286ac24cfd9a5d/executing-2.2.1.tar.gz", hash = "sha256:3632cc370565f6648cc328b32435bd120a1e4ebb20c77e3fdde9a13cd1e533c4", size = 1129488, upload-time = "2025-09-01T09:48:10.866Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl", hash = "sha256:760643d3452b4d777d295bb167ccc74c64a81df23fb5e08eff250c425a4b2017", size = 28317, upload-time = "2025-09-01T09:48:08.5Z" }, +] + +[[package]] +name = "fastjsonschema" +version = "2.22.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/98/474719c58eddaf77fa443b063693e76d49db32bbe851bcbaf58d2700119f/fastjsonschema-2.22.1.tar.gz", hash = "sha256:0b83d1ce8d7845b959dcb20e1a5c3c8883b6541d9c52ab02cce5166b75ec805f", size = 382291, upload-time = "2026-07-27T13:31:08.515Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/17/e1/62cc96341f01bdff2ba967441939178fcd1900d11ce7e6554d9954a5d7ec/fastjsonschema-2.22.1-py3-none-any.whl", hash = "sha256:cf377ff5c9a6f4f3125fb35f75a2c5767bd824ffbcf62c209a93cd48d1453999", size = 26239, upload-time = "2026-07-27T13:31:03.251Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/29/948b9aa87e75820a38650af445d2ef2b6b8a6fab1a23b6bb9e4ef0be2d59/frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1", size = 87782, upload-time = "2025-10-06T05:36:06.649Z" }, + { url = "https://files.pythonhosted.org/packages/64/80/4f6e318ee2a7c0750ed724fa33a4bdf1eacdc5a39a7a24e818a773cd91af/frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b", size = 50594, upload-time = "2025-10-06T05:36:07.69Z" }, + { url = "https://files.pythonhosted.org/packages/2b/94/5c8a2b50a496b11dd519f4a24cb5496cf125681dd99e94c604ccdea9419a/frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4", size = 50448, upload-time = "2025-10-06T05:36:08.78Z" }, + { url = "https://files.pythonhosted.org/packages/6a/bd/d91c5e39f490a49df14320f4e8c80161cfcce09f1e2cde1edd16a551abb3/frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383", size = 242411, upload-time = "2025-10-06T05:36:09.801Z" }, + { url = "https://files.pythonhosted.org/packages/8f/83/f61505a05109ef3293dfb1ff594d13d64a2324ac3482be2cedc2be818256/frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4", size = 243014, upload-time = "2025-10-06T05:36:11.394Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cb/cb6c7b0f7d4023ddda30cf56b8b17494eb3a79e3fda666bf735f63118b35/frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8", size = 234909, upload-time = "2025-10-06T05:36:12.598Z" }, + { url = "https://files.pythonhosted.org/packages/31/c5/cd7a1f3b8b34af009fb17d4123c5a778b44ae2804e3ad6b86204255f9ec5/frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b", size = 250049, upload-time = "2025-10-06T05:36:14.065Z" }, + { url = "https://files.pythonhosted.org/packages/c0/01/2f95d3b416c584a1e7f0e1d6d31998c4a795f7544069ee2e0962a4b60740/frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52", size = 256485, upload-time = "2025-10-06T05:36:15.39Z" }, + { url = "https://files.pythonhosted.org/packages/ce/03/024bf7720b3abaebcff6d0793d73c154237b85bdf67b7ed55e5e9596dc9a/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29", size = 237619, upload-time = "2025-10-06T05:36:16.558Z" }, + { url = "https://files.pythonhosted.org/packages/69/fa/f8abdfe7d76b731f5d8bd217827cf6764d4f1d9763407e42717b4bed50a0/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3", size = 250320, upload-time = "2025-10-06T05:36:17.821Z" }, + { url = "https://files.pythonhosted.org/packages/f5/3c/b051329f718b463b22613e269ad72138cc256c540f78a6de89452803a47d/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143", size = 246820, upload-time = "2025-10-06T05:36:19.046Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/58282e8f98e444b3f4dd42448ff36fa38bef29e40d40f330b22e7108f565/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608", size = 250518, upload-time = "2025-10-06T05:36:20.763Z" }, + { url = "https://files.pythonhosted.org/packages/8f/96/007e5944694d66123183845a106547a15944fbbb7154788cbf7272789536/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa", size = 239096, upload-time = "2025-10-06T05:36:22.129Z" }, + { url = "https://files.pythonhosted.org/packages/66/bb/852b9d6db2fa40be96f29c0d1205c306288f0684df8fd26ca1951d461a56/frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf", size = 39985, upload-time = "2025-10-06T05:36:23.661Z" }, + { url = "https://files.pythonhosted.org/packages/b8/af/38e51a553dd66eb064cdf193841f16f077585d4d28394c2fa6235cb41765/frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746", size = 44591, upload-time = "2025-10-06T05:36:24.958Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1dc65480ab147339fecc70797e9c2f69d9cea9cf38934ce08df070fdb9cb/frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd", size = 40102, upload-time = "2025-10-06T05:36:26.333Z" }, + { url = "https://files.pythonhosted.org/packages/2d/40/0832c31a37d60f60ed79e9dfb5a92e1e2af4f40a16a29abcc7992af9edff/frozenlist-1.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a", size = 85717, upload-time = "2025-10-06T05:36:27.341Z" }, + { url = "https://files.pythonhosted.org/packages/30/ba/b0b3de23f40bc55a7057bd38434e25c34fa48e17f20ee273bbde5e0650f3/frozenlist-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7", size = 49651, upload-time = "2025-10-06T05:36:28.855Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ab/6e5080ee374f875296c4243c381bbdef97a9ac39c6e3ce1d5f7d42cb78d6/frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40", size = 49417, upload-time = "2025-10-06T05:36:29.877Z" }, + { url = "https://files.pythonhosted.org/packages/d5/4e/e4691508f9477ce67da2015d8c00acd751e6287739123113a9fca6f1604e/frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027", size = 234391, upload-time = "2025-10-06T05:36:31.301Z" }, + { url = "https://files.pythonhosted.org/packages/40/76/c202df58e3acdf12969a7895fd6f3bc016c642e6726aa63bd3025e0fc71c/frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822", size = 233048, upload-time = "2025-10-06T05:36:32.531Z" }, + { url = "https://files.pythonhosted.org/packages/f9/c0/8746afb90f17b73ca5979c7a3958116e105ff796e718575175319b5bb4ce/frozenlist-1.8.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121", size = 226549, upload-time = "2025-10-06T05:36:33.706Z" }, + { url = "https://files.pythonhosted.org/packages/7e/eb/4c7eefc718ff72f9b6c4893291abaae5fbc0c82226a32dcd8ef4f7a5dbef/frozenlist-1.8.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5", size = 239833, upload-time = "2025-10-06T05:36:34.947Z" }, + { url = "https://files.pythonhosted.org/packages/c2/4e/e5c02187cf704224f8b21bee886f3d713ca379535f16893233b9d672ea71/frozenlist-1.8.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e", size = 245363, upload-time = "2025-10-06T05:36:36.534Z" }, + { url = "https://files.pythonhosted.org/packages/1f/96/cb85ec608464472e82ad37a17f844889c36100eed57bea094518bf270692/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11", size = 229314, upload-time = "2025-10-06T05:36:38.582Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6f/4ae69c550e4cee66b57887daeebe006fe985917c01d0fff9caab9883f6d0/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1", size = 243365, upload-time = "2025-10-06T05:36:40.152Z" }, + { url = "https://files.pythonhosted.org/packages/7a/58/afd56de246cf11780a40a2c28dc7cbabbf06337cc8ddb1c780a2d97e88d8/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1", size = 237763, upload-time = "2025-10-06T05:36:41.355Z" }, + { url = "https://files.pythonhosted.org/packages/cb/36/cdfaf6ed42e2644740d4a10452d8e97fa1c062e2a8006e4b09f1b5fd7d63/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8", size = 240110, upload-time = "2025-10-06T05:36:42.716Z" }, + { url = "https://files.pythonhosted.org/packages/03/a8/9ea226fbefad669f11b52e864c55f0bd57d3c8d7eb07e9f2e9a0b39502e1/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed", size = 233717, upload-time = "2025-10-06T05:36:44.251Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0b/1b5531611e83ba7d13ccc9988967ea1b51186af64c42b7a7af465dcc9568/frozenlist-1.8.0-cp313-cp313-win32.whl", hash = "sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496", size = 39628, upload-time = "2025-10-06T05:36:45.423Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cf/174c91dbc9cc49bc7b7aab74d8b734e974d1faa8f191c74af9b7e80848e6/frozenlist-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231", size = 43882, upload-time = "2025-10-06T05:36:46.796Z" }, + { url = "https://files.pythonhosted.org/packages/c1/17/502cd212cbfa96eb1388614fe39a3fc9ab87dbbe042b66f97acb57474834/frozenlist-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62", size = 39676, upload-time = "2025-10-06T05:36:47.8Z" }, + { url = "https://files.pythonhosted.org/packages/d2/5c/3bbfaa920dfab09e76946a5d2833a7cbdf7b9b4a91c714666ac4855b88b4/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94", size = 89235, upload-time = "2025-10-06T05:36:48.78Z" }, + { url = "https://files.pythonhosted.org/packages/d2/d6/f03961ef72166cec1687e84e8925838442b615bd0b8854b54923ce5b7b8a/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c", size = 50742, upload-time = "2025-10-06T05:36:49.837Z" }, + { url = "https://files.pythonhosted.org/packages/1e/bb/a6d12b7ba4c3337667d0e421f7181c82dda448ce4e7ad7ecd249a16fa806/frozenlist-1.8.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52", size = 51725, upload-time = "2025-10-06T05:36:50.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/71/d1fed0ffe2c2ccd70b43714c6cab0f4188f09f8a67a7914a6b46ee30f274/frozenlist-1.8.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51", size = 284533, upload-time = "2025-10-06T05:36:51.898Z" }, + { url = "https://files.pythonhosted.org/packages/c9/1f/fb1685a7b009d89f9bf78a42d94461bc06581f6e718c39344754a5d9bada/frozenlist-1.8.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65", size = 292506, upload-time = "2025-10-06T05:36:53.101Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3b/b991fe1612703f7e0d05c0cf734c1b77aaf7c7d321df4572e8d36e7048c8/frozenlist-1.8.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82", size = 274161, upload-time = "2025-10-06T05:36:54.309Z" }, + { url = "https://files.pythonhosted.org/packages/ca/ec/c5c618767bcdf66e88945ec0157d7f6c4a1322f1473392319b7a2501ded7/frozenlist-1.8.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714", size = 294676, upload-time = "2025-10-06T05:36:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ce/3934758637d8f8a88d11f0585d6495ef54b2044ed6ec84492a91fa3b27aa/frozenlist-1.8.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d", size = 300638, upload-time = "2025-10-06T05:36:56.758Z" }, + { url = "https://files.pythonhosted.org/packages/fc/4f/a7e4d0d467298f42de4b41cbc7ddaf19d3cfeabaf9ff97c20c6c7ee409f9/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506", size = 283067, upload-time = "2025-10-06T05:36:57.965Z" }, + { url = "https://files.pythonhosted.org/packages/dc/48/c7b163063d55a83772b268e6d1affb960771b0e203b632cfe09522d67ea5/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51", size = 292101, upload-time = "2025-10-06T05:36:59.237Z" }, + { url = "https://files.pythonhosted.org/packages/9f/d0/2366d3c4ecdc2fd391e0afa6e11500bfba0ea772764d631bbf82f0136c9d/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e", size = 289901, upload-time = "2025-10-06T05:37:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/b8/94/daff920e82c1b70e3618a2ac39fbc01ae3e2ff6124e80739ce5d71c9b920/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0", size = 289395, upload-time = "2025-10-06T05:37:02.115Z" }, + { url = "https://files.pythonhosted.org/packages/e3/20/bba307ab4235a09fdcd3cc5508dbabd17c4634a1af4b96e0f69bfe551ebd/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41", size = 283659, upload-time = "2025-10-06T05:37:03.711Z" }, + { url = "https://files.pythonhosted.org/packages/fd/00/04ca1c3a7a124b6de4f8a9a17cc2fcad138b4608e7a3fc5877804b8715d7/frozenlist-1.8.0-cp313-cp313t-win32.whl", hash = "sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b", size = 43492, upload-time = "2025-10-06T05:37:04.915Z" }, + { url = "https://files.pythonhosted.org/packages/59/5e/c69f733a86a94ab10f68e496dc6b7e8bc078ebb415281d5698313e3af3a1/frozenlist-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888", size = 48034, upload-time = "2025-10-06T05:37:06.343Z" }, + { url = "https://files.pythonhosted.org/packages/16/6c/be9d79775d8abe79b05fa6d23da99ad6e7763a1d080fbae7290b286093fd/frozenlist-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042", size = 41749, upload-time = "2025-10-06T05:37:07.431Z" }, + { url = "https://files.pythonhosted.org/packages/f1/c8/85da824b7e7b9b6e7f7705b2ecaf9591ba6f79c1177f324c2735e41d36a2/frozenlist-1.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0", size = 86127, upload-time = "2025-10-06T05:37:08.438Z" }, + { url = "https://files.pythonhosted.org/packages/8e/e8/a1185e236ec66c20afd72399522f142c3724c785789255202d27ae992818/frozenlist-1.8.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f", size = 49698, upload-time = "2025-10-06T05:37:09.48Z" }, + { url = "https://files.pythonhosted.org/packages/a1/93/72b1736d68f03fda5fdf0f2180fb6caaae3894f1b854d006ac61ecc727ee/frozenlist-1.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c", size = 49749, upload-time = "2025-10-06T05:37:10.569Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b2/fabede9fafd976b991e9f1b9c8c873ed86f202889b864756f240ce6dd855/frozenlist-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2", size = 231298, upload-time = "2025-10-06T05:37:11.993Z" }, + { url = "https://files.pythonhosted.org/packages/3a/3b/d9b1e0b0eed36e70477ffb8360c49c85c8ca8ef9700a4e6711f39a6e8b45/frozenlist-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8", size = 232015, upload-time = "2025-10-06T05:37:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/dc/94/be719d2766c1138148564a3960fc2c06eb688da592bdc25adcf856101be7/frozenlist-1.8.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686", size = 225038, upload-time = "2025-10-06T05:37:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/e4/09/6712b6c5465f083f52f50cf74167b92d4ea2f50e46a9eea0523d658454ae/frozenlist-1.8.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e", size = 240130, upload-time = "2025-10-06T05:37:15.781Z" }, + { url = "https://files.pythonhosted.org/packages/f8/d4/cd065cdcf21550b54f3ce6a22e143ac9e4836ca42a0de1022da8498eac89/frozenlist-1.8.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a", size = 242845, upload-time = "2025-10-06T05:37:17.037Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/f57a5c8c70cd1ead3d5d5f776f89d33110b1addae0ab010ad774d9a44fb9/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128", size = 229131, upload-time = "2025-10-06T05:37:18.221Z" }, + { url = "https://files.pythonhosted.org/packages/6c/52/232476fe9cb64f0742f3fde2b7d26c1dac18b6d62071c74d4ded55e0ef94/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f", size = 240542, upload-time = "2025-10-06T05:37:19.771Z" }, + { url = "https://files.pythonhosted.org/packages/5f/85/07bf3f5d0fb5414aee5f47d33c6f5c77bfe49aac680bfece33d4fdf6a246/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7", size = 237308, upload-time = "2025-10-06T05:37:20.969Z" }, + { url = "https://files.pythonhosted.org/packages/11/99/ae3a33d5befd41ac0ca2cc7fd3aa707c9c324de2e89db0e0f45db9a64c26/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30", size = 238210, upload-time = "2025-10-06T05:37:22.252Z" }, + { url = "https://files.pythonhosted.org/packages/b2/60/b1d2da22f4970e7a155f0adde9b1435712ece01b3cd45ba63702aea33938/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7", size = 231972, upload-time = "2025-10-06T05:37:23.5Z" }, + { url = "https://files.pythonhosted.org/packages/3f/ab/945b2f32de889993b9c9133216c068b7fcf257d8595a0ac420ac8677cab0/frozenlist-1.8.0-cp314-cp314-win32.whl", hash = "sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806", size = 40536, upload-time = "2025-10-06T05:37:25.581Z" }, + { url = "https://files.pythonhosted.org/packages/59/ad/9caa9b9c836d9ad6f067157a531ac48b7d36499f5036d4141ce78c230b1b/frozenlist-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0", size = 44330, upload-time = "2025-10-06T05:37:26.928Z" }, + { url = "https://files.pythonhosted.org/packages/82/13/e6950121764f2676f43534c555249f57030150260aee9dcf7d64efda11dd/frozenlist-1.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b", size = 40627, upload-time = "2025-10-06T05:37:28.075Z" }, + { url = "https://files.pythonhosted.org/packages/c0/c7/43200656ecc4e02d3f8bc248df68256cd9572b3f0017f0a0c4e93440ae23/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d", size = 89238, upload-time = "2025-10-06T05:37:29.373Z" }, + { url = "https://files.pythonhosted.org/packages/d1/29/55c5f0689b9c0fb765055629f472c0de484dcaf0acee2f7707266ae3583c/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed", size = 50738, upload-time = "2025-10-06T05:37:30.792Z" }, + { url = "https://files.pythonhosted.org/packages/ba/7d/b7282a445956506fa11da8c2db7d276adcbf2b17d8bb8407a47685263f90/frozenlist-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930", size = 51739, upload-time = "2025-10-06T05:37:32.127Z" }, + { url = "https://files.pythonhosted.org/packages/62/1c/3d8622e60d0b767a5510d1d3cf21065b9db874696a51ea6d7a43180a259c/frozenlist-1.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c", size = 284186, upload-time = "2025-10-06T05:37:33.21Z" }, + { url = "https://files.pythonhosted.org/packages/2d/14/aa36d5f85a89679a85a1d44cd7a6657e0b1c75f61e7cad987b203d2daca8/frozenlist-1.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24", size = 292196, upload-time = "2025-10-06T05:37:36.107Z" }, + { url = "https://files.pythonhosted.org/packages/05/23/6bde59eb55abd407d34f77d39a5126fb7b4f109a3f611d3929f14b700c66/frozenlist-1.8.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37", size = 273830, upload-time = "2025-10-06T05:37:37.663Z" }, + { url = "https://files.pythonhosted.org/packages/d2/3f/22cff331bfad7a8afa616289000ba793347fcd7bc275f3b28ecea2a27909/frozenlist-1.8.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a", size = 294289, upload-time = "2025-10-06T05:37:39.261Z" }, + { url = "https://files.pythonhosted.org/packages/a4/89/5b057c799de4838b6c69aa82b79705f2027615e01be996d2486a69ca99c4/frozenlist-1.8.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2", size = 300318, upload-time = "2025-10-06T05:37:43.213Z" }, + { url = "https://files.pythonhosted.org/packages/30/de/2c22ab3eb2a8af6d69dc799e48455813bab3690c760de58e1bf43b36da3e/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef", size = 282814, upload-time = "2025-10-06T05:37:45.337Z" }, + { url = "https://files.pythonhosted.org/packages/59/f7/970141a6a8dbd7f556d94977858cfb36fa9b66e0892c6dd780d2219d8cd8/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe", size = 291762, upload-time = "2025-10-06T05:37:46.657Z" }, + { url = "https://files.pythonhosted.org/packages/c1/15/ca1adae83a719f82df9116d66f5bb28bb95557b3951903d39135620ef157/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8", size = 289470, upload-time = "2025-10-06T05:37:47.946Z" }, + { url = "https://files.pythonhosted.org/packages/ac/83/dca6dc53bf657d371fbc88ddeb21b79891e747189c5de990b9dfff2ccba1/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a", size = 289042, upload-time = "2025-10-06T05:37:49.499Z" }, + { url = "https://files.pythonhosted.org/packages/96/52/abddd34ca99be142f354398700536c5bd315880ed0a213812bc491cff5e4/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e", size = 283148, upload-time = "2025-10-06T05:37:50.745Z" }, + { url = "https://files.pythonhosted.org/packages/af/d3/76bd4ed4317e7119c2b7f57c3f6934aba26d277acc6309f873341640e21f/frozenlist-1.8.0-cp314-cp314t-win32.whl", hash = "sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df", size = 44676, upload-time = "2025-10-06T05:37:52.222Z" }, + { url = "https://files.pythonhosted.org/packages/89/76/c615883b7b521ead2944bb3480398cbb07e12b7b4e4d073d3752eb721558/frozenlist-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd", size = 49451, upload-time = "2025-10-06T05:37:53.425Z" }, + { url = "https://files.pythonhosted.org/packages/e0/a3/5982da14e113d07b325230f95060e2169f5311b1017ea8af2a29b374c289/frozenlist-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79", size = 42507, upload-time = "2025-10-06T05:37:54.513Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2026.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/78/f34251dadb8f3921264a1d9b8946f5e542014ee2614b285261b4e40e6775/fsspec-2026.7.0.tar.gz", hash = "sha256:c803c40f4cf860b49dea58ee3e1c33cb9c790520e233537e1340049f89b82a88", size = 317040, upload-time = "2026-07-28T16:34:51.052Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/3c/6a2bf344106328fd04963664a60b9bb6496fc25df8e962fcdc1367285fb9/fsspec-2026.7.0-py3-none-any.whl", hash = "sha256:b57ddbafedfaef7018c1ecab32aa200a9d7ca26b77965f64e48b70061249d279", size = 206583, upload-time = "2026-07-28T16:34:49.538Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, +] + +[[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 = "google-crc32c" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/41/4b9c02f99e4c5fb477122cd5437403b552873f014616ac1d19ac8221a58d/google_crc32c-1.8.0.tar.gz", hash = "sha256:a428e25fb7691024de47fecfbff7ff957214da51eddded0da0ae0e0f03a2cf79", size = 14192, upload-time = "2025-12-16T00:35:25.142Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/5f/7307325b1198b59324c0fa9807cafb551afb65e831699f2ce211ad5c8240/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:4b8286b659c1335172e39563ab0a768b8015e88e08329fa5321f774275fc3113", size = 31300, upload-time = "2025-12-16T00:21:56.723Z" }, + { url = "https://files.pythonhosted.org/packages/21/8e/58c0d5d86e2220e6a37befe7e6a94dd2f6006044b1a33edf1ff6d9f7e319/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:2a3dc3318507de089c5384cc74d54318401410f82aa65b2d9cdde9d297aca7cb", size = 30867, upload-time = "2025-12-16T00:38:31.302Z" }, + { url = "https://files.pythonhosted.org/packages/ce/a9/a780cc66f86335a6019f557a8aaca8fbb970728f0efd2430d15ff1beae0e/google_crc32c-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14f87e04d613dfa218d6135e81b78272c3b904e2a7053b841481b38a7d901411", size = 33364, upload-time = "2025-12-16T00:40:22.96Z" }, + { url = "https://files.pythonhosted.org/packages/21/3f/3457ea803db0198c9aaca2dd373750972ce28a26f00544b6b85088811939/google_crc32c-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb5c869c2923d56cb0c8e6bcdd73c009c36ae39b652dbe46a05eb4ef0ad01454", size = 33740, upload-time = "2025-12-16T00:40:23.96Z" }, + { url = "https://files.pythonhosted.org/packages/df/c0/87c2073e0c72515bb8733d4eef7b21548e8d189f094b5dad20b0ecaf64f6/google_crc32c-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:3cc0c8912038065eafa603b238abf252e204accab2a704c63b9e14837a854962", size = 34437, upload-time = "2025-12-16T00:35:21.395Z" }, + { url = "https://files.pythonhosted.org/packages/d1/db/000f15b41724589b0e7bc24bc7a8967898d8d3bc8caf64c513d91ef1f6c0/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:3ebb04528e83b2634857f43f9bb8ef5b2bbe7f10f140daeb01b58f972d04736b", size = 31297, upload-time = "2025-12-16T00:23:20.709Z" }, + { url = "https://files.pythonhosted.org/packages/d7/0d/8ebed0c39c53a7e838e2a486da8abb0e52de135f1b376ae2f0b160eb4c1a/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:450dc98429d3e33ed2926fc99ee81001928d63460f8538f21a5d6060912a8e27", size = 30867, upload-time = "2025-12-16T00:43:14.628Z" }, + { url = "https://files.pythonhosted.org/packages/ce/42/b468aec74a0354b34c8cbf748db20d6e350a68a2b0912e128cabee49806c/google_crc32c-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3b9776774b24ba76831609ffbabce8cdf6fa2bd5e9df37b594221c7e333a81fa", size = 33344, upload-time = "2025-12-16T00:40:24.742Z" }, + { url = "https://files.pythonhosted.org/packages/1c/e8/b33784d6fc77fb5062a8a7854e43e1e618b87d5ddf610a88025e4de6226e/google_crc32c-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:89c17d53d75562edfff86679244830599ee0a48efc216200691de8b02ab6b2b8", size = 33694, upload-time = "2025-12-16T00:40:25.505Z" }, + { url = "https://files.pythonhosted.org/packages/92/b1/d3cbd4d988afb3d8e4db94ca953df429ed6db7282ed0e700d25e6c7bfc8d/google_crc32c-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:57a50a9035b75643996fbf224d6661e386c7162d1dfdab9bc4ca790947d1007f", size = 34435, upload-time = "2025-12-16T00:35:22.107Z" }, + { url = "https://files.pythonhosted.org/packages/21/88/8ecf3c2b864a490b9e7010c84fd203ec8cf3b280651106a3a74dd1b0ca72/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:e6584b12cb06796d285d09e33f63309a09368b9d806a551d8036a4207ea43697", size = 31301, upload-time = "2025-12-16T00:24:48.527Z" }, + { url = "https://files.pythonhosted.org/packages/36/c6/f7ff6c11f5ca215d9f43d3629163727a272eabc356e5c9b2853df2bfe965/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:f4b51844ef67d6cf2e9425983274da75f18b1597bb2c998e1c0a0e8d46f8f651", size = 30868, upload-time = "2025-12-16T00:48:12.163Z" }, + { url = "https://files.pythonhosted.org/packages/56/15/c25671c7aad70f8179d858c55a6ae8404902abe0cdcf32a29d581792b491/google_crc32c-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b0d1a7afc6e8e4635564ba8aa5c0548e3173e41b6384d7711a9123165f582de2", size = 33381, upload-time = "2025-12-16T00:40:26.268Z" }, + { url = "https://files.pythonhosted.org/packages/42/fa/f50f51260d7b0ef5d4898af122d8a7ec5a84e2984f676f746445f783705f/google_crc32c-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8b3f68782f3cbd1bce027e48768293072813469af6a61a86f6bb4977a4380f21", size = 33734, upload-time = "2025-12-16T00:40:27.028Z" }, + { url = "https://files.pythonhosted.org/packages/08/a5/7b059810934a09fb3ccb657e0843813c1fee1183d3bc2c8041800374aa2c/google_crc32c-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:d511b3153e7011a27ab6ee6bb3a5404a55b994dc1a7322c0b87b29606d9790e2", size = 34878, upload-time = "2025-12-16T00:35:23.142Z" }, +] + +[[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.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/e4/8d187ea29c2e30b3a09505c567513077d6117861bde1fbd997a167f262ec/griffelib-2.1.0.tar.gz", hash = "sha256:762a186d2c6fd6794d4ea20d428d597ffb857cb56b66421651cbba15bdd5e813", size = 216234, upload-time = "2026-06-19T12:05:42.278Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e4/d3/5268aeabf2ad82658c4e2ff3a060648d0f02f3926cb53247c0e4d0dab49e/griffelib-2.1.0-py3-none-any.whl", hash = "sha256:cc7b3d2d2865ad0b909fcc38086e3f554b5ea7acbaa7bbb7ecaa3f5dfb7d9f00", size = 142560, upload-time = "2026-06-19T12:05:38.742Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpcore2" +version = "2.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, + { name = "truststore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/39/a8/20ed1ed79cbc2ecdf5301c0968ab7c85547212e2a7bd126ddd2d986e206e/httpcore2-2.9.1.tar.gz", hash = "sha256:4d8acbf8b306f48c9d6046591fd5ba4037d1b1b1000d140fc2c3eab1e9a0c0e2", size = 67089, upload-time = "2026-07-24T09:21:03.867Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/fb/46c52b781975c335a2bcf1072c7bbc007cbdc8d674217f5ee1daba2c848b/httpcore2-2.9.1-py3-none-any.whl", hash = "sha256:6182472379e855fe4221246a2bb7ecede403bc61c6798062ae1787d051ccde26", size = 82809, upload-time = "2026-07-24T09:21:01.178Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "httpx2" +version = "2.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpcore2" }, + { name = "idna" }, + { name = "truststore" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/14/38128fbafd7e0ed41d874df6c9a653d47c2d111cfe59e2b4ac95161b4abd/httpx2-2.9.1.tar.gz", hash = "sha256:1932a768737e3666291582833da748cc4e563c337cf96706fccc04fa6e58764a", size = 95458, upload-time = "2026-07-24T09:21:04.972Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/b8/cfd91c4ab9134d386d48f0b6ac662ff3d4be6efdee59ee1c67ebc3c0487c/httpx2-2.9.1-py3-none-any.whl", hash = "sha256:1820fe14a9ab1107bfeff39259987429450b070ec0ff38cc87eb0d8c97fdc71a", size = 91191, upload-time = "2026-07-24T09:21:02.6Z" }, +] + +[[package]] +name = "hypothesis" +version = "6.165.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/7a/7a277ac07776191be594f74f6425649d529e4876f7d3ff1ee96d393ffdbc/hypothesis-6.165.3.tar.gz", hash = "sha256:687c5abb1a9c11478577c2cf18685c0eb82150d278477d3e14da290a1ef2a098", size = 502263, upload-time = "2026-08-11T01:23:09.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/c7/18152acad5f85f91554b2030000319b952a54151509953651ec40f37d50d/hypothesis-6.165.3-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:56af539c811b11ab5475704c300b8f0b46cc6dd0edc267e02a16487e803c77f8", size = 781671, upload-time = "2026-08-11T01:22:09.176Z" }, + { url = "https://files.pythonhosted.org/packages/d3/77/4293ea8a7fdb713956a8bf460b9070115df69f8216a900507633f9cdb225/hypothesis-6.165.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:f40c10cfdb1ea2cd75e5d4e6e0cfdcb6198ab8406e8922666480e6dc11eea341", size = 777291, upload-time = "2026-08-11T01:22:15.991Z" }, + { url = "https://files.pythonhosted.org/packages/02/fa/fa2071a6afaefc082dc7a033f41ae61436caf442d5973ba8ca9c29a69460/hypothesis-6.165.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a0854b1de4577f7e1beb1d681360285b5d678b65a809787ff4eab5b8b25efca", size = 1106490, upload-time = "2026-08-11T01:22:07.858Z" }, + { url = "https://files.pythonhosted.org/packages/ba/86/de724b7f9cd10e3be4efa21770457172e549d7576b1d8e29d6177eef5e47/hypothesis-6.165.3-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:360991cda8e488924905af48949033b90d4877ac97b9ad5d826d4d0f5a4b8cfb", size = 1135054, upload-time = "2026-08-11T01:22:29.499Z" }, + { url = "https://files.pythonhosted.org/packages/12/6a/96721cf447bd3c64b5e6843dde4444b20f3ddd901ad366cc73d0e7314bf5/hypothesis-6.165.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf502000f4a8ef4c9ab9493ca3b4fe17ae3033c18a8e2a31cdd69515dc7d97be", size = 1155997, upload-time = "2026-08-11T01:21:48.496Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/a793cce6497f233b155f97684bf7d0e424c25613dd87b8af8a4e87820232/hypothesis-6.165.3-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:b9fcf47ad18f87f7c15bd36289bd45708bbfd250129d73bf554653e2f9afc931", size = 1111326, upload-time = "2026-08-11T01:22:21.9Z" }, + { url = "https://files.pythonhosted.org/packages/28/8d/dc3cdfd55843d038effa2458a9c9bd73002218a8c0fd58c2c0ab7fa328db/hypothesis-6.165.3-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2fb05529cbcab5a317d03d7bb0e90d382f79ef1643e3568577916d0e24bfe70b", size = 1148079, upload-time = "2026-08-11T01:21:51.071Z" }, + { url = "https://files.pythonhosted.org/packages/db/4b/2f62924ac41f3d3482b29ded4c213f27ff4a103e56e84eeb528d4900cac7/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:57eae10a64340cd621a78eae9cb0459bd68ea99fbaa933c4f00e34d5087b6376", size = 1281862, upload-time = "2026-08-11T01:21:39.274Z" }, + { url = "https://files.pythonhosted.org/packages/7e/d4/01c78b7b7348b6e8cef9b999109dfb93b14c7e1e38bc22170129f8b17181/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:19df0f2239052e9a870634a1d9bcdff95e2a2ab508573e5dd5c3d1ca545f5b3c", size = 1408437, upload-time = "2026-08-11T01:22:13.243Z" }, + { url = "https://files.pythonhosted.org/packages/35/76/e940b5a5aaf75bcd4784f1f3f9bf2b9a642a706bc0a9639077ca84f1325f/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:9781a8026adff4b4516404cf0e5f2cadcb471318c2882a264e1c57c4c092266f", size = 1281168, upload-time = "2026-08-11T01:21:58.964Z" }, + { url = "https://files.pythonhosted.org/packages/fc/84/b153e81a614f45e0902e3b9e8a8b079e64214c50abb6fbe9acc62ccf686d/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1dd7e05f88e3e108a5e4f5f71a3eaf205559e8951e3c1f1ffd04cea82ed3b731", size = 1323263, upload-time = "2026-08-11T01:21:52.374Z" }, + { url = "https://files.pythonhosted.org/packages/fb/5f/e5144d9e91ab7260650cb1ee032ca23208d49ebb1334845baf6407c1a9d9/hypothesis-6.165.3-cp310-abi3-win32.whl", hash = "sha256:d1389bda38cb222acc109aef5b31643ce799a39a76294a50ad8b84e32f92d76d", size = 667499, upload-time = "2026-08-11T01:21:47.36Z" }, + { url = "https://files.pythonhosted.org/packages/a9/18/f008b6f1f1c293d51c2776f8815d95bccb777dcf87df2a0ab56b273b47dc/hypothesis-6.165.3-cp310-abi3-win_amd64.whl", hash = "sha256:10cda6988ca4b1da389548b6fdd71af236b588a601fc1757e56eb8988e4240d8", size = 673643, upload-time = "2026-08-11T01:22:46.975Z" }, + { url = "https://files.pythonhosted.org/packages/e2/3d/e7eade134bd7f57d4071d82ae84691bc3017fe6945af0bb149578ba8b565/hypothesis-6.165.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:f88fe4915f8dd4f8999a197f9e22c3a7177042aa994d35c0c7c7b22541d2885b", size = 783298, upload-time = "2026-08-11T01:22:14.706Z" }, + { url = "https://files.pythonhosted.org/packages/d6/a5/668810f493feaf886a9240ad689792fb32450667c8e5770c3bcaa7fabeac/hypothesis-6.165.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c7d9f6c36b812f6069c7436492e12812cf541391954e21d5bd7fcafc9fb46700", size = 774856, upload-time = "2026-08-11T01:22:35.836Z" }, + { url = "https://files.pythonhosted.org/packages/e4/a0/0af93a70f5128763079ab714277ccad4a7de42d442d67dd43e3029178162/hypothesis-6.165.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:423ca8e30087bb41db7e6f47dbf98690a2155241b9f1057e366dc138d7dcc4fe", size = 1105274, upload-time = "2026-08-11T01:23:03.591Z" }, + { url = "https://files.pythonhosted.org/packages/7b/00/ddcdc99beee469573addf5cfcd817c9a20a71832b1ca88404b6d3f99c44c/hypothesis-6.165.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c58c66f3e1b8d4091bb52664d5af4b0c1715293c6822d5344b166494534cd498", size = 1155379, upload-time = "2026-08-11T01:22:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/de/10/d574b21e63f16a1cad9c0cf4592aa170285940f034d04bb33a1e08025397/hypothesis-6.165.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3774882c4685e5474b7940697da55963e591b71c6dce593d90ac4128766371ad", size = 1279259, upload-time = "2026-08-11T01:21:53.63Z" }, + { url = "https://files.pythonhosted.org/packages/b9/3f/13f6b6c7d7d0b9bb570a18617eb659b015c312b1d8d1d3aaf9f2edea9628/hypothesis-6.165.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb3a397a5422c67387f4408989dbdfc2b1e0306f883f2aa79b9472c80958464", size = 1322605, upload-time = "2026-08-11T01:21:42.853Z" }, + { url = "https://files.pythonhosted.org/packages/6c/dd/243317f5fb8497601dc65d3ded984834eb5f36b8ec59e7853ef753ec0ee1/hypothesis-6.165.3-cp312-cp312-win_amd64.whl", hash = "sha256:dbb74811d54b6317ba0d2047aad269c09afefaa25d1849f8f33f80a638b0c3af", size = 670812, upload-time = "2026-08-11T01:22:50.245Z" }, + { url = "https://files.pythonhosted.org/packages/03/3e/95cba31dbe775b99a4548cdae192e1ad15cee7b64fbdfe6cd4c9d00031b4/hypothesis-6.165.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:447f139d6dd70a5d8b178ef507463fb0430ace9ce42e3b2351d2803a391fe774", size = 783183, upload-time = "2026-08-11T01:22:45.286Z" }, + { url = "https://files.pythonhosted.org/packages/56/0e/51bf125cdf7855b69097b8f59c73ef3cf5f4e3d68a16e808d2d1f08a1ff1/hypothesis-6.165.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6152c718606f1705e673c6b30a6ebd3ff08d340da85291dd3c432c73b28a9b3a", size = 774820, upload-time = "2026-08-11T01:22:24.825Z" }, + { url = "https://files.pythonhosted.org/packages/0a/69/b954f742b97441a5c49f8f8704826ee0637a6cce3a7d06ce85fbefc54ac5/hypothesis-6.165.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27fe7826ad83ccc2e8062f0fab43b137bab34cef1a149a926b34a7b8382ee22c", size = 1105186, upload-time = "2026-08-11T01:21:41.733Z" }, + { url = "https://files.pythonhosted.org/packages/6e/8a/33e41d9cc1be7661e0b4129c225a93c3f12544714300aadb95ae7eedf894/hypothesis-6.165.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a1ff92876a324f7b9cdb92cedf103e380b7a12aa7df55ebcb16dd0f495a879e8", size = 1155215, upload-time = "2026-08-11T01:22:06.604Z" }, + { url = "https://files.pythonhosted.org/packages/ee/53/ba09526c9100ace5752908ac7251d2dc3960ce7e0e97a31152aaa26c33ee/hypothesis-6.165.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:53f1564c97d27fc109f212404d49cd71d7789777dbe0685628ffe9838df56240", size = 1279245, upload-time = "2026-08-11T01:21:56.182Z" }, + { url = "https://files.pythonhosted.org/packages/c1/93/fc637d355791a65364a3409ff06ade7ba5d3fc6f1d07a729781dec315fa0/hypothesis-6.165.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:788a9b0a7aae719a2b71a1c2f07e51deb1d0fe990164a9090c686833ed4bfbad", size = 1322370, upload-time = "2026-08-11T01:22:48.492Z" }, + { url = "https://files.pythonhosted.org/packages/b6/8d/826053ba0263143fed2b0e8af009dc868d8a932e7246e191deb8ca7ce8ff/hypothesis-6.165.3-cp313-cp313-win_amd64.whl", hash = "sha256:37830f0795abfdf738d2a5b6f829a73f3ab498de45a2e61b0bf3bd38d8c9ddb9", size = 670804, upload-time = "2026-08-11T01:22:00.103Z" }, + { url = "https://files.pythonhosted.org/packages/e7/27/3230f8de3d853b2b547731916ae1d1026bd197cd3f2d35dafc0b445da46b/hypothesis-6.165.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:38826441dbf528cc156388d0a05526086a12da3e1348353d3fa14de03e57c4b2", size = 783286, upload-time = "2026-08-11T01:22:40.816Z" }, + { url = "https://files.pythonhosted.org/packages/6c/28/9f9ca830d376c50babe55c616f6d99eea886c6ebcd8b512dcd5d56f9e40c/hypothesis-6.165.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:87490115edd34a246a4ba8b1144cbdf571438c46c406ece05caf65908667c9a9", size = 774963, upload-time = "2026-08-11T01:23:05.409Z" }, + { url = "https://files.pythonhosted.org/packages/33/3c/3c81f08ec1edce160da509c5785d78c0e25a7913899c4b9ff724bfd01420/hypothesis-6.165.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f51f4346cfa26bca68c68f7bbbd2b1812208bc9f572187c95ecab080ed402153", size = 1105730, upload-time = "2026-08-11T01:22:42.311Z" }, + { url = "https://files.pythonhosted.org/packages/bf/b5/f6f81b9aec9999ec63920d168617cab67a038be05487eff3410ccd072bfe/hypothesis-6.165.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4da89eb4b36b3260ff714d2ecc3274b9bd599fd96687d2d9ed53d5e1a801a7a7", size = 1155383, upload-time = "2026-08-11T01:21:57.58Z" }, + { url = "https://files.pythonhosted.org/packages/dd/27/7f3a8c6101675bf95c80cd8c9173d65892ca0b7b640551156dc4537fab1f/hypothesis-6.165.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eb6d31c14d7bdfe03e501d88ee296c149a74cc93e3d01c76ea335e64ee5f33ec", size = 1279606, upload-time = "2026-08-11T01:22:37.56Z" }, + { url = "https://files.pythonhosted.org/packages/d9/16/0c23e06a24e421e532f62a95021fae34f685f3a194c081c6991b4ab202b3/hypothesis-6.165.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0863e1a9258bc103abe616fa9471cfa66a1535ea404dd8a0bf360e0a29502397", size = 1322697, upload-time = "2026-08-11T01:22:27.857Z" }, + { url = "https://files.pythonhosted.org/packages/dc/56/8356dadf45e5c635b46aa2b57fa74f3210250a8e38b860b6b75f50ed0b42/hypothesis-6.165.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:53c56155f2cfbb45ec97fef9ea3b8453b4a34c48c3c5cacee16f97dd2a037994", size = 614859, upload-time = "2026-08-11T01:22:01.304Z" }, + { url = "https://files.pythonhosted.org/packages/e3/79/124d4faf235219acd685c359760a5cb3995609bc50ce465e54c3249841ee/hypothesis-6.165.3-cp314-cp314-win_amd64.whl", hash = "sha256:c48f41e950b5e602e2fdf8f92dcc8ac7bf715a003bf822afb7c9d5cbc41bc344", size = 670600, upload-time = "2026-08-11T01:22:10.356Z" }, + { url = "https://files.pythonhosted.org/packages/01/7a/41ac5e68d9ce079d1b76d4c54126354df61b948c3d519d1289aca877eedc/hypothesis-6.165.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:9563d3040178fb1f522665bcec6458cc0d21ab77d7c637058a8be4ea8c01d236", size = 781746, upload-time = "2026-08-11T01:22:34.472Z" }, + { url = "https://files.pythonhosted.org/packages/5d/fb/7ecc21aae63a83dbc8036f9a0544c6b3d798db566b97b5202bdf8e770f80/hypothesis-6.165.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1fe1783543b43ba9808c016950e5e84b3804dc3365ba77c37c427b5896a558a1", size = 773382, upload-time = "2026-08-11T01:22:55.279Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f2/9cc2a4768f9a483b12e307ba585f5eb9c7f5500bd16ff82ddbf62a9a1b88/hypothesis-6.165.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9ea34806a4df4e8305a096dcf8e53cdd903c96c1e0d2dd5b001d2283f639c3f1", size = 1103911, upload-time = "2026-08-11T01:23:00.286Z" }, + { url = "https://files.pythonhosted.org/packages/54/9e/b551a494f84976ee5bb9374c197ccc126dea2ec6f22098d5f70705237473/hypothesis-6.165.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d188454b95ce46ba991e3c52161255d76af25170ad28591f6b30b045e501216e", size = 1154060, upload-time = "2026-08-11T01:22:20.413Z" }, + { url = "https://files.pythonhosted.org/packages/69/37/8e22a236f1f1e599525549a34672fb0523109f571486fe209b12a84a942e/hypothesis-6.165.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:a1c47b15ce97a9b1346bc7d7013c5f215380f78ae01c0f73a1638bd8b98bdd76", size = 1277631, upload-time = "2026-08-11T01:22:30.965Z" }, + { url = "https://files.pythonhosted.org/packages/13/0f/feb33bfc23853b4ba6360ff5e34235cd8bea0d7dd1eb21e17491f581c4e2/hypothesis-6.165.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:996077ef7a3bb332b6638f698ddf7555c82784b58dde80eeba3f07c0a322b40f", size = 1321326, upload-time = "2026-08-11T01:21:45.089Z" }, + { url = "https://files.pythonhosted.org/packages/9f/3b/ad56b56540a0719f493edec0dd442ebb21272147d2482ef505d19760a6d3/hypothesis-6.165.3-cp314-cp314t-win_amd64.whl", hash = "sha256:57a8273bdafe3f450afe66999fd130d4935d775eaf4ef63fcac0bee8015fc512", size = 670613, upload-time = "2026-08-11T01:22:05.294Z" }, +] + +[[package]] +name = "idna" +version = "3.18" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "ipykernel" +version = "7.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "appnope", marker = "sys_platform == 'darwin'" }, + { name = "comm" }, + { name = "debugpy" }, + { name = "ipython" }, + { name = "jupyter-client" }, + { name = "jupyter-core" }, + { name = "matplotlib-inline" }, + { name = "nest-asyncio2" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyzmq" }, + { name = "tornado" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/c4/e4a38f579de4225a561305666f7541cdabb30075def2aa1ac17bd73c1fb5/ipykernel-7.3.0.tar.gz", hash = "sha256:9acaaaf97d16355166e4085afe9d225bfbdf2b7ef520f9df3be8f2b248275e09", size = 184899, upload-time = "2026-06-10T08:41:25.481Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3d/02/77b271f5dc58bfbc0b577c877b2365d1ffea2afe66a80c13f2312820348c/ipykernel-7.3.0-py3-none-any.whl", hash = "sha256:897eb64da762549ef610698fca5e9675195ec6ac8ec7f19d81ce1ca20c876057", size = 120583, upload-time = "2026-06-10T08:41:23.648Z" }, +] + +[[package]] +name = "ipython" +version = "9.16.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ipython-pygments-lexers" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/96/b150fe7e25a5a29ae9ac1374e71488639605d39a1ea4abb74c9ce33af235/ipython-9.16.1.tar.gz", hash = "sha256:5a3d1f9a47ff216d6cf9cf863124f6a2c1a198d1354c546a4d24a370a283b64c", size = 4515302, upload-time = "2026-08-03T08:36:15.571Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/8e/1239df488393d61076653bfb29f759d0f60cab8e030abdf7c17c31539b51/ipython-9.16.1-py3-none-any.whl", hash = "sha256:4acae635506f6d352d94c4899a19d5f85f8bc4d230932342dca556fdab1c69b4", size = 625974, upload-time = "2026-08-03T08:36:13.654Z" }, +] + +[[package]] +name = "ipython-pygments-lexers" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" }, +] + +[[package]] +name = "jedi" +version = "0.20.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "parso" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/46/b7/a3635f6a2d7cf5b5dd98064fc1d5fbbafcb25477bcea204a3a92145d158b/jedi-0.20.0.tar.gz", hash = "sha256:c3f4ccbd276696f4b19c54618d4fb18f9fc24b0aef02acf704b23f487daa1011", size = 3119416, upload-time = "2026-05-01T23:38:47.814Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/93/242e2eab5fe682ffcb8b0084bde703a41d51e17ee0f3a31ff0d9d813620a/jedi-0.20.0-py2.py3-none-any.whl", hash = "sha256:7bdd9c2634f56713299976f4cbd59cb3fa92165cc5e05ea811fb253480728b67", size = 4884812, upload-time = "2026-05-01T23:38:43.919Z" }, +] + +[[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 = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + +[[package]] +name = "jupyter-client" +version = "8.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jupyter-core" }, + { name = "python-dateutil" }, + { name = "pyzmq" }, + { name = "tornado" }, + { name = "traitlets" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/dc/5512503b088997c2250b8bf18258fba9d9ce5ead641183700960d3c9d342/jupyter_client-8.9.1.tar.gz", hash = "sha256:a58f730dd9e728ba16ba1d62ebccf7ffe1ebbdbce4e95cfae941b7321ae1f4fa", size = 359256, upload-time = "2026-06-09T13:15:01.033Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/6f/56d39bf385c5c27988aebaf0c18a2a17e960575740100973511018bd904e/jupyter_client-8.9.1-py3-none-any.whl", hash = "sha256:0b7a295bc46e8751e9adae84781f726c851c1d911bd793edc4a3bde942e3da81", size = 109828, upload-time = "2026-06-09T13:14:58.835Z" }, +] + +[[package]] +name = "jupyter-core" +version = "5.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "platformdirs" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/02/49/9d1284d0dc65e2c757b74c6687b6d319b02f822ad039e5c512df9194d9dd/jupyter_core-5.9.1.tar.gz", hash = "sha256:4d09aaff303b9566c3ce657f580bd089ff5c91f5f89cf7d8846c3cdf465b5508", size = 89814, upload-time = "2025-10-16T19:19:18.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/e7/80988e32bf6f73919a113473a604f5a8f09094de312b9d52b79c2df7612b/jupyter_core-5.9.1-py3-none-any.whl", hash = "sha256:ebf87fdc6073d142e114c72c9e29a9d7ca03fad818c5d300ce2adc1fb0743407", size = 29032, upload-time = "2025-10-16T19:19:16.783Z" }, +] + +[[package]] +name = "markdown" +version = "3.10.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/29/6f/da4c6aea59b3001f2e8c0ec7497475aadaf3b021c10cab5b2858f0f32b26/markdown-3.10.3.tar.gz", hash = "sha256:3589362618f743188b4d955b874402bc814f4f83f544dc207719f4baa7d9c45f", size = 372596, upload-time = "2026-07-30T19:05:29.005Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/69/4a5af2bc115a9a33fefe51709749de8262be3f9ba063d1753a837cdbc49c/markdown-3.10.3-py3-none-any.whl", hash = "sha256:fa6c92a00a4a3c98b22728c64a935ae1928250ae65058a6ded814d2cc29a4cea", size = 110757, upload-time = "2026-07-30T19:05:27.883Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[package]] +name = "matplotlib-inline" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" }, +] + +[[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.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/c0/f641843de3f612a6b48253f39244165acff36657a91cc903633d456ae1ac/mkdocs_autorefs-1.4.4.tar.gz", hash = "sha256:d54a284f27a7346b9c38f1f852177940c222da508e66edc816a0fa55fc6da197", size = 56588, upload-time = "2026-02-10T15:23:55.105Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/de/a3e710469772c6a89595fc52816da05c1e164b4c866a89e3cb82fb1b67c5/mkdocs_autorefs-1.4.4-py3-none-any.whl", hash = "sha256:834ef5408d827071ad1bc69e0f39704fa34c7fc05bc8e1c72b227dfdc5c76089", size = 25530, upload-time = "2026-02-10T15:23:53.817Z" }, +] + +[[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.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/b6/e858701499d57eee8b3fd8e78168083956c6683ddbe727b46758b19e1119/mkdocstrings_python-2.0.5.tar.gz", hash = "sha256:3a4d92556ad39637e88af94a5374213af9a8e3040c3824ceaed04b486c017594", size = 199578, upload-time = "2026-06-19T10:41:08.868Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/fc/10ab7e80650a9c9e8f4f1105f8c8e73567f88ed0c06ada589ab81d38687c/mkdocstrings_python-2.0.5-py3-none-any.whl", hash = "sha256:30c837bbff016549f659fcba6539ac351303f0fd7e713c89a040611072236e9d", size = 104951, upload-time = "2026-06-19T10:41:07.378Z" }, +] + +[[package]] +name = "multidict" +version = "6.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1a/c2/c2d94cbe6ac1753f3fc980da97b3d930efe1da3af3c9f5125354436c073d/multidict-6.7.1.tar.gz", hash = "sha256:ec6652a1bee61c53a3e5776b6049172c53b6aaba34f18c9ad04f82712bac623d", size = 102010, upload-time = "2026-01-26T02:46:45.979Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8d/9c/f20e0e2cf80e4b2e4b1c365bf5fe104ee633c751a724246262db8f1a0b13/multidict-6.7.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a90f75c956e32891a4eda3639ce6dd86e87105271f43d43442a3aedf3cddf172", size = 76893, upload-time = "2026-01-26T02:43:52.754Z" }, + { url = "https://files.pythonhosted.org/packages/fe/cf/18ef143a81610136d3da8193da9d80bfe1cb548a1e2d1c775f26b23d024a/multidict-6.7.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fccb473e87eaa1382689053e4a4618e7ba7b9b9b8d6adf2027ee474597128cd", size = 45456, upload-time = "2026-01-26T02:43:53.893Z" }, + { url = "https://files.pythonhosted.org/packages/a9/65/1caac9d4cd32e8433908683446eebc953e82d22b03d10d41a5f0fefe991b/multidict-6.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b0fa96985700739c4c7853a43c0b3e169360d6855780021bfc6d0f1ce7c123e7", size = 43872, upload-time = "2026-01-26T02:43:55.041Z" }, + { url = "https://files.pythonhosted.org/packages/cf/3b/d6bd75dc4f3ff7c73766e04e705b00ed6dbbaccf670d9e05a12b006f5a21/multidict-6.7.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cb2a55f408c3043e42b40cc8eecd575afa27b7e0b956dfb190de0f8499a57a53", size = 251018, upload-time = "2026-01-26T02:43:56.198Z" }, + { url = "https://files.pythonhosted.org/packages/fd/80/c959c5933adedb9ac15152e4067c702a808ea183a8b64cf8f31af8ad3155/multidict-6.7.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb0ce7b2a32d09892b3dd6cc44877a0d02a33241fafca5f25c8b6b62374f8b75", size = 258883, upload-time = "2026-01-26T02:43:57.499Z" }, + { url = "https://files.pythonhosted.org/packages/86/85/7ed40adafea3d4f1c8b916e3b5cc3a8e07dfcdcb9cd72800f4ed3ca1b387/multidict-6.7.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c3a32d23520ee37bf327d1e1a656fec76a2edd5c038bf43eddfa0572ec49c60b", size = 242413, upload-time = "2026-01-26T02:43:58.755Z" }, + { url = "https://files.pythonhosted.org/packages/d2/57/b8565ff533e48595503c785f8361ff9a4fde4d67de25c207cd0ba3befd03/multidict-6.7.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c90fed18bffc0189ba814749fdcc102b536e83a9f738a9003e569acd540a733", size = 268404, upload-time = "2026-01-26T02:44:00.216Z" }, + { url = "https://files.pythonhosted.org/packages/e0/50/9810c5c29350f7258180dfdcb2e52783a0632862eb334c4896ac717cebcb/multidict-6.7.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:da62917e6076f512daccfbbde27f46fed1c98fee202f0559adec8ee0de67f71a", size = 269456, upload-time = "2026-01-26T02:44:02.202Z" }, + { url = "https://files.pythonhosted.org/packages/f3/8d/5e5be3ced1d12966fefb5c4ea3b2a5b480afcea36406559442c6e31d4a48/multidict-6.7.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bfde23ef6ed9db7eaee6c37dcec08524cb43903c60b285b172b6c094711b3961", size = 256322, upload-time = "2026-01-26T02:44:03.56Z" }, + { url = "https://files.pythonhosted.org/packages/31/6e/d8a26d81ac166a5592782d208dd90dfdc0a7a218adaa52b45a672b46c122/multidict-6.7.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3758692429e4e32f1ba0df23219cd0b4fc0a52f476726fff9337d1a57676a582", size = 253955, upload-time = "2026-01-26T02:44:04.845Z" }, + { url = "https://files.pythonhosted.org/packages/59/4c/7c672c8aad41534ba619bcd4ade7a0dc87ed6b8b5c06149b85d3dd03f0cd/multidict-6.7.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:398c1478926eca669f2fd6a5856b6de9c0acf23a2cb59a14c0ba5844fa38077e", size = 251254, upload-time = "2026-01-26T02:44:06.133Z" }, + { url = "https://files.pythonhosted.org/packages/7b/bd/84c24de512cbafbdbc39439f74e967f19570ce7924e3007174a29c348916/multidict-6.7.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c102791b1c4f3ab36ce4101154549105a53dc828f016356b3e3bcae2e3a039d3", size = 252059, upload-time = "2026-01-26T02:44:07.518Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ba/f5449385510825b73d01c2d4087bf6d2fccc20a2d42ac34df93191d3dd03/multidict-6.7.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a088b62bd733e2ad12c50dad01b7d0166c30287c166e137433d3b410add807a6", size = 263588, upload-time = "2026-01-26T02:44:09.382Z" }, + { url = "https://files.pythonhosted.org/packages/d7/11/afc7c677f68f75c84a69fe37184f0f82fce13ce4b92f49f3db280b7e92b3/multidict-6.7.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d51ff4785d58d3f6c91bdbffcb5e1f7ddfda557727043aa20d20ec4f65e324a", size = 259642, upload-time = "2026-01-26T02:44:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/2b/17/ebb9644da78c4ab36403739e0e6e0e30ebb135b9caf3440825001a0bddcb/multidict-6.7.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc5907494fccf3e7d3f94f95c91d6336b092b5fc83811720fae5e2765890dfba", size = 251377, upload-time = "2026-01-26T02:44:12.042Z" }, + { url = "https://files.pythonhosted.org/packages/ca/a4/840f5b97339e27846c46307f2530a2805d9d537d8b8bd416af031cad7fa0/multidict-6.7.1-cp312-cp312-win32.whl", hash = "sha256:28ca5ce2fd9716631133d0e9a9b9a745ad7f60bac2bccafb56aa380fc0b6c511", size = 41887, upload-time = "2026-01-26T02:44:14.245Z" }, + { url = "https://files.pythonhosted.org/packages/80/31/0b2517913687895f5904325c2069d6a3b78f66cc641a86a2baf75a05dcbb/multidict-6.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcee94dfbd638784645b066074b338bc9cc155d4b4bffa4adce1615c5a426c19", size = 46053, upload-time = "2026-01-26T02:44:15.371Z" }, + { url = "https://files.pythonhosted.org/packages/0c/5b/aba28e4ee4006ae4c7df8d327d31025d760ffa992ea23812a601d226e682/multidict-6.7.1-cp312-cp312-win_arm64.whl", hash = "sha256:ba0a9fb644d0c1a2194cf7ffb043bd852cea63a57f66fbd33959f7dae18517bf", size = 43307, upload-time = "2026-01-26T02:44:16.852Z" }, + { url = "https://files.pythonhosted.org/packages/f2/22/929c141d6c0dba87d3e1d38fbdf1ba8baba86b7776469f2bc2d3227a1e67/multidict-6.7.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2b41f5fed0ed563624f1c17630cb9941cf2309d4df00e494b551b5f3e3d67a23", size = 76174, upload-time = "2026-01-26T02:44:18.509Z" }, + { url = "https://files.pythonhosted.org/packages/c7/75/bc704ae15fee974f8fccd871305e254754167dce5f9e42d88a2def741a1d/multidict-6.7.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:84e61e3af5463c19b67ced91f6c634effb89ef8bfc5ca0267f954451ed4bb6a2", size = 45116, upload-time = "2026-01-26T02:44:19.745Z" }, + { url = "https://files.pythonhosted.org/packages/79/76/55cd7186f498ed080a18440c9013011eb548f77ae1b297206d030eb1180a/multidict-6.7.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:935434b9853c7c112eee7ac891bc4cb86455aa631269ae35442cb316790c1445", size = 43524, upload-time = "2026-01-26T02:44:21.571Z" }, + { url = "https://files.pythonhosted.org/packages/e9/3c/414842ef8d5a1628d68edee29ba0e5bcf235dbfb3ccd3ea303a7fe8c72ff/multidict-6.7.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:432feb25a1cb67fe82a9680b4d65fb542e4635cb3166cd9c01560651ad60f177", size = 249368, upload-time = "2026-01-26T02:44:22.803Z" }, + { url = "https://files.pythonhosted.org/packages/f6/32/befed7f74c458b4a525e60519fe8d87eef72bb1e99924fa2b0f9d97a221e/multidict-6.7.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e82d14e3c948952a1a85503817e038cba5905a3352de76b9a465075d072fba23", size = 256952, upload-time = "2026-01-26T02:44:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/03/d6/c878a44ba877f366630c860fdf74bfb203c33778f12b6ac274936853c451/multidict-6.7.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4cfb48c6ea66c83bcaaf7e4dfa7ec1b6bbcf751b7db85a328902796dfde4c060", size = 240317, upload-time = "2026-01-26T02:44:25.772Z" }, + { url = "https://files.pythonhosted.org/packages/68/49/57421b4d7ad2e9e60e25922b08ceb37e077b90444bde6ead629095327a6f/multidict-6.7.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1d540e51b7e8e170174555edecddbd5538105443754539193e3e1061864d444d", size = 267132, upload-time = "2026-01-26T02:44:27.648Z" }, + { url = "https://files.pythonhosted.org/packages/b7/fe/ec0edd52ddbcea2a2e89e174f0206444a61440b40f39704e64dc807a70bd/multidict-6.7.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:273d23f4b40f3dce4d6c8a821c741a86dec62cded82e1175ba3d99be128147ed", size = 268140, upload-time = "2026-01-26T02:44:29.588Z" }, + { url = "https://files.pythonhosted.org/packages/b0/73/6e1b01cbeb458807aa0831742232dbdd1fa92bfa33f52a3f176b4ff3dc11/multidict-6.7.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d624335fd4fa1c08a53f8b4be7676ebde19cd092b3895c421045ca87895b429", size = 254277, upload-time = "2026-01-26T02:44:30.902Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b2/5fb8c124d7561a4974c342bc8c778b471ebbeb3cc17df696f034a7e9afe7/multidict-6.7.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:12fad252f8b267cc75b66e8fc51b3079604e8d43a75428ffe193cd9e2195dfd6", size = 252291, upload-time = "2026-01-26T02:44:32.31Z" }, + { url = "https://files.pythonhosted.org/packages/5a/96/51d4e4e06bcce92577fcd488e22600bd38e4fd59c20cb49434d054903bd2/multidict-6.7.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:03ede2a6ffbe8ef936b92cb4529f27f42be7f56afcdab5ab739cd5f27fb1cbf9", size = 250156, upload-time = "2026-01-26T02:44:33.734Z" }, + { url = "https://files.pythonhosted.org/packages/db/6b/420e173eec5fba721a50e2a9f89eda89d9c98fded1124f8d5c675f7a0c0f/multidict-6.7.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:90efbcf47dbe33dcf643a1e400d67d59abeac5db07dc3f27d6bdeae497a2198c", size = 249742, upload-time = "2026-01-26T02:44:35.222Z" }, + { url = "https://files.pythonhosted.org/packages/44/a3/ec5b5bd98f306bc2aa297b8c6f11a46714a56b1e6ef5ebda50a4f5d7c5fb/multidict-6.7.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5c4b9bfc148f5a91be9244d6264c53035c8a0dcd2f51f1c3c6e30e30ebaa1c84", size = 262221, upload-time = "2026-01-26T02:44:36.604Z" }, + { url = "https://files.pythonhosted.org/packages/cd/f7/e8c0d0da0cd1e28d10e624604e1a36bcc3353aaebdfdc3a43c72bc683a12/multidict-6.7.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:401c5a650f3add2472d1d288c26deebc540f99e2fb83e9525007a74cd2116f1d", size = 258664, upload-time = "2026-01-26T02:44:38.008Z" }, + { url = "https://files.pythonhosted.org/packages/52/da/151a44e8016dd33feed44f730bd856a66257c1ee7aed4f44b649fb7edeb3/multidict-6.7.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:97891f3b1b3ffbded884e2916cacf3c6fc87b66bb0dde46f7357404750559f33", size = 249490, upload-time = "2026-01-26T02:44:39.386Z" }, + { url = "https://files.pythonhosted.org/packages/87/af/a3b86bf9630b732897f6fc3f4c4714b90aa4361983ccbdcd6c0339b21b0c/multidict-6.7.1-cp313-cp313-win32.whl", hash = "sha256:e1c5988359516095535c4301af38d8a8838534158f649c05dd1050222321bcb3", size = 41695, upload-time = "2026-01-26T02:44:41.318Z" }, + { url = "https://files.pythonhosted.org/packages/b2/35/e994121b0e90e46134673422dd564623f93304614f5d11886b1b3e06f503/multidict-6.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:960c83bf01a95b12b08fd54324a4eb1d5b52c88932b5cba5d6e712bb3ed12eb5", size = 45884, upload-time = "2026-01-26T02:44:42.488Z" }, + { url = "https://files.pythonhosted.org/packages/ca/61/42d3e5dbf661242a69c97ea363f2d7b46c567da8eadef8890022be6e2ab0/multidict-6.7.1-cp313-cp313-win_arm64.whl", hash = "sha256:563fe25c678aaba333d5399408f5ec3c383ca5b663e7f774dd179a520b8144df", size = 43122, upload-time = "2026-01-26T02:44:43.664Z" }, + { url = "https://files.pythonhosted.org/packages/6d/b3/e6b21c6c4f314bb956016b0b3ef2162590a529b84cb831c257519e7fde44/multidict-6.7.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:c76c4bec1538375dad9d452d246ca5368ad6e1c9039dadcf007ae59c70619ea1", size = 83175, upload-time = "2026-01-26T02:44:44.894Z" }, + { url = "https://files.pythonhosted.org/packages/fb/76/23ecd2abfe0957b234f6c960f4ade497f55f2c16aeb684d4ecdbf1c95791/multidict-6.7.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:57b46b24b5d5ebcc978da4ec23a819a9402b4228b8a90d9c656422b4bdd8a963", size = 48460, upload-time = "2026-01-26T02:44:46.106Z" }, + { url = "https://files.pythonhosted.org/packages/c4/57/a0ed92b23f3a042c36bc4227b72b97eca803f5f1801c1ab77c8a212d455e/multidict-6.7.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e954b24433c768ce78ab7929e84ccf3422e46deb45a4dc9f93438f8217fa2d34", size = 46930, upload-time = "2026-01-26T02:44:47.278Z" }, + { url = "https://files.pythonhosted.org/packages/b5/66/02ec7ace29162e447f6382c495dc95826bf931d3818799bbef11e8f7df1a/multidict-6.7.1-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3bd231490fa7217cc832528e1cd8752a96f0125ddd2b5749390f7c3ec8721b65", size = 242582, upload-time = "2026-01-26T02:44:48.604Z" }, + { url = "https://files.pythonhosted.org/packages/58/18/64f5a795e7677670e872673aca234162514696274597b3708b2c0d276cce/multidict-6.7.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:253282d70d67885a15c8a7716f3a73edf2d635793ceda8173b9ecc21f2fb8292", size = 250031, upload-time = "2026-01-26T02:44:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ed/e192291dbbe51a8290c5686f482084d31bcd9d09af24f63358c3d42fd284/multidict-6.7.1-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0b4c48648d7649c9335cf1927a8b87fa692de3dcb15faa676c6a6f1f1aabda43", size = 228596, upload-time = "2026-01-26T02:44:51.951Z" }, + { url = "https://files.pythonhosted.org/packages/1e/7e/3562a15a60cf747397e7f2180b0a11dc0c38d9175a650e75fa1b4d325e15/multidict-6.7.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:98bc624954ec4d2c7cb074b8eefc2b5d0ce7d482e410df446414355d158fe4ca", size = 257492, upload-time = "2026-01-26T02:44:53.902Z" }, + { url = "https://files.pythonhosted.org/packages/24/02/7d0f9eae92b5249bb50ac1595b295f10e263dd0078ebb55115c31e0eaccd/multidict-6.7.1-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1b99af4d9eec0b49927b4402bcbb58dea89d3e0db8806a4086117019939ad3dd", size = 255899, upload-time = "2026-01-26T02:44:55.316Z" }, + { url = "https://files.pythonhosted.org/packages/00/e3/9b60ed9e23e64c73a5cde95269ef1330678e9c6e34dd4eb6b431b85b5a10/multidict-6.7.1-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6aac4f16b472d5b7dc6f66a0d49dd57b0e0902090be16594dc9ebfd3d17c47e7", size = 247970, upload-time = "2026-01-26T02:44:56.783Z" }, + { url = "https://files.pythonhosted.org/packages/3e/06/538e58a63ed5cfb0bd4517e346b91da32fde409d839720f664e9a4ae4f9d/multidict-6.7.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:21f830fe223215dffd51f538e78c172ed7c7f60c9b96a2bf05c4848ad49921c3", size = 245060, upload-time = "2026-01-26T02:44:58.195Z" }, + { url = "https://files.pythonhosted.org/packages/b2/2f/d743a3045a97c895d401e9bd29aaa09b94f5cbdf1bd561609e5a6c431c70/multidict-6.7.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:f5dd81c45b05518b9aa4da4aa74e1c93d715efa234fd3e8a179df611cc85e5f4", size = 235888, upload-time = "2026-01-26T02:44:59.57Z" }, + { url = "https://files.pythonhosted.org/packages/38/83/5a325cac191ab28b63c52f14f1131f3b0a55ba3b9aa65a6d0bf2a9b921a0/multidict-6.7.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:eb304767bca2bb92fb9c5bd33cedc95baee5bb5f6c88e63706533a1c06ad08c8", size = 243554, upload-time = "2026-01-26T02:45:01.054Z" }, + { url = "https://files.pythonhosted.org/packages/20/1f/9d2327086bd15da2725ef6aae624208e2ef828ed99892b17f60c344e57ed/multidict-6.7.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:c9035dde0f916702850ef66460bc4239d89d08df4d02023a5926e7446724212c", size = 252341, upload-time = "2026-01-26T02:45:02.484Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2c/2a1aa0280cf579d0f6eed8ee5211c4f1730bd7e06c636ba2ee6aafda302e/multidict-6.7.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:af959b9beeb66c822380f222f0e0a1889331597e81f1ded7f374f3ecb0fd6c52", size = 246391, upload-time = "2026-01-26T02:45:03.862Z" }, + { url = "https://files.pythonhosted.org/packages/e5/03/7ca022ffc36c5a3f6e03b179a5ceb829be9da5783e6fe395f347c0794680/multidict-6.7.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:41f2952231456154ee479651491e94118229844dd7226541788be783be2b5108", size = 243422, upload-time = "2026-01-26T02:45:05.296Z" }, + { url = "https://files.pythonhosted.org/packages/dc/1d/b31650eab6c5778aceed46ba735bd97f7c7d2f54b319fa916c0f96e7805b/multidict-6.7.1-cp313-cp313t-win32.whl", hash = "sha256:df9f19c28adcb40b6aae30bbaa1478c389efd50c28d541d76760199fc1037c32", size = 47770, upload-time = "2026-01-26T02:45:06.754Z" }, + { url = "https://files.pythonhosted.org/packages/ac/5b/2d2d1d522e51285bd61b1e20df8f47ae1a9d80839db0b24ea783b3832832/multidict-6.7.1-cp313-cp313t-win_amd64.whl", hash = "sha256:d54ecf9f301853f2c5e802da559604b3e95bb7a3b01a9c295c6ee591b9882de8", size = 53109, upload-time = "2026-01-26T02:45:08.044Z" }, + { url = "https://files.pythonhosted.org/packages/3d/a3/cc409ba012c83ca024a308516703cf339bdc4b696195644a7215a5164a24/multidict-6.7.1-cp313-cp313t-win_arm64.whl", hash = "sha256:5a37ca18e360377cfda1d62f5f382ff41f2b8c4ccb329ed974cc2e1643440118", size = 45573, upload-time = "2026-01-26T02:45:09.349Z" }, + { url = "https://files.pythonhosted.org/packages/91/cc/db74228a8be41884a567e88a62fd589a913708fcf180d029898c17a9a371/multidict-6.7.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8f333ec9c5eb1b7105e3b84b53141e66ca05a19a605368c55450b6ba208cb9ee", size = 75190, upload-time = "2026-01-26T02:45:10.651Z" }, + { url = "https://files.pythonhosted.org/packages/d5/22/492f2246bb5b534abd44804292e81eeaf835388901f0c574bac4eeec73c5/multidict-6.7.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a407f13c188f804c759fc6a9f88286a565c242a76b27626594c133b82883b5c2", size = 44486, upload-time = "2026-01-26T02:45:11.938Z" }, + { url = "https://files.pythonhosted.org/packages/f1/4f/733c48f270565d78b4544f2baddc2fb2a245e5a8640254b12c36ac7ac68e/multidict-6.7.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0e161ddf326db5577c3a4cc2d8648f81456e8a20d40415541587a71620d7a7d1", size = 43219, upload-time = "2026-01-26T02:45:14.346Z" }, + { url = "https://files.pythonhosted.org/packages/24/bb/2c0c2287963f4259c85e8bcbba9182ced8d7fca65c780c38e99e61629d11/multidict-6.7.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:1e3a8bb24342a8201d178c3b4984c26ba81a577c80d4d525727427460a50c22d", size = 245132, upload-time = "2026-01-26T02:45:15.712Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f9/44d4b3064c65079d2467888794dea218d1601898ac50222ab8a9a8094460/multidict-6.7.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97231140a50f5d447d3164f994b86a0bed7cd016e2682f8650d6a9158e14fd31", size = 252420, upload-time = "2026-01-26T02:45:17.293Z" }, + { url = "https://files.pythonhosted.org/packages/8b/13/78f7275e73fa17b24c9a51b0bd9d73ba64bb32d0ed51b02a746eb876abe7/multidict-6.7.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b10359683bd8806a200fd2909e7c8ca3a7b24ec1d8132e483d58e791d881048", size = 233510, upload-time = "2026-01-26T02:45:19.356Z" }, + { url = "https://files.pythonhosted.org/packages/4b/25/8167187f62ae3cbd52da7893f58cb036b47ea3fb67138787c76800158982/multidict-6.7.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:283ddac99f7ac25a4acadbf004cb5ae34480bbeb063520f70ce397b281859362", size = 264094, upload-time = "2026-01-26T02:45:20.834Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e7/69a3a83b7b030cf283fb06ce074a05a02322359783424d7edf0f15fe5022/multidict-6.7.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:538cec1e18c067d0e6103aa9a74f9e832904c957adc260e61cd9d8cf0c3b3d37", size = 260786, upload-time = "2026-01-26T02:45:22.818Z" }, + { url = "https://files.pythonhosted.org/packages/fe/3b/8ec5074bcfc450fe84273713b4b0a0dd47c0249358f5d82eb8104ffe2520/multidict-6.7.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7eee46ccb30ff48a1e35bb818cc90846c6be2b68240e42a78599166722cea709", size = 248483, upload-time = "2026-01-26T02:45:24.368Z" }, + { url = "https://files.pythonhosted.org/packages/48/5a/d5a99e3acbca0e29c5d9cba8f92ceb15dce78bab963b308ae692981e3a5d/multidict-6.7.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa263a02f4f2dd2d11a7b1bb4362aa7cb1049f84a9235d31adf63f30143469a0", size = 248403, upload-time = "2026-01-26T02:45:25.982Z" }, + { url = "https://files.pythonhosted.org/packages/35/48/e58cd31f6c7d5102f2a4bf89f96b9cf7e00b6c6f3d04ecc44417c00a5a3c/multidict-6.7.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:2e1425e2f99ec5bd36c15a01b690a1a2456209c5deed58f95469ffb46039ccbb", size = 240315, upload-time = "2026-01-26T02:45:27.487Z" }, + { url = "https://files.pythonhosted.org/packages/94/33/1cd210229559cb90b6786c30676bb0c58249ff42f942765f88793b41fdce/multidict-6.7.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:497394b3239fc6f0e13a78a3e1b61296e72bf1c5f94b4c4eb80b265c37a131cd", size = 245528, upload-time = "2026-01-26T02:45:28.991Z" }, + { url = "https://files.pythonhosted.org/packages/64/f2/6e1107d226278c876c783056b7db43d800bb64c6131cec9c8dfb6903698e/multidict-6.7.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:233b398c29d3f1b9676b4b6f75c518a06fcb2ea0b925119fb2c1bc35c05e1601", size = 258784, upload-time = "2026-01-26T02:45:30.503Z" }, + { url = "https://files.pythonhosted.org/packages/4d/c1/11f664f14d525e4a1b5327a82d4de61a1db604ab34c6603bb3c2cc63ad34/multidict-6.7.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:93b1818e4a6e0930454f0f2af7dfce69307ca03cdcfb3739bf4d91241967b6c1", size = 251980, upload-time = "2026-01-26T02:45:32.603Z" }, + { url = "https://files.pythonhosted.org/packages/e1/9f/75a9ac888121d0c5bbd4ecf4eead45668b1766f6baabfb3b7f66a410e231/multidict-6.7.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f33dc2a3abe9249ea5d8360f969ec7f4142e7ac45ee7014d8f8d5acddf178b7b", size = 243602, upload-time = "2026-01-26T02:45:34.043Z" }, + { url = "https://files.pythonhosted.org/packages/9a/e7/50bf7b004cc8525d80dbbbedfdc7aed3e4c323810890be4413e589074032/multidict-6.7.1-cp314-cp314-win32.whl", hash = "sha256:3ab8b9d8b75aef9df299595d5388b14530839f6422333357af1339443cff777d", size = 40930, upload-time = "2026-01-26T02:45:36.278Z" }, + { url = "https://files.pythonhosted.org/packages/e0/bf/52f25716bbe93745595800f36fb17b73711f14da59ed0bb2eba141bc9f0f/multidict-6.7.1-cp314-cp314-win_amd64.whl", hash = "sha256:5e01429a929600e7dab7b166062d9bb54a5eed752384c7384c968c2afab8f50f", size = 45074, upload-time = "2026-01-26T02:45:37.546Z" }, + { url = "https://files.pythonhosted.org/packages/97/ab/22803b03285fa3a525f48217963da3a65ae40f6a1b6f6cf2768879e208f9/multidict-6.7.1-cp314-cp314-win_arm64.whl", hash = "sha256:4885cb0e817aef5d00a2e8451d4665c1808378dc27c2705f1bf4ef8505c0d2e5", size = 42471, upload-time = "2026-01-26T02:45:38.889Z" }, + { url = "https://files.pythonhosted.org/packages/e0/6d/f9293baa6146ba9507e360ea0292b6422b016907c393e2f63fc40ab7b7b5/multidict-6.7.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0458c978acd8e6ea53c81eefaddbbee9c6c5e591f41b3f5e8e194780fe026581", size = 82401, upload-time = "2026-01-26T02:45:40.254Z" }, + { url = "https://files.pythonhosted.org/packages/7a/68/53b5494738d83558d87c3c71a486504d8373421c3e0dbb6d0db48ad42ee0/multidict-6.7.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:c0abd12629b0af3cf590982c0b413b1e7395cd4ec026f30986818ab95bfaa94a", size = 48143, upload-time = "2026-01-26T02:45:41.635Z" }, + { url = "https://files.pythonhosted.org/packages/37/e8/5284c53310dcdc99ce5d66563f6e5773531a9b9fe9ec7a615e9bc306b05f/multidict-6.7.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:14525a5f61d7d0c94b368a42cff4c9a4e7ba2d52e2672a7b23d84dc86fb02b0c", size = 46507, upload-time = "2026-01-26T02:45:42.99Z" }, + { url = "https://files.pythonhosted.org/packages/e4/fc/6800d0e5b3875568b4083ecf5f310dcf91d86d52573160834fb4bfcf5e4f/multidict-6.7.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:17307b22c217b4cf05033dabefe68255a534d637c6c9b0cc8382718f87be4262", size = 239358, upload-time = "2026-01-26T02:45:44.376Z" }, + { url = "https://files.pythonhosted.org/packages/41/75/4ad0973179361cdf3a113905e6e088173198349131be2b390f9fa4da5fc6/multidict-6.7.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a7e590ff876a3eaf1c02a4dfe0724b6e69a9e9de6d8f556816f29c496046e59", size = 246884, upload-time = "2026-01-26T02:45:47.167Z" }, + { url = "https://files.pythonhosted.org/packages/c3/9c/095bb28b5da139bd41fb9a5d5caff412584f377914bd8787c2aa98717130/multidict-6.7.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5fa6a95dfee63893d80a34758cd0e0c118a30b8dcb46372bf75106c591b77889", size = 225878, upload-time = "2026-01-26T02:45:48.698Z" }, + { url = "https://files.pythonhosted.org/packages/07/d0/c0a72000243756e8f5a277b6b514fa005f2c73d481b7d9e47cd4568aa2e4/multidict-6.7.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a0543217a6a017692aa6ae5cc39adb75e587af0f3a82288b1492eb73dd6cc2a4", size = 253542, upload-time = "2026-01-26T02:45:50.164Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6b/f69da15289e384ecf2a68837ec8b5ad8c33e973aa18b266f50fe55f24b8c/multidict-6.7.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f99fe611c312b3c1c0ace793f92464d8cd263cc3b26b5721950d977b006b6c4d", size = 252403, upload-time = "2026-01-26T02:45:51.779Z" }, + { url = "https://files.pythonhosted.org/packages/a2/76/b9669547afa5a1a25cd93eaca91c0da1c095b06b6d2d8ec25b713588d3a1/multidict-6.7.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9004d8386d133b7e6135679424c91b0b854d2d164af6ea3f289f8f2761064609", size = 244889, upload-time = "2026-01-26T02:45:53.27Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a9/a50d2669e506dad33cfc45b5d574a205587b7b8a5f426f2fbb2e90882588/multidict-6.7.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e628ef0e6859ffd8273c69412a2465c4be4a9517d07261b33334b5ec6f3c7489", size = 241982, upload-time = "2026-01-26T02:45:54.919Z" }, + { url = "https://files.pythonhosted.org/packages/c5/bb/1609558ad8b456b4827d3c5a5b775c93b87878fd3117ed3db3423dfbce1b/multidict-6.7.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:841189848ba629c3552035a6a7f5bf3b02eb304e9fea7492ca220a8eda6b0e5c", size = 232415, upload-time = "2026-01-26T02:45:56.981Z" }, + { url = "https://files.pythonhosted.org/packages/d8/59/6f61039d2aa9261871e03ab9dc058a550d240f25859b05b67fd70f80d4b3/multidict-6.7.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:ce1bbd7d780bb5a0da032e095c951f7014d6b0a205f8318308140f1a6aba159e", size = 240337, upload-time = "2026-01-26T02:45:58.698Z" }, + { url = "https://files.pythonhosted.org/packages/a1/29/fdc6a43c203890dc2ae9249971ecd0c41deaedfe00d25cb6564b2edd99eb/multidict-6.7.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b26684587228afed0d50cf804cc71062cc9c1cdf55051c4c6345d372947b268c", size = 248788, upload-time = "2026-01-26T02:46:00.862Z" }, + { url = "https://files.pythonhosted.org/packages/a9/14/a153a06101323e4cf086ecee3faadba52ff71633d471f9685c42e3736163/multidict-6.7.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9f9af11306994335398293f9958071019e3ab95e9a707dc1383a35613f6abcb9", size = 242842, upload-time = "2026-01-26T02:46:02.824Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/604ae839e64a4a6efc80db94465348d3b328ee955e37acb24badbcd24d83/multidict-6.7.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b4938326284c4f1224178a560987b6cf8b4d38458b113d9b8c1db1a836e640a2", size = 240237, upload-time = "2026-01-26T02:46:05.898Z" }, + { url = "https://files.pythonhosted.org/packages/5f/60/c3a5187bf66f6fb546ff4ab8fb5a077cbdd832d7b1908d4365c7f74a1917/multidict-6.7.1-cp314-cp314t-win32.whl", hash = "sha256:98655c737850c064a65e006a3df7c997cd3b220be4ec8fe26215760b9697d4d7", size = 48008, upload-time = "2026-01-26T02:46:07.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/f7/addf1087b860ac60e6f382240f64fb99f8bfb532bb06f7c542b83c29ca61/multidict-6.7.1-cp314-cp314t-win_amd64.whl", hash = "sha256:497bde6223c212ba11d462853cfa4f0ae6ef97465033e7dc9940cdb3ab5b48e5", size = 53542, upload-time = "2026-01-26T02:46:08.809Z" }, + { url = "https://files.pythonhosted.org/packages/4c/81/4629d0aa32302ef7b2ec65c75a728cc5ff4fa410c50096174c1632e70b3e/multidict-6.7.1-cp314-cp314t-win_arm64.whl", hash = "sha256:2bbd113e0d4af5db41d5ebfe9ccaff89de2120578164f86a5d17d5a576d1e5b2", size = 44719, upload-time = "2026-01-26T02:46:11.146Z" }, + { url = "https://files.pythonhosted.org/packages/81/08/7036c080d7117f28a4af526d794aab6a84463126db031b007717c1a6676e/multidict-6.7.1-py3-none-any.whl", hash = "sha256:55d97cc6dae627efa6a6e548885712d4864b81110ac76fa4e534c03819fa4a56", size = 12319, upload-time = "2026-01-26T02:46:44.004Z" }, +] + +[[package]] +name = "nbclient" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jupyter-client" }, + { name = "jupyter-core" }, + { name = "nbformat" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/a5/b3bae4b590c0cbcada2c63a34f7580024e834a8ba213e949a2f906705787/nbclient-0.11.0.tar.gz", hash = "sha256:04a134a5b087f2c5887f228aca155db50169b8cd9334dee6942c8e927e56081a", size = 62535, upload-time = "2026-06-05T07:52:41.746Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/36/c9/94d73e5a01c5b926c3fa2496e97d7a8dc28ed5a77c0b2ed712f1a62e6694/nbclient-0.11.0-py3-none-any.whl", hash = "sha256:ef7fa0d59d6e1d41103933d8a445a18d5de860ca6b613b87b8574accdb3c2895", size = 25288, upload-time = "2026-06-05T07:52:40.115Z" }, +] + +[[package]] +name = "nbformat" +version = "5.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fastjsonschema" }, + { name = "jsonschema" }, + { name = "jupyter-core" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b2/fd/80f407a9525bc5bd9865e5c37db3b78867fa43217f8aac5eab22b5f028b3/nbformat-5.11.0.tar.gz", hash = "sha256:7dbaed4a69cae28c2b4d44ab7430a6af4544fb89455023f6f21550be757b60c8", size = 151822, upload-time = "2026-08-06T12:29:55.597Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/4a/0eece9dad5e73230ca972f7bc29456ce7d74772f123d401fcf67379008f7/nbformat-5.11.0-py3-none-any.whl", hash = "sha256:f70a17f591a9ccd1c601d5e61a4b20972703926df0ba42458ce14bf575766bb6", size = 79820, upload-time = "2026-08-06T12:29:54.178Z" }, +] + +[[package]] +name = "nest-asyncio2" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b4/73/731debf26e27e0a0323d7bda270dc2f634b398e38f040a09da1f4351d0aa/nest_asyncio2-1.7.2.tar.gz", hash = "sha256:1921d70b92cc4612c374928d081552efb59b83d91b2b789d935c665fa01729a8", size = 14743, upload-time = "2026-02-13T00:34:04.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/3c/3179b85b0e1c3659f0369940200cd6d0fa900e6cefcc7ea0bc6dd0e29ffb/nest_asyncio2-1.7.2-py3-none-any.whl", hash = "sha256:f5dfa702f3f81f6a03857e9a19e2ba578c0946a4ad417b4c50a24d7ba641fe01", size = 7843, upload-time = "2026-02-13T00:34:02.691Z" }, +] + +[[package]] +name = "numcodecs" +version = "0.16.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/44/bd/8a391e7c356366224734efd24da929cc4796fff468bfb179fe1af6548535/numcodecs-0.16.5.tar.gz", hash = "sha256:0d0fb60852f84c0bd9543cc4d2ab9eefd37fc8efcc410acd4777e62a1d300318", size = 6276387, upload-time = "2025-11-21T02:49:48.986Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/cc/55420f3641a67f78392dc0bc5d02cb9eb0a9dcebf2848d1ac77253ca61fa/numcodecs-0.16.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:24e675dc8d1550cd976a99479b87d872cb142632c75cc402fea04c08c4898523", size = 1656287, upload-time = "2025-11-21T02:49:25.755Z" }, + { url = "https://files.pythonhosted.org/packages/f5/6c/86644987505dcb90ba6d627d6989c27bafb0699f9fd00187e06d05ea8594/numcodecs-0.16.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:94ddfa4341d1a3ab99989d13b01b5134abb687d3dab2ead54b450aefe4ad5bd6", size = 1148899, upload-time = "2025-11-21T02:49:26.87Z" }, + { url = "https://files.pythonhosted.org/packages/97/1e/98aaddf272552d9fef1f0296a9939d1487914a239e98678f6b20f8b0a5c8/numcodecs-0.16.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b554ab9ecf69de7ca2b6b5e8bc696bd9747559cb4dd5127bd08d7a28bec59c3a", size = 8534814, upload-time = "2025-11-21T02:49:28.547Z" }, + { url = "https://files.pythonhosted.org/packages/fb/53/78c98ef5c8b2b784453487f3e4d6c017b20747c58b470393e230c78d18e8/numcodecs-0.16.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad1a379a45bd3491deab8ae6548313946744f868c21d5340116977ea3be5b1d6", size = 9173471, upload-time = "2025-11-21T02:49:30.444Z" }, + { url = "https://files.pythonhosted.org/packages/1c/20/2fdec87fc7f8cec950d2b0bea603c12dc9f05b4966dc5924ba5a36a61bf6/numcodecs-0.16.5-cp312-cp312-win_amd64.whl", hash = "sha256:845a9857886ffe4a3172ba1c537ae5bcc01e65068c31cf1fce1a844bd1da050f", size = 801412, upload-time = "2025-11-21T02:49:32.123Z" }, + { url = "https://files.pythonhosted.org/packages/38/38/071ced5a5fd1c85ba0e14ba721b66b053823e5176298c2f707e50bed11d9/numcodecs-0.16.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:25be3a516ab677dad890760d357cfe081a371d9c0a2e9a204562318ac5969de3", size = 1654359, upload-time = "2025-11-21T02:49:33.673Z" }, + { url = "https://files.pythonhosted.org/packages/d1/c0/5f84ba7525577c1b9909fc2d06ef11314825fc4ad4378f61d0e4c9883b4a/numcodecs-0.16.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0107e839ef75b854e969cb577e140b1aadb9847893937636582d23a2a4c6ce50", size = 1144237, upload-time = "2025-11-21T02:49:35.294Z" }, + { url = "https://files.pythonhosted.org/packages/0b/00/787ea5f237b8ea7bc67140c99155f9c00b5baf11c49afc5f3bfefa298f95/numcodecs-0.16.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:015a7c859ecc2a06e2a548f64008c0ec3aaecabc26456c2c62f4278d8fc20597", size = 8483064, upload-time = "2025-11-21T02:49:36.454Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e6/d359fdd37498e74d26a167f7a51e54542e642ea47181eb4e643a69a066c3/numcodecs-0.16.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84230b4b9dad2392f2a84242bd6e3e659ac137b5a1ce3571d6965fca673e0903", size = 9126063, upload-time = "2025-11-21T02:49:38.018Z" }, + { url = "https://files.pythonhosted.org/packages/27/72/6663cc0382ddbb866136c255c837bcb96cc7ce5e83562efec55e1b995941/numcodecs-0.16.5-cp313-cp313-win_amd64.whl", hash = "sha256:5088145502ad1ebf677ec47d00eb6f0fd600658217db3e0c070c321c85d6cf3d", size = 799275, upload-time = "2025-11-21T02:49:39.558Z" }, + { url = "https://files.pythonhosted.org/packages/3c/9e/38e7ca8184c958b51f45d56a4aeceb1134ecde2d8bd157efadc98502cc42/numcodecs-0.16.5-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:b05647b8b769e6bc8016e9fd4843c823ce5c9f2337c089fb5c9c4da05e5275de", size = 1654721, upload-time = "2025-11-21T02:49:40.602Z" }, + { url = "https://files.pythonhosted.org/packages/a1/37/260fa42e7b2b08e6e00ad632f8dd620961a60a459426c26cea390f8c68d0/numcodecs-0.16.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3832bd1b5af8bb3e413076b7d93318c8e7d7b68935006b9fa36ca057d1725a8f", size = 1146887, upload-time = "2025-11-21T02:49:41.721Z" }, + { url = "https://files.pythonhosted.org/packages/4e/15/e2e1151b5a8b14a15dfd4bb4abccce7fff7580f39bc34092780088835f3a/numcodecs-0.16.5-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49f7b7d24f103187f53135bed28bb9f0ed6b2e14c604664726487bb6d7c882e1", size = 8476987, upload-time = "2025-11-21T02:49:43.363Z" }, + { url = "https://files.pythonhosted.org/packages/6d/30/16a57fc4d9fb0ba06c600408bd6634f2f1753c54a7a351c99c5e09b51ee2/numcodecs-0.16.5-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aec9736d81b70f337d89c4070ee3ffeff113f386fd789492fa152d26a15043e4", size = 9102377, upload-time = "2025-11-21T02:49:45.508Z" }, + { url = "https://files.pythonhosted.org/packages/31/a5/a0425af36c20d55a3ea884db4b4efca25a43bea9214ba69ca7932dd997b4/numcodecs-0.16.5-cp314-cp314-win_amd64.whl", hash = "sha256:b16a14303800e9fb88abc39463ab4706c037647ac17e49e297faa5f7d7dbbf1d", size = 819022, upload-time = "2025-11-21T02:49:47.39Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/7b/14687aa674250e5e546f616f486b0d56d3631cd5b2415739141ce40bdcea/numpy-2.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2c889b56fe48b1018f764b0eec8df59ab654e9148aa91faa12596043500de277", size = 16801574, upload-time = "2026-07-04T17:06:12.423Z" }, + { url = "https://files.pythonhosted.org/packages/e1/19/cc5bb2a3f2913d27d6dbb2c78d25921fabaedc6741d4a5a615a11f3c5bf3/numpy-2.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab451b59c5643c570974c43aef780703ef1d3b4965d2be07afd530615a9358d1", size = 11772250, upload-time = "2026-07-04T17:06:15.726Z" }, + { url = "https://files.pythonhosted.org/packages/42/77/fdf34a71dd30f54979b18603bee915e0aaf825b07afe79acd60b04b691e2/numpy-2.5.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:78798bd5b9ad744056af8efa90e3b9ddaa53272a0848a483084a1cc0a13b2dc0", size = 5331516, upload-time = "2026-07-04T17:06:17.913Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e2/eb7efa015b4cce41e2517bf182a7fce0d7d5b9d9ed76a29bfa0f4fe4505c/numpy-2.5.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:2ae0ca40bcb22d6ba59c1dfd5446f49940b0f2d821fde133f10dda11f816b84e", size = 6664863, upload-time = "2026-07-04T17:06:20.02Z" }, + { url = "https://files.pythonhosted.org/packages/a9/4b/a2b32dd94ee9ffbeecb28152240042a3949db33b1c834d44090b80e1b3b8/numpy-2.5.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61ac47e772e6b8ea489e1d2f441a34c5c3ac17327e7ce294cbdf535795ad4e75", size = 15167977, upload-time = "2026-07-04T17:06:21.621Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a9/6e73d68500f80773f65f0654ea932019d6694329a0eb0ed0533de38df376/numpy-2.5.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:59fda5e192b570217ec2580c96f00e9a7e12ef6866a900eb089b62c1a32545ca", size = 16672469, upload-time = "2026-07-04T17:06:24.064Z" }, + { url = "https://files.pythonhosted.org/packages/24/7d/ad3e59015135f5261c95fd4cafeff159c955febd83a99a1d9250c4233815/numpy-2.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f7119ebff1a9829e9f431a4f9d28e703023bb6b9fe7c8f724467dbfc27c94ab3", size = 16527531, upload-time = "2026-07-04T17:06:26.69Z" }, + { url = "https://files.pythonhosted.org/packages/83/d0/a39b2fbcde9cb17a1dac678f254b33a6336298af9df338824c685425d5e8/numpy-2.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e824c2acf8862052246be5a44c15da1777940c60d010dd2aab897824d9c430f9", size = 18431940, upload-time = "2026-07-04T17:06:29.521Z" }, + { url = "https://files.pythonhosted.org/packages/04/12/cff070947791c1ed425ff76413189adbdc2fbe215eba7ce7fa454a03c7f8/numpy-2.5.1-cp312-cp312-win32.whl", hash = "sha256:08d60c810432eb83360958dea0999ac4cfb94531ea8efcbf0b7f277c2068aeb2", size = 6066764, upload-time = "2026-07-04T17:06:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/65/66/53f31807a48a750f9d748da273bc3fcedd12b27ff1f3e373bfec55ef2dc0/numpy-2.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:f7d60026c0bdb1380e83bfa7a0419c4577ee4b9a08880afcb6dadeb74c649fa2", size = 12430966, upload-time = "2026-07-04T17:06:34.926Z" }, + { url = "https://files.pythonhosted.org/packages/2b/2a/d1a88066b1c14186f5d3c0d18c94f17b064511982bab0578d49ee9d43c29/numpy-2.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:17a25e09640602e10bc8de0e6fa2b3fd68eedd84ba6d7842dc8f32f9ab87bd0b", size = 10350488, upload-time = "2026-07-04T17:06:37.785Z" }, + { url = "https://files.pythonhosted.org/packages/eb/07/ec2a3f0c91761581d4b7104a740791800025983f9a4dc4e73f91a99aeac4/numpy-2.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0bfebd8695f9863592fe744be833a258120b14a9f39da255e8aa8fade2c0ddd1", size = 16796419, upload-time = "2026-07-04T17:06:40.37Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ab/ddb499fc4f8780354395face5b65c7fd107bcd6e1d667a5f07d046956f6f/numpy-2.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:30b44a6b53a7ae63c54c089a8726e5563ed302716c5b7ccc85afade40b0e7ff6", size = 11765832, upload-time = "2026-07-04T17:06:42.768Z" }, + { url = "https://files.pythonhosted.org/packages/88/b3/3c28c558a09fc72100c646dac6d2fce8e834c471b0edca01a29996706117/numpy-2.5.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:6165343f81b56ef8f514f396989e529b61d9dc709b99421b07e9f3e698e2287d", size = 5325143, upload-time = "2026-07-04T17:06:45.466Z" }, + { url = "https://files.pythonhosted.org/packages/5e/0e/ce19b985bb15c596f4f05954e76cccc77c845083b3b8f938a6c68e523128/numpy-2.5.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4939237038ada79308dda3204ac6462df056b5672b2e25db1149cf873668b3e1", size = 6659749, upload-time = "2026-07-04T17:06:47.288Z" }, + { url = "https://files.pythonhosted.org/packages/2e/20/1ee6614d64332a1bba6411f38e68cb79eec1b2459e20a623777c5c5492a2/numpy-2.5.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c6759f538fb912fc46de0a6b1758ccf7b57bc7c7ebebc23974fdac3de8db0cd", size = 15164716, upload-time = "2026-07-04T17:06:49.494Z" }, + { url = "https://files.pythonhosted.org/packages/ed/a7/2bcd3fdbb87804755c35b729bf8709d62025c5f4cfd7d5b2415997097515/numpy-2.5.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9726558e8db4a5bf7929a70ae50f63abda4daf0efe810e3bfbab95976f75fc1a", size = 16661440, upload-time = "2026-07-04T17:06:52.061Z" }, + { url = "https://files.pythonhosted.org/packages/fc/d7/a41e3310c886fe457d36e670bbf24fae411aca8a7b6ad92a32afd924077c/numpy-2.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3935f3b419b244a02732676fa5317a9193cc596a4c0646db07e5b421229ac9f7", size = 16526305, upload-time = "2026-07-04T17:06:54.605Z" }, + { url = "https://files.pythonhosted.org/packages/53/75/4333a9a707c1edd3a4e1a0c58eca52c0f31e55089fa80db02b5565b24df7/numpy-2.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dc932a65ded7ce9013d120845a2514dcccb1a67bfc8deb8d37633762951904a6", size = 18423008, upload-time = "2026-07-04T17:06:57.54Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/e314a32b1c11a2ffe818ddad3a57b50b4b6e1b6c487192eb50cdef0415d0/numpy-2.5.1-cp313-cp313-win32.whl", hash = "sha256:4b4ff1608417eb7a59da7b967bbb798cacfe071d2caf526a24281cd562072ed9", size = 6063885, upload-time = "2026-07-04T17:07:00.14Z" }, + { url = "https://files.pythonhosted.org/packages/10/70/800b3fca480af32df9e8ea9f3d4a0c8feb4b32d7f195d174eabbda4829ad/numpy-2.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:6c3fe51bc6a16453d452997053454f309e8e0ed7b42d6b361ce4ac8c32913d74", size = 12425674, upload-time = "2026-07-04T17:07:02.387Z" }, + { url = "https://files.pythonhosted.org/packages/8b/0b/196350c122f50f6ca56846f2d71efd5e0d24b7b2e07355e019b2e2c7a11e/numpy-2.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:f7feb014281029e628ba2d5a007407443b06e418b6fe451d1e2adcbc8eba0107", size = 10350256, upload-time = "2026-07-04T17:07:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/db/f4/731b6085a83faf6ca843394cbd5e217280c214399f7e8b21b9f552af0ae2/numpy-2.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7c786fe9a5bbe360022e584c5a34cf6b54265c71bd7ec8ac3d8fec38968071f8", size = 16795063, upload-time = "2026-07-04T17:07:07.374Z" }, + { url = "https://files.pythonhosted.org/packages/bf/64/0e215f2048dd11a55bb989ed41b3585ef57452404e638d703a211a3e4157/numpy-2.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:32985c896d897419ef8da6917872d80b78ad0ea26d85b23245c7366ffde76d75", size = 11776652, upload-time = "2026-07-04T17:07:09.907Z" }, + { url = "https://files.pythonhosted.org/packages/b5/59/2b844c7a6e9deff69b404a66221e1542937734f65d5e6e39411876053862/numpy-2.5.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:efd736408cc97c79b9e6917338dfc8f06013b2274f992e96b1d9a81a71e2a2c2", size = 5335944, upload-time = "2026-07-04T17:07:12.227Z" }, + { url = "https://files.pythonhosted.org/packages/86/51/9bf7cb2cabcebc9e017e4ec7e6322b378317a542c08b4cb68479c1efc716/numpy-2.5.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:ab84dc6b074fa881cae55bea94cc4f68e285181ba7f32497bf7dee6b1496165b", size = 6656266, upload-time = "2026-07-04T17:07:14.368Z" }, + { url = "https://files.pythonhosted.org/packages/83/3e/fb7615b211b82a32f44d5180a6d421b61f84d4fadd578b48ba4ac34e189f/numpy-2.5.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:caf3e317d33d60c37986b452613f4ab51246d0691350c03d0cb4a898627f4a95", size = 15179720, upload-time = "2026-07-04T17:07:16.272Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/0f992cb24560673496c5d68de61913b57166ce530ffda07c1f280e0cc464/numpy-2.5.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54ad769f17bc2d833b620851989f62054fb9ab93c969d9e1dc3c8e3d56beea21", size = 16664835, upload-time = "2026-07-04T17:07:19.021Z" }, + { url = "https://files.pythonhosted.org/packages/a2/2f/97d6475ee91afe2587797d09446f9d3e475ad4cb681662d824809327b75a/numpy-2.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c12afb53450fa976d4c681c50a7423729a4c51c0465ed9f32b8a9cabbc472373", size = 16539135, upload-time = "2026-07-04T17:07:22.015Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5b/4db81e4ba0be7e2776b1de68c82aa862c7f8ec27e1b4927d4ae075e20678/numpy-2.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e8c11c405efc5ff6816d5983c96cdfa215bab3428961243af3ff59b228490438", size = 18426684, upload-time = "2026-07-04T17:07:24.941Z" }, + { url = "https://files.pythonhosted.org/packages/1f/64/c0ba2d90724d450279a7df8f32057241070250a26a7e2b5337d77347f481/numpy-2.5.1-cp314-cp314-win32.whl", hash = "sha256:f2479a47f8d5932d1718168a681ad6e536a9df484c83cfcf9de365e164537ace", size = 6116103, upload-time = "2026-07-04T17:07:27.622Z" }, + { url = "https://files.pythonhosted.org/packages/c1/1a/837f9ed7405adcd7a40538792eb169eddd8fa5630c16a1ef49dae71a30f4/numpy-2.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:24d0eb82c0541d3415a33425db64ae439dffccd7b4dbcb30e7c35120205c506a", size = 12562177, upload-time = "2026-07-04T17:07:29.887Z" }, + { url = "https://files.pythonhosted.org/packages/22/ed/49707938b6dd0a78a9178dd93227dc89e4c11af47f5c798d70366e8d0483/numpy-2.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5a4c988b38d261deeeaad9954e3deb091ad905c94e8bb6708654ef1d97f286b0", size = 10627739, upload-time = "2026-07-04T17:07:32.568Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c7/bb4b882cfe7f299cbc8b66e42e7dd78cf9d14e40f9469fc5e3db7e15b3bd/numpy-2.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a33276be12fa045805f477f22482088b66bb758ffbe89a9d21457de863a32e22", size = 11894709, upload-time = "2026-07-04T17:07:34.941Z" }, + { url = "https://files.pythonhosted.org/packages/40/3f/5af7f4a7f6224aef48017aa82bb6174c7a659d724be0c75017b7e64a55b4/numpy-2.5.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:f089d7b00756190aacf1f5d34bdf38c3c430ac82b4f868f8cede73380460fce7", size = 5453810, upload-time = "2026-07-04T17:07:37.495Z" }, + { url = "https://files.pythonhosted.org/packages/20/c9/3474309bc94d634d3f9c3eddf03250ecb8c22cd948ef16fef69a77cc5d7b/numpy-2.5.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:09e9bfd8d2cf479c7d174804fb3811c53a8e9f20a37444008606b57d6b7a826d", size = 6761189, upload-time = "2026-07-04T17:07:39.563Z" }, + { url = "https://files.pythonhosted.org/packages/90/8a/558ae39fdd55d7e7f7fef9a84a6e964ac6b23edbd2a07e52bb084500507d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e68d8dd1e7eba712948f2053a29ec86917bc70ba1358df869d9f06649ef9cf09", size = 15225039, upload-time = "2026-07-04T17:07:41.682Z" }, + { url = "https://files.pythonhosted.org/packages/63/27/ca7392b2d030277bdf0273e7d23255b3ee57d57a7c170a6f4fb3981e1e5d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99d5095fa265a0c4152e7bb12759e14381ef5496152f1ce58f44bdf55c44beb4", size = 16701306, upload-time = "2026-07-04T17:07:44.611Z" }, + { url = "https://files.pythonhosted.org/packages/02/42/03d53ae7996c44d4374a8262e9dc41671fd56cbb98f7d47ef85cf5da4c6b/numpy-2.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab87a91b3cc3382b8956095bd8f95e00cf679bb81554339be1a2ba404a1473c1", size = 16589955, upload-time = "2026-07-04T17:07:47.694Z" }, + { url = "https://files.pythonhosted.org/packages/7b/15/6c1784ae469640e65db111e9a34b3d0f14d91e8a38b9ce34810ced370dbb/numpy-2.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:224ca51130ef7da85bea2191625181cb4f337f9cb64b471f10c1a12aa8b60077", size = 18464252, upload-time = "2026-07-04T17:07:50.684Z" }, + { url = "https://files.pythonhosted.org/packages/94/a8/f98e50356cf167df656c526c2dfeec2d7dde182f2a3da4b458a5938e2776/numpy-2.5.1-cp314-cp314t-win32.whl", hash = "sha256:6eab239876581b2b3c5a242281b6007bbdbcd1c7085d7709bb57c5929b11e6bf", size = 6263298, upload-time = "2026-07-04T17:07:53.445Z" }, + { url = "https://files.pythonhosted.org/packages/72/ac/96ae880cdecad0b3275d9359fcec72667b49a4863c9f12942e43679dda02/numpy-2.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:83ce9c80d5b521b0d77ddcbe5447c218d247929b6cc056ca5351342accfff0af", size = 12748623, upload-time = "2026-07-04T17:07:55.384Z" }, + { url = "https://files.pythonhosted.org/packages/a1/5a/4d2b1601df3602dba7a14f3348ba9bfe94a18adb428e693df6154c293831/numpy-2.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:5a6db61f9aaa57e369905c67d852045d3c4f7126405b29d09b19dec118e9c9cb", size = 10697674, upload-time = "2026-07-04T17:07:58.506Z" }, +] + +[[package]] +name = "packaging" +version = "26.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, +] + +[[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 = "parso" +version = "0.8.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, +] + +[[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 = "pexpect" +version = "4.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ptyprocess" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.11.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e5/98/0bf930c4f97d0266b58a89e36c015f56232c52b5d2f207215d48cca9e8f7/platformdirs-4.11.2.tar.gz", hash = "sha256:3a2ae5fca3520a01ab1be8b45613537f52ddf5b5f6f53d88233892dfbf0cd82d", size = 32716, upload-time = "2026-08-10T15:48:06.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/e2/4e6eee633809c376c024821b91ade709cbfd040ec53939ffbcc292aa7eee/platformdirs-4.11.2-py3-none-any.whl", hash = "sha256:7f89089b6ea71bda7962953edcf784b2e2d9d285b40ad88be2bb75c6e9d82ab4", size = 23361, upload-time = "2026-08-10T15:48:04.855Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "prompt-toolkit" +version = "3.0.53" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/ea/39b988c938f75cb75d7045b5c69f8bfed47ee2152c8837fb403de29d6fb8/prompt_toolkit-3.0.53.tar.gz", hash = "sha256:9ec8a0ad96d5c56148b3f914aa79c1564c3fde5d2e6b876e7bc327e353cf8fa6", size = 435492, upload-time = "2026-07-26T20:56:14.758Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/44/c87281c333769159c50594f22610f77398a47ccbfbbf23074e744e86f87c/propcache-0.5.2.tar.gz", hash = "sha256:01c4fc7480cd0598bb4b57022df55b9ca296da7fc5a8760bd8451a7e63a7d427", size = 50208, upload-time = "2026-05-08T21:02:12.199Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4a/cb/e27bc2b2737a0bb49962b275efa051e8f1c35a936df7d5139b6b658b7dc9/propcache-0.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:806719138ecd720339a12410fb9614ac9b2b2d3a5fdf8235d56981c36f4039ba", size = 95887, upload-time = "2026-05-08T21:00:11.277Z" }, + { url = "https://files.pythonhosted.org/packages/e6/13/b8ae04c59392f8d11c6cd9fb4011d1dc7c86b81225c770280300e259ffe1/propcache-0.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:db2b80ea58eab4f86b2beec3cc8b39e8ff9276ac20e96b7cce43c8ae84cd6b5a", size = 54654, upload-time = "2026-05-08T21:00:12.604Z" }, + { url = "https://files.pythonhosted.org/packages/2c/7d/49777a3e20b55863d4794384a38acd460c04157b0a00f8602b0d508b8431/propcache-0.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e5cbfac9f61484f7e9f3597775500cd3ebe8274e9b050c38f9525c77c97520bf", size = 55190, upload-time = "2026-05-08T21:00:13.935Z" }, + { url = "https://files.pythonhosted.org/packages/44/c7/085d0cd63062e84044e3f05797749c3f8e3938ff3aeb0eb2f69d43fafc91/propcache-0.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbc581d2814337da56222fab8dc5f161cd798a434e49bac27930aaef798e144", size = 59995, upload-time = "2026-05-08T21:00:15.526Z" }, + { url = "https://files.pythonhosted.org/packages/9c/42/32cf8e3009e92b2645cf1e944f701e8ea4e924dffde1ee26db860bcbf7e4/propcache-0.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:857187f381f88c8e2fa2fe56ab94879d011b883d5a2ee5a1b60a8cd2a06846d9", size = 63422, upload-time = "2026-05-08T21:00:16.824Z" }, + { url = "https://files.pythonhosted.org/packages/9e/1b/f112433f99fc979431b87a39ef169e3f8df070d99a72792c56d6937ac48b/propcache-0.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:178b4a2cdaac1818e2bf1c5a99b94383fa73ea5382e032a48dec07dc5668dc42", size = 64342, upload-time = "2026-05-08T21:00:18.362Z" }, + { url = "https://files.pythonhosted.org/packages/14/15/5574111ae50dd6e879456888c0eadd4c5a869959775854e18e18a6b345f3/propcache-0.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f328175a2cde1f0ff2c4ed8ce968b9dcfb55f3a7153f39e2957ed994da13476", size = 61639, upload-time = "2026-05-08T21:00:19.692Z" }, + { url = "https://files.pythonhosted.org/packages/cc/da/4d775080b1490c0ae604acda868bd71aabe3a89ed16f2aa4339eb8a283e7/propcache-0.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5671d09a36b06d0fd4a3da0fccbcae360e9b1570924171a15e9e0997f0249fba", size = 61588, upload-time = "2026-05-08T21:00:21.155Z" }, + { url = "https://files.pythonhosted.org/packages/04/ac/f076982cbe2195ee9cf32de5a1e46951d9fb399fc207f390562dd0fd8fb2/propcache-0.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:80168e2ebe4d3ec6599d10ad8f520304ae1cad9b6c5a95372aef1b66b7bfb53a", size = 60029, upload-time = "2026-05-08T21:00:22.713Z" }, + { url = "https://files.pythonhosted.org/packages/70/60/189be62e0dd898dce3b331e1b8c7a543cd3a405ac0c81fe8ee8a9d5d77e1/propcache-0.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:45f11346f884bc47444f6e6647131055844134c3175b629f84952e2b5cd62b64", size = 56774, upload-time = "2026-05-08T21:00:24.001Z" }, + { url = "https://files.pythonhosted.org/packages/ea/9e/93377b9c7939c1ffae98f878dee955efadfd638078bc86dbc21f9d52f651/propcache-0.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8e778ebd44ef4f66ed60a0416b06b489687db264a9c0b3620362f26489492913", size = 63532, upload-time = "2026-05-08T21:00:25.545Z" }, + { url = "https://files.pythonhosted.org/packages/14/f9/590ef6cfb9b8028d516d287812ece32bb0bc5f11fbb9c8bf6b2e6313fec8/propcache-0.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:c0cb9ed24c8964e172768d455a38254c2dd8a552905729ce006cad3d3dda59b1", size = 61592, upload-time = "2026-05-08T21:00:27.186Z" }, + { url = "https://files.pythonhosted.org/packages/b4/5e/70958b3034c297a630bba2f17ca7abc2d5f39a803ad7e370ab79d1ecd022/propcache-0.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:1d1ad32d9d4355e2be65574fd0bfd3677e7066b009cd5b9b2dee8aa6a6393b33", size = 64788, upload-time = "2026-05-08T21:00:28.8Z" }, + { url = "https://files.pythonhosted.org/packages/12/fd/77fe5936d8c3086ca9048f7f415f122ed82e53884a9ec193646b42deef06/propcache-0.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c80f4ba3e8f00189165999a742ee526ebeccedf6c3f7beb0c7df821e9772435a", size = 62514, upload-time = "2026-05-08T21:00:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/cf/74/66bd798b5b3be70aa1b391f5cc9d6a0a5532d7fd3b19ec0b213e72e6ad9d/propcache-0.5.2-cp312-cp312-win32.whl", hash = "sha256:8c7972d8f193740d9175f0998ab38717e6cd322d5935c5b0fef8c0d323fd9031", size = 39018, upload-time = "2026-05-08T21:00:31.622Z" }, + { url = "https://files.pythonhosted.org/packages/61/7c/5c0d34aa3024694d6dcb9271cdbdd08c4e47c1c0ad95ec7e7bc74cdea145/propcache-0.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:d9ee8826a7d47863a08ac44e1a5f611a462eefc3a194b492da242128bec75b42", size = 42322, upload-time = "2026-05-08T21:00:32.918Z" }, + { url = "https://files.pythonhosted.org/packages/4d/91/875812f1a3feb20ceba818ef39fbe4d92f1081e04ac815c822496d0d038b/propcache-0.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:2800a4a8ead6b28cccd1ec54b59346f0def7922ee1c7598e8499c733cfbb7c84", size = 38172, upload-time = "2026-05-08T21:00:35.124Z" }, + { url = "https://files.pythonhosted.org/packages/c5/09/f049e45385503fe67db75a6b6186a7b9f0c3930366dc960522c312a825b1/propcache-0.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:099aaf4b4d1a02265b92a977edf00b5c4f63b3b17ac6de39b0d637c9cac0188a", size = 94457, upload-time = "2026-05-08T21:00:36.355Z" }, + { url = "https://files.pythonhosted.org/packages/6b/65/83d1d05655baf63113731bd5a1008435e14f8d1e5a06cbe4ec5b23ad7a31/propcache-0.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:68ce1c44c7a813a7f71ea04315a8c7b330b63db99d059a797a4651bb6f69f117", size = 53835, upload-time = "2026-05-08T21:00:38.072Z" }, + { url = "https://files.pythonhosted.org/packages/a9/12/a6ba6482bb5ea3260c000c9b20881c95fa11c6b30173715668259f844ed7/propcache-0.5.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fc299c129490f55f254cd90be0deca4764e36e9a7c08b4aa588479a3bbed3098", size = 54545, upload-time = "2026-05-08T21:00:39.319Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/7fa086f5764c59ec8a8e157cd93aa8497acc00aba9dcdec56bfffb32602d/propcache-0.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a6ae2198be502c10f09b2516e7b5d019816924bc3183a43ce792a7bd6625e6f4", size = 59886, upload-time = "2026-05-08T21:00:40.621Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e4/5d7663dc8235956c8f5281698a3af1d351d8820341ddd890f59d9a9127f2/propcache-0.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6041d31504dc1779d700e1edcfb08eea334b357620b06681a4eabb57a74e574e", size = 63261, upload-time = "2026-05-08T21:00:41.775Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4a/15a03adee24d6350da4292caeac44c34c033d2afe5e87eb370f38854560f/propcache-0.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f7eabc04151c78a9f4d5bbb5f1faf571e4defeb4b585e0fe95b60ff2dbe4d3d7", size = 64184, upload-time = "2026-05-08T21:00:43.018Z" }, + { url = "https://files.pythonhosted.org/packages/8b/c6/979176efdaa3d239e36d503d5af63a0a773b36662ed8f52e5b6a6d9fd40e/propcache-0.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4db0ba63d693afd40d249bd93f842b5f144f8fcbb83de05660373bcf30517b1d", size = 61534, upload-time = "2026-05-08T21:00:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/c8/22/63e8cd1bae4c2d2be6493b6b7d10566ddafad88137cfbc99964a1119853c/propcache-0.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1dbcf7675229b35d31abb6547d8ebc8c27a830ac3f9a794edff6254873ec7c0a", size = 61500, upload-time = "2026-05-08T21:00:45.796Z" }, + { url = "https://files.pythonhosted.org/packages/60/5a/28e5d9acbac1cc9ccb67045e8c1b943aa8d79fdf39c93bd73cacd68008ea/propcache-0.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d310c013aad2c72f1c3f2f8dd3279d460a858c551f97aeb8c63e4693cca7b4d2", size = 59994, upload-time = "2026-05-08T21:00:47.093Z" }, + { url = "https://files.pythonhosted.org/packages/f3/40/db650677f554a95b9c01a7c9d93d629e93a15562f5deb4573c9ee136fed2/propcache-0.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:06187263ddad280d05b4d8a8b3bb7d164cbebd469236544a42e6d9b28ac6a4fa", size = 56884, upload-time = "2026-05-08T21:00:48.376Z" }, + { url = "https://files.pythonhosted.org/packages/80/45/70b39b89516ff8b96bf732fa6fded8cef20f293cb1508690101c3c07ec51/propcache-0.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3115559b8effafd63b142ea5ed53d63a16ea6469cbc63dce4ee194b42db5d853", size = 63464, upload-time = "2026-05-08T21:00:49.954Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e2/fa59d3a89eac5534293124af4f1d0d0ada091ce4a0ab4610ce03fd2bdd8d/propcache-0.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:c60462af8e6dc30c35407c7237ea908d777b22862bbee27bc4699c0d8bcdc45a", size = 61588, upload-time = "2026-05-08T21:00:51.281Z" }, + { url = "https://files.pythonhosted.org/packages/0b/97/efb547a55c4bc7381cfb202d6a2239ac621045277bc1ea5dfd3a7f0516c0/propcache-0.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:40314bca9ac559716fe374094fc81c11dcc34b64fd6c585360f5775690505704", size = 64667, upload-time = "2026-05-08T21:00:52.602Z" }, + { url = "https://files.pythonhosted.org/packages/92/56/f5c7d9b4b7595d5127da38974d791b2153f3d1eae6c674af3583ace92ad3/propcache-0.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cfa21e036ce1e1db2be04ba3b85d2df1bb1702fa01932d984c5464c665228ff4", size = 62463, upload-time = "2026-05-08T21:00:54.303Z" }, + { url = "https://files.pythonhosted.org/packages/bd/3b/484a3a65fc9f9f60c41dcd17b428bace5389544e2c680994534a20755066/propcache-0.5.2-cp313-cp313-win32.whl", hash = "sha256:f156a3529f38063b6dbaf356e15602a7f95f8055b1295a438433a6386f10463d", size = 38621, upload-time = "2026-05-08T21:00:55.808Z" }, + { url = "https://files.pythonhosted.org/packages/1c/fd/3f0f10dba4dabad3bf53102be007abf55481067952bde0fdddff439e7c61/propcache-0.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:dfed59d0a5aeb01e242e66ff0300bc4a265a7c05f612d30016f0b60b1017d757", size = 41649, upload-time = "2026-05-08T21:00:57.061Z" }, + { url = "https://files.pythonhosted.org/packages/90/ec/6ce619cc32bb500a482f811f9cd509368b4e58e638d13f2c68f370d6b475/propcache-0.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:ba338430e87ceb9c8f0cf754de38a9860560261e56c00376debd628698a7364f", size = 37636, upload-time = "2026-05-08T21:00:58.646Z" }, + { url = "https://files.pythonhosted.org/packages/1b/82/c1d268bbbf2ef981c5bf0fbbe746db617c66e3bcefe431a1aa8943fbe23a/propcache-0.5.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:a592f5f3da71c8691c788c13cb6734b6d17663d2e1cb8caddf0673d01ef8847d", size = 98872, upload-time = "2026-05-08T21:00:59.889Z" }, + { url = "https://files.pythonhosted.org/packages/f4/d4/52c871e73e864e6b34c0e2d58ac1ec5ccd149497ddc7ad2137ae98323a35/propcache-0.5.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:6a997d0489e9668a384fcfd5061b857aa5361de73191cac204d04b889cfbbafa", size = 56257, upload-time = "2026-05-08T21:01:01.195Z" }, + { url = "https://files.pythonhosted.org/packages/67/f0/9b90ca2a210b3d09bcfcd96ecd0f55545c091535abce2a45de2775cfd357/propcache-0.5.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:10734b5484ea113152ee25a91dccedf81631791805d2c9ccb054958e51842c94", size = 56696, upload-time = "2026-05-08T21:01:02.941Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0e/6e9d4ba07c8e56e21ddec1e75f12148142b21ca83a51871babce095334f4/propcache-0.5.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cafca7e56c12bb02ae16d283742bef25a61122e9dab2b5b3f2ccbe589ce32164", size = 62378, upload-time = "2026-05-08T21:01:04.475Z" }, + { url = "https://files.pythonhosted.org/packages/65/19/c10badaa463dde8a27ce884f8ee2ec37e6035b7c9f5ff0c8f74f06f08dac/propcache-0.5.2-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f064f8d2b59177878b7615df1735cd8fe3462ed6be8c7b217d17a276489c2b7f", size = 65283, upload-time = "2026-05-08T21:01:05.959Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b6/93bea99ca80e19cef6512a8580e5b7857bbe09422d9daa7fd4ef5723306c/propcache-0.5.2-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f78abfa8dfc32376fd1aacf597b2f2fbbe0ea751419aee718af5d4f82537ef8c", size = 66616, upload-time = "2026-05-08T21:01:07.228Z" }, + { url = "https://files.pythonhosted.org/packages/83/e4/5c7462e50625f051f37fb38b8224f7639f667184bbd34424ec83819bb1b7/propcache-0.5.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f7467da8a9822bf1a55336f877340c5bcbd3c482afc43a99771169f74a26dedc", size = 63773, upload-time = "2026-05-08T21:01:08.514Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b6/99238894047b13c823be25027e736626cd414a52a5e30d2c3347c2733529/propcache-0.5.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a6ddc6ac9e25de626c1f129c1b467d7ecd33ce2237d3fd0c4e429feef0a7ee1f", size = 63664, upload-time = "2026-05-08T21:01:09.874Z" }, + { url = "https://files.pythonhosted.org/packages/85/1e/a3a1a63116a2b8edb415a8bb9a6f0c34bd03830b1e18e8ce2904e1dc1cf4/propcache-0.5.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:2f22cbbac9e26a8e864c0985ff1268d5d939d53d9d9411a9824279097e03a2cb", size = 62643, upload-time = "2026-05-08T21:01:11.132Z" }, + { url = "https://files.pythonhosted.org/packages/e4/03/893cf147de2fc6543c5eaa07ad833170e7e2a2385725bbebe8c0503723bb/propcache-0.5.2-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:fc76378c62a0f04d0cd82fbb1a2cd2d7e28fcb40d5873f28a6c44e388aaa2751", size = 59595, upload-time = "2026-05-08T21:01:12.387Z" }, + { url = "https://files.pythonhosted.org/packages/86/3b/04c1a2e12c57766568ba75ba72b3bf2042818d4c1425fab6fc07155c7cff/propcache-0.5.2-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:acd2c8edba48e31e58a363b8cf4e5c7db3b04b3f9e371f601df30d9b0d244836", size = 65711, upload-time = "2026-05-08T21:01:13.676Z" }, + { url = "https://files.pythonhosted.org/packages/1c/34/80f8d0099f8d6bacc4de1624c85672681c8cd1149ca2da0e38fd120b817f/propcache-0.5.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:452b5065457eb9991ec5eb38ff41d6cd4c991c9ac7c531c4d5849ae473a9a13f", size = 64247, upload-time = "2026-05-08T21:01:14.936Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1a/8b08f3a5f1037e9e370c55883ceeeee0f6dd0416fb2d2d67b8bfc91f2a79/propcache-0.5.2-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:3430bb2bfe1331885c427745a751e774ee679fd4344f80b97bf879815fe8fa55", size = 67102, upload-time = "2026-05-08T21:01:16.281Z" }, + { url = "https://files.pythonhosted.org/packages/34/68/8bdb7bb7756d76e005490649d10e4a8369e610c74d619f71e1aedf889e9c/propcache-0.5.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:cef6cea3922890dd6c9654971001fa797b526c16ab5e1e46c05fd6f877be7568", size = 64964, upload-time = "2026-05-08T21:01:17.57Z" }, + { url = "https://files.pythonhosted.org/packages/0a/aa/50fb0b5d3968b61a510926ff8b8465f1d6e976b3ab74496d7a4b9fc42515/propcache-0.5.2-cp313-cp313t-win32.whl", hash = "sha256:72d61e16dd78228b58c5d47be830ff3da7e5f139abdf0aef9d86cde1c5cf2191", size = 42546, upload-time = "2026-05-08T21:01:18.946Z" }, + { url = "https://files.pythonhosted.org/packages/ae/4c/0ddbae64321bd4a95bcbfc19307238016b5b1fee645c84626c8d539e5b74/propcache-0.5.2-cp313-cp313t-win_amd64.whl", hash = "sha256:0958834041a0166d343b8d2cedcd8bcbaeb4fdbe0cf08320c5379f143c3be6e7", size = 46330, upload-time = "2026-05-08T21:01:20.162Z" }, + { url = "https://files.pythonhosted.org/packages/00/d9/9cddc8efb78d8af264c5ec9f6d10b62f57c515feda8d321595f56010fb23/propcache-0.5.2-cp313-cp313t-win_arm64.whl", hash = "sha256:6de8bd93ddde9b992cf2b2e0d796d501a19026b5b9fd87356d7d0779531a8d96", size = 40521, upload-time = "2026-05-08T21:01:21.399Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ea/23ee535d90ce8bcc465a3028eb3cc0ce3bd1005f4bb27710b30587de798d/propcache-0.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:46088abff4cba581dea21ae0467a480526cb25aa5f3c269e909f800328bc3999", size = 94662, upload-time = "2026-05-08T21:01:22.683Z" }, + { url = "https://files.pythonhosted.org/packages/b5/06/c5a52f419b5d8972f8d46a7577476090d8e3263ff589ce40b5ca4968d5be/propcache-0.5.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fc88b26f08d634f7bc819a7852e5214f5802641ab8d9fd5326892292eee1993e", size = 53928, upload-time = "2026-05-08T21:01:23.986Z" }, + { url = "https://files.pythonhosted.org/packages/63/b1/4260d67d6bd85e58a66b72d54ce15d5de789b6f3870cc6bedf8ff9667401/propcache-0.5.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:97797ebb098e670a2f92dd66f32897e30d7615b14e7f59711de23e30a9072539", size = 54650, upload-time = "2026-05-08T21:01:25.305Z" }, + { url = "https://files.pythonhosted.org/packages/70/06/2f46c318e3307cd7a6a7481def374ce838c0fe20084b39dd54b0879d0e99/propcache-0.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ba57fffe4ac99c5d30076161b5866336d97600769bad35cc68f7774b15298a4e", size = 59912, upload-time = "2026-05-08T21:01:26.545Z" }, + { url = "https://files.pythonhosted.org/packages/4c/29/fe1aebec2ce57ab985a9c382bded1124431f85078113aa222c5d278430d4/propcache-0.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:583c19759d9eec1e5b69e2fbef36a7d9c326041be9746cb822d335c8cedc2979", size = 63300, upload-time = "2026-05-08T21:01:27.937Z" }, + { url = "https://files.pythonhosted.org/packages/b4/18/2334b26768b6c82be8c69e83671b767d5ef426aa09b0cba6c2ea47816774/propcache-0.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d0326e2e5e1f3163fa306c834e48e8d490e5fae607a097a40c0648109b47ba80", size = 64208, upload-time = "2026-05-08T21:01:29.484Z" }, + { url = "https://files.pythonhosted.org/packages/2b/76/7f1bfd6afff4c5e38e36a3c6d68eb5f4b7311ea80baf693db78d95b603c4/propcache-0.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e00820e192c8dbebcafb383ebbf99030895f09905e7a0eb2e0340a0bcc2bc825", size = 61633, upload-time = "2026-05-08T21:01:31.068Z" }, + { url = "https://files.pythonhosted.org/packages/c4/46/b3ff8aba2b4953a3e50de2cf72f1b5748b8eca93b15f3dc2c84339084c09/propcache-0.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c66afea89b1e43725731d2004732a046fe6fe955d51f952c3e95a7314a284a39", size = 61724, upload-time = "2026-05-08T21:01:32.374Z" }, + { url = "https://files.pythonhosted.org/packages/c5/01/814cfcafbcff954f94c01cf30e097ddc88a076b5440fbcf4570753437d40/propcache-0.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d4dc37dec6c6cdad0b57881a5658fd14fbf53e333b1a86cf86559f190e1d9ec4", size = 60069, upload-time = "2026-05-08T21:01:33.67Z" }, + { url = "https://files.pythonhosted.org/packages/da/68/5c6f7622d510cc666a300687e06fd060c1a43361c0c9b20d284f06d8096a/propcache-0.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:5570dbcc97571c15f68068e529c92715a12f8d54030e272d264b377e22bd17a5", size = 57099, upload-time = "2026-05-08T21:01:34.915Z" }, + { url = "https://files.pythonhosted.org/packages/55/27/9cb0b4c679124085327957d42521c99dba04c88c90c3e55a6f0b633ebccc/propcache-0.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f814362777a9f841adddb200ecdf8f5cb1e5a3c4b7a86378edbd6ccb26edd702", size = 63391, upload-time = "2026-05-08T21:01:36.231Z" }, + { url = "https://files.pythonhosted.org/packages/f0/9d/7258aaa5bdf60fc6f27591eef6fe52768cb0beda7140be477c8b12c9794a/propcache-0.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:196913dea116aeb5a2ba95af4ddcb7ea85559ae07d8eee8751688310d09168c3", size = 61626, upload-time = "2026-05-08T21:01:37.545Z" }, + { url = "https://files.pythonhosted.org/packages/8e/0d/41c602003e8a9b16fe1e7eadf62c7bfba9d5474370b24200bf48b315f45f/propcache-0.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6e7b8719005dd1175be4ab1cd25e9b98659a5e0347331506ec6760d2773a7fb5", size = 64781, upload-time = "2026-05-08T21:01:38.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f3/38e66b1856e9bd079deea015bc4a55f7767c0e4db2f7dcf69e7e680ba4ce/propcache-0.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:51f96d685ab16e88cab128cd37a52c5da540809c8b879fa047731bfcb4ad35a4", size = 62570, upload-time = "2026-05-08T21:01:40.415Z" }, + { url = "https://files.pythonhosted.org/packages/95/ca/bbfe9b910ce57dde8bb4876b4520fc02a4e89497c10de26be936758a3aaa/propcache-0.5.2-cp314-cp314-win32.whl", hash = "sha256:cc6fc3cc62e8501d3ed62894425040d2728ecddb1ed072737a5c70bd537aa9f0", size = 39436, upload-time = "2026-05-08T21:01:41.654Z" }, + { url = "https://files.pythonhosted.org/packages/61/d2/45c9defbaa1ea297035d9d4cce9e8f80daafbf19319c6007f157c6256ea9/propcache-0.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:81e3a30b0bb60caa22033dd0f8a3618d1d67356212514f62c57db75cb0ef410c", size = 42373, upload-time = "2026-05-08T21:01:43.041Z" }, + { url = "https://files.pythonhosted.org/packages/44/68/9ea5103f41d5217d7d6ec24db90018e23aebec070c3f9a6e54d12b841fd8/propcache-0.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:0d2c9bf8528f135dbb805ce027567e09164f7efa51a2be07458a2c0420f292d0", size = 38554, upload-time = "2026-05-08T21:01:44.336Z" }, + { url = "https://files.pythonhosted.org/packages/8a/81/fadf555f42d3b762eea8a53950b0489fdc0aa9da5f8ed9e10ce0a4e01b48/propcache-0.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4bc8ff1feffc6a61c7002ffe84634c41b822e104990ae009f44a0834430070bb", size = 99395, upload-time = "2026-05-08T21:01:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/f5/c9/c61e134a686949cf7971af3a390148b1156f7be81c73bc0cd12c873e2d48/propcache-0.5.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79aa3ff0a9b566633b642fa9caf7e21ed1c13d6feca718187873f199e1514078", size = 56653, upload-time = "2026-05-08T21:01:47.307Z" }, + { url = "https://files.pythonhosted.org/packages/cb/73/daf935ea7048ddd7ec8eec5345b4a40b619d2d178b3c0a0900796bc3c794/propcache-0.5.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1b31822f4474c4036bae62de9402710051d431a606d6a0f907fec79935a071aa", size = 56914, upload-time = "2026-05-08T21:01:48.573Z" }, + { url = "https://files.pythonhosted.org/packages/79/9f/aba959b435ea18617edd7cf0a7ad0b9c574b8fc7e3d2cd55fb59cb255d33/propcache-0.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13fef48778b5a2a756523fdb781326b028ca75e32858b04f2cdd19f394564917", size = 62567, upload-time = "2026-05-08T21:01:49.903Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a1/859942de9a791ff42f6141736f5b37749b8f53e65edfa49638c67dd67e6a/propcache-0.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8b73ab70f1a3351fbc71f663b3e645af6dd0329100c353081cf69c37433fc6fe", size = 65542, upload-time = "2026-05-08T21:01:51.204Z" }, + { url = "https://files.pythonhosted.org/packages/b5/61/315bc0fd6c0fc7f80a528b8afd209e5fc4a875ea79571b91b8f50f442907/propcache-0.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5538d2c13d93e4698af7e092b57bc7298fd35d1d58e656ae18f23ee0d0378e03", size = 66845, upload-time = "2026-05-08T21:01:52.539Z" }, + { url = "https://files.pythonhosted.org/packages/47/f7/9f8122e3132e8e354ac41975ef8f1099be7d5a16bc7ae562734e993665c0/propcache-0.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cd645f03898405cabe694fb8bc35241e3a9c332ec85627584fe3de201452b335", size = 63985, upload-time = "2026-05-08T21:01:53.847Z" }, + { url = "https://files.pythonhosted.org/packages/c8/54/c317819ec157cbf6f35df9df9657a6f82daf34d5faf15948b2f639c2192e/propcache-0.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a473b3440261e0c60706e732b2ed2f517857344fc21bf48fdfe211e2d98eb285", size = 63999, upload-time = "2026-05-08T21:01:55.179Z" }, + { url = "https://files.pythonhosted.org/packages/5a/56/387e3f7dfce0a9233df41fb888aa1c30222cb4bbbf09537c02dd9bd85fe2/propcache-0.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7afa37062e6650640e932e4cc9297d81f9f42d9944029cc386b8247dea4da837", size = 62779, upload-time = "2026-05-08T21:01:57.489Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9c/596784cb5824ed61ee960d3f8655a3f0993e107c6e98ab6c818b7fb92ccb/propcache-0.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:8a90efd5777e996e42d568db9ac740b944d691e565cbfd31b2f7832f9184b2b8", size = 59796, upload-time = "2026-05-08T21:01:58.736Z" }, + { url = "https://files.pythonhosted.org/packages/c2/3d/1a6cfa1726a48542c1e8784a0761421476a5b68e09b7f36bf95eb954aaba/propcache-0.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:f19bb891234d72535764d703bfed1153cc34f4214d5bd7150aee1eec9e8f4366", size = 66023, upload-time = "2026-05-08T21:02:00.228Z" }, + { url = "https://files.pythonhosted.org/packages/e4/0e/05fd6990369477076e4e280bcb970de760fddf0161a46e988bc95f7940ec/propcache-0.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:32775082acd2d807ee3db715c7770d38767b817870acfa08c29e057f3c4d5b56", size = 64448, upload-time = "2026-05-08T21:02:01.888Z" }, + { url = "https://files.pythonhosted.org/packages/cd/86/5f8da315a4309c62c10c0b2516b17492d5d3bbe1bb862b96604db67e2a37/propcache-0.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9282fb1a3bccd038da9f768b927b24a0c753e466c086b7c4f3c6982851eefb2d", size = 67329, upload-time = "2026-05-08T21:02:03.484Z" }, + { url = "https://files.pythonhosted.org/packages/da/d3/3368efe79ab21f0cdf86ef49895811c9cc933131d4cde1f28a624e22e712/propcache-0.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cc49723e2f60d6b32a0f0b08a3fd6d13203c07f1cd9566cfce0f12a917c967a2", size = 65172, upload-time = "2026-05-08T21:02:04.745Z" }, + { url = "https://files.pythonhosted.org/packages/d5/07/127e8b0bacfb325396196f9d976a22453049b89b9b2b08477cc3145faa44/propcache-0.5.2-cp314-cp314t-win32.whl", hash = "sha256:2d7aa89ebca5acc98cba9d1472d976e394782f587bad6661003602a619fd1821", size = 43813, upload-time = "2026-05-08T21:02:06.025Z" }, + { url = "https://files.pythonhosted.org/packages/88/fb/46dad6c0ae49ed230ab1b16c890c2b6314e2403e6c412976f4a72d64a527/propcache-0.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:d447bb0b3054be5818458fbb171208b1d9ff11eba14e18ca18b90cbb45767370", size = 47764, upload-time = "2026-05-08T21:02:07.353Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c4/a47d0a63aa309d10d59ede6e9d4cff03a344a79d1f0f4cd0cd74997b53e0/propcache-0.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:fe67a3d11cd9b4efabfa45c3d00ffba2b26811442a73a581a94b67c2b5faccf6", size = 41140, upload-time = "2026-05-08T21:02:09.065Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ed/1cdcab6ba3d6ab7feca11fc14f0eeea80755bb53ef4e892079f31b10a25f/propcache-0.5.2-py3-none-any.whl", hash = "sha256:be1ddfcbb376e3de5d2e2db1d58d6d67463e6b4f9f040c000de8e300295465fe", size = 14036, upload-time = "2026-05-08T21:02:10.673Z" }, +] + +[[package]] +name = "psutil" +version = "7.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" }, + { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" }, + { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" }, + { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" }, + { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" }, + { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" }, + { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" }, + { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" }, + { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" }, + { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" }, + { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" }, + { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" }, + { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, + { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, + { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, + { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, + { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, + { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, +] + +[[package]] +name = "ptyprocess" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" }, +] + +[[package]] +name = "pure-eval" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/05/0a34433a064256a578f1783a10da6df098ceaa4a57bbeaa96a6c0352786b/pure_eval-0.2.3.tar.gz", hash = "sha256:5f4e983f40564c576c7c8635ae88db5956bb2229d7e9237d03b3c0b0190eaf42", size = 19752, upload-time = "2024-07-21T12:58:21.801Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8e/37/efad0257dc6e593a18957422533ff0f87ede7c9c6ea010a2177d738fb82f/pure_eval-0.2.3-py3-none-any.whl", hash = "sha256:1db8e35b67b3d218d818ae653e27f06c3aa420901fa7b081ca98cbedc874e0d0", size = 11842, upload-time = "2024-07-21T12:58:20.04Z" }, +] + +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[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.1.1" +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/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[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 = "pyzmq" +version = "27.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "implementation_name == 'pypy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/04/0b/3c9baedbdf613ecaa7aa07027780b8867f57b6293b6ee50de316c9f3222b/pyzmq-27.1.0.tar.gz", hash = "sha256:ac0765e3d44455adb6ddbf4417dcce460fc40a05978c08efdf2948072f6db540", size = 281750, upload-time = "2025-09-08T23:10:18.157Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/e7/038aab64a946d535901103da16b953c8c9cc9c961dadcbf3609ed6428d23/pyzmq-27.1.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:452631b640340c928fa343801b0d07eb0c3789a5ffa843f6e1a9cee0ba4eb4fc", size = 1306279, upload-time = "2025-09-08T23:08:03.807Z" }, + { url = "https://files.pythonhosted.org/packages/e8/5e/c3c49fdd0f535ef45eefcc16934648e9e59dace4a37ee88fc53f6cd8e641/pyzmq-27.1.0-cp312-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1c179799b118e554b66da67d88ed66cd37a169f1f23b5d9f0a231b4e8d44a113", size = 895645, upload-time = "2025-09-08T23:08:05.301Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e5/b0b2504cb4e903a74dcf1ebae157f9e20ebb6ea76095f6cfffea28c42ecd/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3837439b7f99e60312f0c926a6ad437b067356dc2bc2ec96eb395fd0fe804233", size = 652574, upload-time = "2025-09-08T23:08:06.828Z" }, + { url = "https://files.pythonhosted.org/packages/f8/9b/c108cdb55560eaf253f0cbdb61b29971e9fb34d9c3499b0e96e4e60ed8a5/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43ad9a73e3da1fab5b0e7e13402f0b2fb934ae1c876c51d0afff0e7c052eca31", size = 840995, upload-time = "2025-09-08T23:08:08.396Z" }, + { url = "https://files.pythonhosted.org/packages/c2/bb/b79798ca177b9eb0825b4c9998c6af8cd2a7f15a6a1a4272c1d1a21d382f/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0de3028d69d4cdc475bfe47a6128eb38d8bc0e8f4d69646adfbcd840facbac28", size = 1642070, upload-time = "2025-09-08T23:08:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/9c/80/2df2e7977c4ede24c79ae39dcef3899bfc5f34d1ca7a5b24f182c9b7a9ca/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:cf44a7763aea9298c0aa7dbf859f87ed7012de8bda0f3977b6fb1d96745df856", size = 2021121, upload-time = "2025-09-08T23:08:11.907Z" }, + { url = "https://files.pythonhosted.org/packages/46/bd/2d45ad24f5f5ae7e8d01525eb76786fa7557136555cac7d929880519e33a/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f30f395a9e6fbca195400ce833c731e7b64c3919aa481af4d88c3759e0cb7496", size = 1878550, upload-time = "2025-09-08T23:08:13.513Z" }, + { url = "https://files.pythonhosted.org/packages/e6/2f/104c0a3c778d7c2ab8190e9db4f62f0b6957b53c9d87db77c284b69f33ea/pyzmq-27.1.0-cp312-abi3-win32.whl", hash = "sha256:250e5436a4ba13885494412b3da5d518cd0d3a278a1ae640e113c073a5f88edd", size = 559184, upload-time = "2025-09-08T23:08:15.163Z" }, + { url = "https://files.pythonhosted.org/packages/fc/7f/a21b20d577e4100c6a41795842028235998a643b1ad406a6d4163ea8f53e/pyzmq-27.1.0-cp312-abi3-win_amd64.whl", hash = "sha256:9ce490cf1d2ca2ad84733aa1d69ce6855372cb5ce9223802450c9b2a7cba0ccf", size = 619480, upload-time = "2025-09-08T23:08:17.192Z" }, + { url = "https://files.pythonhosted.org/packages/78/c2/c012beae5f76b72f007a9e91ee9401cb88c51d0f83c6257a03e785c81cc2/pyzmq-27.1.0-cp312-abi3-win_arm64.whl", hash = "sha256:75a2f36223f0d535a0c919e23615fc85a1e23b71f40c7eb43d7b1dedb4d8f15f", size = 552993, upload-time = "2025-09-08T23:08:18.926Z" }, + { url = "https://files.pythonhosted.org/packages/60/cb/84a13459c51da6cec1b7b1dc1a47e6db6da50b77ad7fd9c145842750a011/pyzmq-27.1.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:93ad4b0855a664229559e45c8d23797ceac03183c7b6f5b4428152a6b06684a5", size = 1122436, upload-time = "2025-09-08T23:08:20.801Z" }, + { url = "https://files.pythonhosted.org/packages/dc/b6/94414759a69a26c3dd674570a81813c46a078767d931a6c70ad29fc585cb/pyzmq-27.1.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:fbb4f2400bfda24f12f009cba62ad5734148569ff4949b1b6ec3b519444342e6", size = 1156301, upload-time = "2025-09-08T23:08:22.47Z" }, + { url = "https://files.pythonhosted.org/packages/a5/ad/15906493fd40c316377fd8a8f6b1f93104f97a752667763c9b9c1b71d42d/pyzmq-27.1.0-cp313-cp313t-macosx_10_15_universal2.whl", hash = "sha256:e343d067f7b151cfe4eb3bb796a7752c9d369eed007b91231e817071d2c2fec7", size = 1341197, upload-time = "2025-09-08T23:08:24.286Z" }, + { url = "https://files.pythonhosted.org/packages/14/1d/d343f3ce13db53a54cb8946594e567410b2125394dafcc0268d8dda027e0/pyzmq-27.1.0-cp313-cp313t-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:08363b2011dec81c354d694bdecaef4770e0ae96b9afea70b3f47b973655cc05", size = 897275, upload-time = "2025-09-08T23:08:26.063Z" }, + { url = "https://files.pythonhosted.org/packages/69/2d/d83dd6d7ca929a2fc67d2c3005415cdf322af7751d773524809f9e585129/pyzmq-27.1.0-cp313-cp313t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d54530c8c8b5b8ddb3318f481297441af102517602b569146185fa10b63f4fa9", size = 660469, upload-time = "2025-09-08T23:08:27.623Z" }, + { url = "https://files.pythonhosted.org/packages/3e/cd/9822a7af117f4bc0f1952dbe9ef8358eb50a24928efd5edf54210b850259/pyzmq-27.1.0-cp313-cp313t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f3afa12c392f0a44a2414056d730eebc33ec0926aae92b5ad5cf26ebb6cc128", size = 847961, upload-time = "2025-09-08T23:08:29.672Z" }, + { url = "https://files.pythonhosted.org/packages/9a/12/f003e824a19ed73be15542f172fd0ec4ad0b60cf37436652c93b9df7c585/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c65047adafe573ff023b3187bb93faa583151627bc9c51fc4fb2c561ed689d39", size = 1650282, upload-time = "2025-09-08T23:08:31.349Z" }, + { url = "https://files.pythonhosted.org/packages/d5/4a/e82d788ed58e9a23995cee70dbc20c9aded3d13a92d30d57ec2291f1e8a3/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:90e6e9441c946a8b0a667356f7078d96411391a3b8f80980315455574177ec97", size = 2024468, upload-time = "2025-09-08T23:08:33.543Z" }, + { url = "https://files.pythonhosted.org/packages/d9/94/2da0a60841f757481e402b34bf4c8bf57fa54a5466b965de791b1e6f747d/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:add071b2d25f84e8189aaf0882d39a285b42fa3853016ebab234a5e78c7a43db", size = 1885394, upload-time = "2025-09-08T23:08:35.51Z" }, + { url = "https://files.pythonhosted.org/packages/4f/6f/55c10e2e49ad52d080dc24e37adb215e5b0d64990b57598abc2e3f01725b/pyzmq-27.1.0-cp313-cp313t-win32.whl", hash = "sha256:7ccc0700cfdf7bd487bea8d850ec38f204478681ea02a582a8da8171b7f90a1c", size = 574964, upload-time = "2025-09-08T23:08:37.178Z" }, + { url = "https://files.pythonhosted.org/packages/87/4d/2534970ba63dd7c522d8ca80fb92777f362c0f321900667c615e2067cb29/pyzmq-27.1.0-cp313-cp313t-win_amd64.whl", hash = "sha256:8085a9fba668216b9b4323be338ee5437a235fe275b9d1610e422ccc279733e2", size = 641029, upload-time = "2025-09-08T23:08:40.595Z" }, + { url = "https://files.pythonhosted.org/packages/f6/fa/f8aea7a28b0641f31d40dea42d7ef003fded31e184ef47db696bc74cd610/pyzmq-27.1.0-cp313-cp313t-win_arm64.whl", hash = "sha256:6bb54ca21bcfe361e445256c15eedf083f153811c37be87e0514934d6913061e", size = 561541, upload-time = "2025-09-08T23:08:42.668Z" }, + { url = "https://files.pythonhosted.org/packages/87/45/19efbb3000956e82d0331bafca5d9ac19ea2857722fa2caacefb6042f39d/pyzmq-27.1.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ce980af330231615756acd5154f29813d553ea555485ae712c491cd483df6b7a", size = 1341197, upload-time = "2025-09-08T23:08:44.973Z" }, + { url = "https://files.pythonhosted.org/packages/48/43/d72ccdbf0d73d1343936296665826350cb1e825f92f2db9db3e61c2162a2/pyzmq-27.1.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1779be8c549e54a1c38f805e56d2a2e5c009d26de10921d7d51cfd1c8d4632ea", size = 897175, upload-time = "2025-09-08T23:08:46.601Z" }, + { url = "https://files.pythonhosted.org/packages/2f/2e/a483f73a10b65a9ef0161e817321d39a770b2acf8bcf3004a28d90d14a94/pyzmq-27.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7200bb0f03345515df50d99d3db206a0a6bee1955fbb8c453c76f5bf0e08fb96", size = 660427, upload-time = "2025-09-08T23:08:48.187Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d2/5f36552c2d3e5685abe60dfa56f91169f7a2d99bbaf67c5271022ab40863/pyzmq-27.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01c0e07d558b06a60773744ea6251f769cd79a41a97d11b8bf4ab8f034b0424d", size = 847929, upload-time = "2025-09-08T23:08:49.76Z" }, + { url = "https://files.pythonhosted.org/packages/c4/2a/404b331f2b7bf3198e9945f75c4c521f0c6a3a23b51f7a4a401b94a13833/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:80d834abee71f65253c91540445d37c4c561e293ba6e741b992f20a105d69146", size = 1650193, upload-time = "2025-09-08T23:08:51.7Z" }, + { url = "https://files.pythonhosted.org/packages/1c/0b/f4107e33f62a5acf60e3ded67ed33d79b4ce18de432625ce2fc5093d6388/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:544b4e3b7198dde4a62b8ff6685e9802a9a1ebf47e77478a5eb88eca2a82f2fd", size = 2024388, upload-time = "2025-09-08T23:08:53.393Z" }, + { url = "https://files.pythonhosted.org/packages/0d/01/add31fe76512642fd6e40e3a3bd21f4b47e242c8ba33efb6809e37076d9b/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cedc4c68178e59a4046f97eca31b148ddcf51e88677de1ef4e78cf06c5376c9a", size = 1885316, upload-time = "2025-09-08T23:08:55.702Z" }, + { url = "https://files.pythonhosted.org/packages/c4/59/a5f38970f9bf07cee96128de79590bb354917914a9be11272cfc7ff26af0/pyzmq-27.1.0-cp314-cp314t-win32.whl", hash = "sha256:1f0b2a577fd770aa6f053211a55d1c47901f4d537389a034c690291485e5fe92", size = 587472, upload-time = "2025-09-08T23:08:58.18Z" }, + { url = "https://files.pythonhosted.org/packages/70/d8/78b1bad170f93fcf5e3536e70e8fadac55030002275c9a29e8f5719185de/pyzmq-27.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:19c9468ae0437f8074af379e986c5d3d7d7bfe033506af442e8c879732bedbe0", size = 661401, upload-time = "2025-09-08T23:08:59.802Z" }, + { url = "https://files.pythonhosted.org/packages/81/d6/4bfbb40c9a0b42fc53c7cf442f6385db70b40f74a783130c5d0a5aa62228/pyzmq-27.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:dc5dbf68a7857b59473f7df42650c621d7e8923fb03fa74a526890f4d33cc4d7", size = 575170, upload-time = "2025-09-08T23:09:01.418Z" }, +] + +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + +[[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 = "rpds-py" +version = "2026.6.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5c/be/2e8974163072e7bab7df1a5acd54c4498e75e35d6d18b864d3a9d5dadc92/rpds_py-2026.6.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0", size = 343691, upload-time = "2026-06-30T07:15:14.96Z" }, + { url = "https://files.pythonhosted.org/packages/a4/73/319dfa745dd668efe89309141ded489126461fcecd2b8f3a3cda185129b6/rpds_py-2026.6.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf", size = 338542, upload-time = "2026-06-30T07:15:16.267Z" }, + { url = "https://files.pythonhosted.org/packages/21/63/4239893be1c4d09b709b1a8f6be4188f0870084ff547f46606b8a75f1b03/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24", size = 368180, upload-time = "2026-06-30T07:15:17.62Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ca/9c5de382225234ceb37b1844ebdb140db12b2a278bb9efe2fcd19f6c82ce/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e", size = 375067, upload-time = "2026-06-30T07:15:18.952Z" }, + { url = "https://files.pythonhosted.org/packages/87/dc/863f69d1bf04ade34b7fe0d59b9fdf6f0135fe2d7cbca74f1d665589559d/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975", size = 490509, upload-time = "2026-06-30T07:15:20.434Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ef/eac16a12048b45ec7c7fa94f2be3438a5f26bf9cc8580b18a1cfd609b7f6/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680", size = 382754, upload-time = "2026-06-30T07:15:21.831Z" }, + { url = "https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6", size = 366189, upload-time = "2026-06-30T07:15:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/e3/29/41a7b0e98a4b44cd676ab7598419623373eb43b20be68c084935c1a8cf88/rpds_py-2026.6.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a", size = 377750, upload-time = "2026-06-30T07:15:24.659Z" }, + { url = "https://files.pythonhosted.org/packages/2e/05/ecda0bec46f9a1565090bcdc941d023f6a25aff85fda28f89f8d19878152/rpds_py-2026.6.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4", size = 395576, upload-time = "2026-06-30T07:15:25.987Z" }, + { url = "https://files.pythonhosted.org/packages/68/a8/6ed52f03ee6cb854ce78785cc9a9a672eb880e83fd7224d471f667d151f1/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa", size = 543807, upload-time = "2026-06-30T07:15:27.356Z" }, + { url = "https://files.pythonhosted.org/packages/8f/d6/156c0d3eea27ba09b92562ba2364ba124c0a061b199e17eac637cd25a5e2/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc", size = 611187, upload-time = "2026-06-30T07:15:28.931Z" }, + { url = "https://files.pythonhosted.org/packages/f1/31/774212ed989c62f7f310220089f9b0a3fb8f40f5443d1727abd5d9f52bc9/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822", size = 573030, upload-time = "2026-06-30T07:15:30.553Z" }, + { url = "https://files.pythonhosted.org/packages/c9/50/22f73127a41f1ce4f87fe39aadfb9a126345801c274aa93ae88456249327/rpds_py-2026.6.3-cp312-cp312-win32.whl", hash = "sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed", size = 202185, upload-time = "2026-06-30T07:15:32.027Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/f0ee4d4dde9d3b69dedf1b5f74e7a40017046d55052d173e418c6a94f960/rpds_py-2026.6.3-cp312-cp312-win_amd64.whl", hash = "sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f", size = 220394, upload-time = "2026-06-30T07:15:33.359Z" }, + { url = "https://files.pythonhosted.org/packages/f3/83/3382fe37f809b59f02aac04dbc4e765b480b46ee0227ed516e3bdc4d3dfc/rpds_py-2026.6.3-cp312-cp312-win_arm64.whl", hash = "sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96", size = 215753, upload-time = "2026-06-30T07:15:34.778Z" }, + { url = "https://files.pythonhosted.org/packages/a4/9e/b818ee580026ec578138e961027a68820c40afeb1ec8f6819b54fb99e196/rpds_py-2026.6.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:3cfe765c1da0072636ca06628261e0ea05688e160d5c8a03e0217c3854037223", size = 343012, upload-time = "2026-06-30T07:15:36.005Z" }, + { url = "https://files.pythonhosted.org/packages/f3/6b/686d9dc4359a8f163cfbbf89ee0b4e586431de22fe8248edb63a8cf50d49/rpds_py-2026.6.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f4d78253f6996be4901669ad25319f842f740eccf4d58e3c7f3dd39e6dde1d8f", size = 338203, upload-time = "2026-06-30T07:15:37.462Z" }, + { url = "https://files.pythonhosted.org/packages/9e/9b/069aa329940f8207615e091f5eedbbd40e1e15eac68a0790fd05ccdf796c/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:54f45a148e28767bf343d33a684693c70e451c6f4c0e9904709a723fafbdfc1f", size = 367984, upload-time = "2026-06-30T07:15:39.008Z" }, + { url = "https://files.pythonhosted.org/packages/14/db/34c203e4becff3703e4d3bc121842c00b8689197f398161203a880052f4e/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:842e7b070435622248c7a2c44ae53fa1440e073cc3023bc919fed570884097a7", size = 374815, upload-time = "2026-06-30T07:15:40.253Z" }, + { url = "https://files.pythonhosted.org/packages/ee/7d/8071067d2cc453d916ad836e828c943f575e8a44612537759002a1e07381/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8020133a74bd81b4572dd8e4be028a6b1ebcd70e6726edc3918008c08bee6ee6", size = 490545, upload-time = "2026-06-30T07:15:41.729Z" }, + { url = "https://files.pythonhosted.org/packages/a3/42/da06c5aa8f0484ff07f270787434204d9f4535e2f8c3b51ed402267e63c3/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cdc7e35386f3847df728fbcb5e887e2d79c19e2fa1eba9e51b6621d23e3243af", size = 382828, upload-time = "2026-06-30T07:15:43.327Z" }, + { url = "https://files.pythonhosted.org/packages/57/d7/fe978efc2ae50abe48eb7464668ea99f53c010c60aeebb7b35ad27f23661/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acac386b453c2516111b50985d60ce46e7fadb5ea71ae7b25f4c946935bf27cf", size = 365678, upload-time = "2026-06-30T07:15:44.992Z" }, + { url = "https://files.pythonhosted.org/packages/69/9d/1d8922e1990b2a6eb532b6ff53d3e73d2b3bbffc84116c75826bee73dfc6/rpds_py-2026.6.3-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:425560c6fa0415f27261727bb20bd097568485e5eb0c121f1949417d1c516885", size = 377811, upload-time = "2026-06-30T07:15:46.523Z" }, + { url = "https://files.pythonhosted.org/packages/b1/3d/198dceafb4fb034a6a47347e1b0735d34e0bd4a50be4e898d408ee66cb14/rpds_py-2026.6.3-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a550fb4950a06dde3beb4721f5ad4b25bf4513784665b0a8522c792e2bd822a4", size = 395382, upload-time = "2026-06-30T07:15:47.955Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f1/13968e49655d40b6b19d8b9140296bbc6f1d86b3f0f6c346cf9f1adddf4b/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f4bca01b63096f606e095734dd56e74e175f94cfbf24ff3d63281cec61f7bb7", size = 543832, upload-time = "2026-06-30T07:15:49.33Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ab/289bcb1b90bd3e40a2900c561fa0e2087345ecbb094f0b870f2345142b7c/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ccffae9a092a00deb7efd545fe5e2c33c33b88e7c054337e9a74c179347d0b7d", size = 611011, upload-time = "2026-06-30T07:15:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/1e/16/5043105e679436ccfbc8e5e0dd2d663ed18a8b8113515fd06a5e5d77c83e/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1cf01971c4f2c5553b772a542e4aaf191789cd331bc2cd4ff0e6e65ba49e1e97", size = 572431, upload-time = "2026-06-30T07:15:52.394Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/adab103321c0a6565d5ae1c2998349bc3ee175b82ccc5ae8fc04cc413075/rpds_py-2026.6.3-cp313-cp313-win32.whl", hash = "sha256:8c3d1e9c15b9d51ca0391e13da1a25a0a4df3c58a37c9dc368e0736cf7f69df0", size = 201710, upload-time = "2026-06-30T07:15:53.894Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ed/a03b09668e74e5dabbf2e211f6468e1820c0552f7b0500082da31841bf7b/rpds_py-2026.6.3-cp313-cp313-win_amd64.whl", hash = "sha256:9250a9a0a6fd4648b3f868da8d91a4c52b5811a62df58e753d50ae4454a36f80", size = 219454, upload-time = "2026-06-30T07:15:55.25Z" }, + { url = "https://files.pythonhosted.org/packages/27/17/b8642c12930b71bc2b25831f6708ccf0f75abcd11883932ec9ce54ba3a78/rpds_py-2026.6.3-cp313-cp313-win_arm64.whl", hash = "sha256:900a67df3fd1660b035a4761c4ce73c382ea6b35f90f9863c36c6fd8bf8b09bb", size = 215063, upload-time = "2026-06-30T07:15:56.573Z" }, + { url = "https://files.pythonhosted.org/packages/b6/36/7fbe9dcdaf857fb3f63c2a2284b62492d95f5e8334e947e5fb6e7f68c9be/rpds_py-2026.6.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e", size = 344510, upload-time = "2026-06-30T07:15:57.921Z" }, + { url = "https://files.pythonhosted.org/packages/ba/54/f785cc3d3f60839ca57a5af4927a9f347b07b2799c373fc20f7949f87c7e/rpds_py-2026.6.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd", size = 339495, upload-time = "2026-06-30T07:15:59.238Z" }, + { url = "https://files.pythonhosted.org/packages/63/ef/d4cdaf309e6b095b43597103cf8c0b951d6cca2acce68c474f75ec12e0c7/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d", size = 369454, upload-time = "2026-06-30T07:16:01.021Z" }, + { url = "https://files.pythonhosted.org/packages/96/4a/9559a68b7ee15db09d7981212e8c2e219d2a1d6d4faa0391d813c3496a36/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda", size = 374583, upload-time = "2026-06-30T07:16:02.287Z" }, + { url = "https://files.pythonhosted.org/packages/ef/75/8964aa7d2c6e8ac43eba8eb6e6b0fdda1f46d39f2fc3e6aa9f2cb17f485d/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8", size = 492919, upload-time = "2026-06-30T07:16:03.723Z" }, + { url = "https://files.pythonhosted.org/packages/8f/97/6908094ac804115e65aedfd90f1b5fee4eebebd3f6c4cfc5419939267565/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53", size = 383725, upload-time = "2026-06-30T07:16:05.305Z" }, + { url = "https://files.pythonhosted.org/packages/d1/9c/0d1fdc2e7aba23e290d603bc494e97bd205bae262ce33c6b32a69768ed5e/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504", size = 367255, upload-time = "2026-06-30T07:16:07.086Z" }, + { url = "https://files.pythonhosted.org/packages/c4/fe/f0209ca4a9ed074bc8acb44dfd0e81c3122e94c9689f5645b7973a866719/rpds_py-2026.6.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc", size = 379060, upload-time = "2026-06-30T07:16:08.525Z" }, + { url = "https://files.pythonhosted.org/packages/c6/8d/f1cc54c616b9d8897de8738aac148d20afca93f68187475fe194d09a71b9/rpds_py-2026.6.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77", size = 395960, upload-time = "2026-06-30T07:16:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/fb/04/aafff00f73aeca2945f734f1d483c64ab8f472d0864ab02377fd8e89c3b2/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698", size = 545356, upload-time = "2026-06-30T07:16:11.816Z" }, + { url = "https://files.pythonhosted.org/packages/fd/cc/e229663b9e4ddac5a4acbe9085dd80a71af2a5d356b8b39d6bff233f24b0/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd", size = 612319, upload-time = "2026-06-30T07:16:13.586Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7a/8a0e6d3e6cd066af108b71b43122c3fe158dd9eb86acac626593a2582eb1/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d", size = 573508, upload-time = "2026-06-30T07:16:15.23Z" }, + { url = "https://files.pythonhosted.org/packages/87/03/2a69ab618a789cf6cf85c86bb844c62d090e700ab1a2aa676b3741b6c516/rpds_py-2026.6.3-cp314-cp314-win32.whl", hash = "sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8", size = 202504, upload-time = "2026-06-30T07:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/85/62/a3892ba945f4e24c78f352e5de3c7620d8479f73f211406a97263d13c7d2/rpds_py-2026.6.3-cp314-cp314-win_amd64.whl", hash = "sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5", size = 220380, upload-time = "2026-06-30T07:16:18.108Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e7/c2bd44dc831931815ad11ebb5f430b5a0a4d3caa9de837107876c30c3432/rpds_py-2026.6.3-cp314-cp314-win_arm64.whl", hash = "sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703", size = 215976, upload-time = "2026-06-30T07:16:19.654Z" }, + { url = "https://files.pythonhosted.org/packages/79/9c/fff7b74bce9a091ec9a012a03f9ff5f69364eaf9451060dfc4486da2ffdd/rpds_py-2026.6.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90", size = 346840, upload-time = "2026-06-30T07:16:21.268Z" }, + { url = "https://files.pythonhosted.org/packages/e9/44/77bcb1168b33704908295533d27f10eb811e9e3e193e8993dc99572211d3/rpds_py-2026.6.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4", size = 340282, upload-time = "2026-06-30T07:16:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/87/3c/7a9081c7c9e645b39efe19e4ffbeccd80add246327cd9b888aecffd72317/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9", size = 370403, upload-time = "2026-06-30T07:16:24.415Z" }, + { url = "https://files.pythonhosted.org/packages/f7/69/af47021eb7dad6ff3396cb001c08f0f3c4d06c20253f75be6421a59fe6b7/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f", size = 376055, upload-time = "2026-06-30T07:16:26.111Z" }, + { url = "https://files.pythonhosted.org/packages/81/fc/a3bcf517084396a6dd258c592567a3c011ba4557f2fde23dceaf26e74f2e/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41", size = 494419, upload-time = "2026-06-30T07:16:27.596Z" }, + { url = "https://files.pythonhosted.org/packages/c9/eb/13d529d1788135425c7bf207f8463458ca5d92e43f3f701365b83e9dffc1/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945", size = 384848, upload-time = "2026-06-30T07:16:29.183Z" }, + { url = "https://files.pythonhosted.org/packages/8e/f4/b7ac49f30013aba8f7b9566b1dd07e81de95e708c1374b7bacc5b9bc5c9c/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f", size = 371369, upload-time = "2026-06-30T07:16:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/31/86/6260bafa622f788b07ddec0e52d810305c8b9b0b8c27f58a2ab04bf62b4f/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1", size = 379673, upload-time = "2026-06-30T07:16:32.486Z" }, + { url = "https://files.pythonhosted.org/packages/19/c3/03f1ee79a047b48daeca157c89a18509cde22b6b951d642b9b0af1be660a/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e", size = 397500, upload-time = "2026-06-30T07:16:34.471Z" }, + { url = "https://files.pythonhosted.org/packages/f0/95/8ed0cd8c377dca12aea498f119fe639fc474d1461545c39d2b5872eb1c0f/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538", size = 545978, upload-time = "2026-06-30T07:16:36.45Z" }, + { url = "https://files.pythonhosted.org/packages/d3/f2/0eb57f0eaa83f8fc152a7e03de968ab77e1f00732bebc892b190c6eebde7/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db", size = 613350, upload-time = "2026-06-30T07:16:38.213Z" }, + { url = "https://files.pythonhosted.org/packages/5b/de/e0674bdbc3ef7634989b3f854c3f34bc1f587d36e5bfdc5c378d57034619/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2", size = 576486, upload-time = "2026-06-30T07:16:39.797Z" }, + { url = "https://files.pythonhosted.org/packages/f2/f6/21101359743cd136ada781e8210a85769578422ba460672eea0e29739200/rpds_py-2026.6.3-cp314-cp314t-win32.whl", hash = "sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e", size = 201068, upload-time = "2026-06-30T07:16:41.316Z" }, + { url = "https://files.pythonhosted.org/packages/a6/b2/9574d4d44f7760c2aa32d92a0a4f41698e33f5b204a0bf5c9758f52c79d5/rpds_py-2026.6.3-cp314-cp314t-win_amd64.whl", hash = "sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2", size = 220600, upload-time = "2026-06-30T07:16:43.091Z" }, + { url = "https://files.pythonhosted.org/packages/08/ae/f23a2697e6ee6340a578b0f136be6483657bef0c6f9497b752bb5c0964bb/rpds_py-2026.6.3-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:e059c5dde6452b44424bd1834557556c226b57781dee1227af23518459722b13", size = 344726, upload-time = "2026-06-30T07:16:44.5Z" }, + { url = "https://files.pythonhosted.org/packages/c3/63/e7b3a1a5358dd32c930a1062d8e15b67fd6e8922e81df9e91706d66ee5c8/rpds_py-2026.6.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2f7c26fbc5acd2522b95d4177fe4710ffd8e9b20529e703ffbf8db4d93903f05", size = 339587, upload-time = "2026-06-30T07:16:46.255Z" }, + { url = "https://files.pythonhosted.org/packages/ec/64/10a85681916ca55fffb91b0a211f84e34297c109243484dd6394660a8a7c/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a3086b538543802f84c843911242db20447de00d8752dd0efc936dbcf02218ba", size = 369585, upload-time = "2026-06-30T07:16:48.101Z" }, + { url = "https://files.pythonhosted.org/packages/76/c2/baf95c7c38823e12ba34407c5f5767a89e5cf2233895e56f608167ae9493/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8f2e5c5ee828d42cb11760761c0af6507927bec42d0ad5458f97c9203b054617", size = 375479, upload-time = "2026-06-30T07:16:49.93Z" }, + { url = "https://files.pythonhosted.org/packages/6a/94/0aad06c72d65101e11d33528d438cda99a39ce0da99466e156158f2541d3/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ed0c1e5d10cdc7135537988c74a0188da68e2f3c30813ba3744ab1e42e0480f9", size = 492418, upload-time = "2026-06-30T07:16:51.641Z" }, + { url = "https://files.pythonhosted.org/packages/b5/17/de3f5a479a1f056535d7489819639d8cd591ea6281d700390b43b1abd745/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c2642a7603ec0b16ed77da4555db3b4b472341904873788327c0b0d7b95f1bb", size = 384123, upload-time = "2026-06-30T07:16:53.622Z" }, + { url = "https://files.pythonhosted.org/packages/46/7d/bf09bd1b145bb2671c03e1e6d1ab8651858d90d8c7dfeadd85a37a934fd8/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e4320744c1ffdd95a603def63344bfab2d33edeab301c5007e7de9f9f5b3885", size = 367351, upload-time = "2026-06-30T07:16:55.241Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ea/1bb734f314b8be319149ddee80b18bd41372bdcfbdf88d28131c0cd37719/rpds_py-2026.6.3-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:a9f4645593036b81bbdb36b9c8e0ea0d1c3fee968c4d59db0344c14087ef143a", size = 378827, upload-time = "2026-06-30T07:16:56.841Z" }, + { url = "https://files.pythonhosted.org/packages/4b/93/d9611e5b25e26df9a3649813ed66193ace9347a7c7fc4ab7cf70e94851c0/rpds_py-2026.6.3-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e55d236be29255554da47abe5c577637db7c24a02b8b46f0ca9524c855801868", size = 395966, upload-time = "2026-06-30T07:16:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/c3/cb/99d77e16e5534ae1d90629bbe419ba6ee170833a6a85e3aa1cc41726fbbc/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:24e9c5386e16669b674a69c156c8eeefcb578f3b3397b713b08e6d60f3c7b187", size = 545680, upload-time = "2026-06-30T07:17:00.164Z" }, + { url = "https://files.pythonhosted.org/packages/59/15/11a29755f790cef7a2f755e8e14f4f0c33f39489e1893a632a2eee59672b/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c60924535c75f1566b6eb75b5c31a48a43fef04fa2d0d201acbad8a9969c6107", size = 611853, upload-time = "2026-06-30T07:17:01.962Z" }, + { url = "https://files.pythonhosted.org/packages/68/86/0c27547e21644da938fb530f7e1a8148dd24d02db07e7a5f2567a17ce710/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:38a2fea2787428f811719ceb9114cb78964a3138838320c29ac39526c79c16ba", size = 573715, upload-time = "2026-06-30T07:17:03.693Z" }, + { url = "https://files.pythonhosted.org/packages/29/71/4d8fcf700931815594bce892255bbd973b94efaf0fc1932b0590df18d886/rpds_py-2026.6.3-cp315-cp315-win32.whl", hash = "sha256:d483fe17f01ad64b7bf7cc38fcefff1ca9fb83f8c2b2542b68f97ffe0611b369", size = 202864, upload-time = "2026-06-30T07:17:05.746Z" }, + { url = "https://files.pythonhosted.org/packages/eb/62/b577562de0edbb55b2be85ce5fd09c33e386b9b13eee09833af4240fd5c4/rpds_py-2026.6.3-cp315-cp315-win_amd64.whl", hash = "sha256:67e3a721ffc5d8d2210d3671872298c4a84e4b8035cfe42ffd7cde35d772b146", size = 220430, upload-time = "2026-06-30T07:17:07.471Z" }, + { url = "https://files.pythonhosted.org/packages/c8/95/d6d0b2509825141eef60669a5739eec88dbc6a48053d6c92993a5704defe/rpds_py-2026.6.3-cp315-cp315-win_arm64.whl", hash = "sha256:6e84adbcf4bf841aed8116a8264b9f50b4cb3e7bd89b516122e616ac56ca269e", size = 215877, upload-time = "2026-06-30T07:17:09.008Z" }, + { url = "https://files.pythonhosted.org/packages/b7/bf/f3ea278f0afd615c1d0f19cb69043a41526e2bb600c2b536eb192218eb27/rpds_py-2026.6.3-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ae6dd8f10bd17aad820876d24caec9efdafd80a318d16c0a48edb5e136902c6b", size = 346933, upload-time = "2026-06-30T07:17:10.762Z" }, + { url = "https://files.pythonhosted.org/packages/9d/29/9907bdf1c5346763cf10b7f6852aad86652168c259def904cbe0082c5864/rpds_py-2026.6.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bdbd97738551fca3917c1bd7188bec1920bb520104f28e7e1007f9ceb17b7690", size = 340274, upload-time = "2026-06-30T07:17:12.266Z" }, + { url = "https://files.pythonhosted.org/packages/6f/2c/8e03767b5778ef25cebf74a7a91a2c3806f8eced4c92cb7406bbe060756d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b95977e7211527ab0ba576e286d023389fbeeb32a6b7b771665d333c60e5342", size = 370763, upload-time = "2026-06-30T07:17:14.107Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e1/df2a7e1ba2efd796af26194250b8d42c821b46592311595162af9ef0528d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15fde0e6fb0d88a60d221204873743e5d9f0b7d29165e62cd86d0413ad74ba6", size = 376467, upload-time = "2026-06-30T07:17:15.76Z" }, + { url = "https://files.pythonhosted.org/packages/6b/de/8a0814d1946af29cb068fb259aa8622f856df1d0bab58429448726b537f5/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a136d453475ac0fcbda502ef1e6504bd28d6d904700915d278deeab0d00fe140", size = 496689, upload-time = "2026-06-30T07:17:17.308Z" }, + { url = "https://files.pythonhosted.org/packages/df/f3/f19e0c852ba13694f5a79f3b719331051573cb5693feacf8a88ffffc3a71/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f826877d462181e5eb1c26a0026b8d0cab05d99844ecb6d8bf3627a2ca0c0442", size = 385340, upload-time = "2026-06-30T07:17:18.928Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ae/7ec3a9d2d4351f99e37bcb06b6b6f954512646bfdbf9742e1de727865daf/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79486287de1730dbaff3dbd124d0ca4d2ef7f9d29bf2544f1f93c09b5bcbbd12", size = 372179, upload-time = "2026-06-30T07:17:20.539Z" }, + { url = "https://files.pythonhosted.org/packages/d3/ac/9cee911dff2aaa9a5a8354f6610bf2e6a616de9197c5fff4f54f82585f1e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:808345f53cb952433ca2816f1604ff3515608a81784954f38d4452acfe8e61d5", size = 379993, upload-time = "2026-06-30T07:17:22.212Z" }, + { url = "https://files.pythonhosted.org/packages/83/6b/7c2a07ba88d1e9a936612f7a5d067467ed03d971d5a06f7d309dff044a7e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1967debc37f64f2c4dc90a7f563aec558b471966e12adcac4e1c4240496b6ebf", size = 398909, upload-time = "2026-06-30T07:17:23.66Z" }, + { url = "https://files.pythonhosted.org/packages/97/0b/776ffcb66783637b0031f6d58d6fb55913c8b5abf00aeecd46bf933fb477/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:f0840b5b17057f7fd918b76183a4b5a0635f43e14eb2ce60dce1d4ee4707ea00", size = 546584, upload-time = "2026-06-30T07:17:25.264Z" }, + { url = "https://files.pythonhosted.org/packages/55/33/ba3bc04d7092bd553c9b2b195624992d2cc4f3de1f380b7b93cbee67bd79/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:faa679d19a6696fd54259ad321251ad77a13e70e03dd834daa762a44fb6196ef", size = 614357, upload-time = "2026-06-30T07:17:26.888Z" }, + { url = "https://files.pythonhosted.org/packages/8b/71/14edf065f04630b1a8472f7653cad03f6c478bcf95ea0e6aed55451e33ea/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:23a439f31ccbeff1574e24889128821d1f7917470e830cf6544dced1c662262a", size = 576533, upload-time = "2026-06-30T07:17:28.546Z" }, + { url = "https://files.pythonhosted.org/packages/ba/76/65002b08596c389105720a8c0d22298b8dc25a4baf89b2ce431343c8b1de/rpds_py-2026.6.3-cp315-cp315t-win32.whl", hash = "sha256:913ca42ccad3f8cc6e292b587ae8ae49c8c823e5dce51a736252fc7c7cdfa577", size = 201204, upload-time = "2026-06-30T07:17:30.193Z" }, + { url = "https://files.pythonhosted.org/packages/8c/97/d855d6b3c322d1f27e26f5241c42016b56cf01377ea8ed348285f54652f0/rpds_py-2026.6.3-cp315-cp315t-win_amd64.whl", hash = "sha256:ae3d4fe8c0b9213624fdce7279d70e3b148b682ca20719ebd193a23ebfa47324", size = 220719, upload-time = "2026-06-30T07:17:31.788Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4d/94/1e5e4967626faf12fa56999cd6222dff6992ceb086ad7945756baf70c7a7/ruff-0.16.0.tar.gz", hash = "sha256:e460aafd5495ec89efaa6ced2e4a9a581116451e1c88b9d37ef497e0f8e93982", size = 4790557, upload-time = "2026-07-23T19:11:30.981Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4b/81/1c8818fee7ce1a04cd7d1b3172e0a8f8e4f1dc4feb7fc390e16daa8af323/ruff-0.16.0-py3-none-linux_armv6l.whl", hash = "sha256:e5115729eb08c585e5121978ba5d5b60caeae394ce21b9fb5e6cd33a1c6c9b1e", size = 10754633, upload-time = "2026-07-23T19:10:46.415Z" }, + { url = "https://files.pythonhosted.org/packages/23/df/beaf59c09d68db84304d555f188b276a77132a5d5b0b67a5c762aa143628/ruff-0.16.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:3c954b1d580bfa035b41654f7858cc7e71d5fc3ac5b723dd62bd9133830ed522", size = 10969164, upload-time = "2026-07-23T19:10:50.271Z" }, + { url = "https://files.pythonhosted.org/packages/42/ce/741cd197496a1abbf51352710fd15ed995d2a2be87189c1da26a450d6e83/ruff-0.16.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e01c21d10eb1b29f47b7454e1f4056db9a3f0260c646aa88457c610291db9f81", size = 10488846, upload-time = "2026-07-23T19:10:52.639Z" }, + { url = "https://files.pythonhosted.org/packages/52/2a/a2db8e88cade358f5cdcb05674a917751074109315d014eb6352d9a893f7/ruff-0.16.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6e364e5ed22ed8dc05082fd78e35308618260907ac2d3c1d637b2e682415b6c9", size = 10889729, upload-time = "2026-07-23T19:10:54.89Z" }, + { url = "https://files.pythonhosted.org/packages/42/65/62a771694ebd63029dc953e27dbad40e1588bd4860ff9fe881018fddaa49/ruff-0.16.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d327b8fc113a1d4421a04f3839d3752057c8dd1ee320223a6f3f52d04ada462a", size = 10568275, upload-time = "2026-07-23T19:10:56.993Z" }, + { url = "https://files.pythonhosted.org/packages/3f/e2/ced249fe8af5f086c5c58cc21cc3356d50f32f7401c5df87050c999620a7/ruff-0.16.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a9b50c55e263103586b3dcf5f73d479eb8cb5fdb6098fec59a62891dab653717", size = 11385112, upload-time = "2026-07-23T19:10:59.615Z" }, + { url = "https://files.pythonhosted.org/packages/87/0b/05154977a8fd69eeb6c103271f55403bfd8711f5c0f8ed07489d95a504e7/ruff-0.16.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0ff4a79ce3ec0172f3241943835de1c4cb4e2dcd07f0f8c2d02603dbbbee4b17", size = 12207008, upload-time = "2026-07-23T19:11:02.154Z" }, + { url = "https://files.pythonhosted.org/packages/fb/29/98225831a3a1eab0e02f4acc6ca6559a98611dcc68b6965ff4b7234627c1/ruff-0.16.0-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e95c448fca1fb2a18372a9440926c5a6ee789639bb975c72e7ae6d0b04218ab4", size = 11650842, upload-time = "2026-07-23T19:11:04.557Z" }, + { url = "https://files.pythonhosted.org/packages/91/66/6bd3cf90500653d55dc0ffc8507aa8300bd49d0214b2e8cb4d3fef2943ba/ruff-0.16.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f11a8d11010301d0a398a2fdef67691feca7294da6aef55e2150e8fa2cd520b", size = 11400718, upload-time = "2026-07-23T19:11:09.233Z" }, + { url = "https://files.pythonhosted.org/packages/8e/a2/a54eb4eae05d66364050a5d3b8a9c5ef88196531b3cbe7109d873f87f819/ruff-0.16.0-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:48044c678e9cb8698246c99b14aaccfa6601dea7379eb48a6f8f73f7a6d86cd0", size = 11426177, upload-time = "2026-07-23T19:11:11.994Z" }, + { url = "https://files.pythonhosted.org/packages/1a/be/16e3eea4b2a478a496919f5e36f17c4559e54620bd3bbac5d6affa068006/ruff-0.16.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:7aa0959bad8eb8bef50340154fc9b58678dae31fa4293afa38b44b6e552c0213", size = 10856126, upload-time = "2026-07-23T19:11:14.221Z" }, + { url = "https://files.pythonhosted.org/packages/a2/84/252eb8b868a16eec7257c14f504f77537e734b2d69c762e639e588e304a3/ruff-0.16.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:28ea2b7df8ebf7f9da6b7d47b230ab48f387c0a29be3b474c4d0740e197bb9af", size = 10571208, upload-time = "2026-07-23T19:11:16.378Z" }, + { url = "https://files.pythonhosted.org/packages/21/09/817a482f542f7570cbb4554b26e896610c7114f539b1d9e2d2145bf6bef6/ruff-0.16.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:33a3dfac8c35f81498dea9181bccc2f4c4bc8f1521a1dd9406e77643e0f0fb09", size = 11063329, upload-time = "2026-07-23T19:11:19.173Z" }, + { url = "https://files.pythonhosted.org/packages/2e/23/9403c180ca1cb9b1f7335f5c3e5305c09d49ea5b345196682a36028bde4a/ruff-0.16.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a5237a0bda500d30d81b8e07a6973a5cbc772864cbf746ae2f4e8a2e01c9f4ed", size = 11489751, upload-time = "2026-07-23T19:11:21.74Z" }, + { url = "https://files.pythonhosted.org/packages/b2/1d/1b2ef7bcde851c78d7f17f1cca13fd6dc695fc4b3d6197941e72cae5b132/ruff-0.16.0-py3-none-win32.whl", hash = "sha256:7fab76fa065c873f41ff744347c6e77bcc3dfec4bcc754dc26b63d23c0f7f5fb", size = 10785885, upload-time = "2026-07-23T19:11:23.947Z" }, + { url = "https://files.pythonhosted.org/packages/b2/a3/d5e4ef7a56be3f928ffb90b94c25ba7d3cb9c7fe0736aeaaedf361770712/ruff-0.16.0-py3-none-win_amd64.whl", hash = "sha256:429c117f022bf481fabd9d551e7a3952b24c65e6ef44337ea09d90bebef14472", size = 11923141, upload-time = "2026-07-23T19:11:26.409Z" }, + { url = "https://files.pythonhosted.org/packages/cb/9a/8415f2657cbe200f41a4531ccededf135505a92d4a012229121f885b26f9/ruff-0.16.0-py3-none-win_arm64.whl", hash = "sha256:14296fedcd2705c77ab8235439278bbb38f285cf7da5528b00b3e330c3d4872d", size = 11273407, upload-time = "2026-07-23T19:11:28.705Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[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 = "stack-data" +version = "0.6.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asttokens" }, + { name = "executing" }, + { name = "pure-eval" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" }, +] + +[[package]] +name = "starlette" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/e3/7c1dc7381d9f8ab7d854328ebfa884e62cb3f3d8549ddfd37c7814f42afa/starlette-1.3.1.tar.gz", hash = "sha256:05d0213193f2fbaae60e2ecb593b4add4262ad4e46536b54abe36f11a71724e0", size = 2703240, upload-time = "2026-06-12T09:23:11.602Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" }, +] + +[[package]] +name = "tornado" +version = "6.5.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/10/d3/343e5bb989d6515b1646cf3d40135d73f3d5e45339bded401b56cdac24dd/tornado-6.5.8.tar.gz", hash = "sha256:9452e1b208a8bd771e2cb1f2ff564985b9b214bdebbe622793e1799e0a6bd23f", size = 520493, upload-time = "2026-08-07T02:12:42.971Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f2/d5/007086fd8df5489338e204f65adce33fd4f21a4999dbb2b9cff2f897b5f4/tornado-6.5.8-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:cc6aa787d7cfab7c3d35189dc7a56fbd2399a569624c730c6b55b3d6531d0403", size = 449487, upload-time = "2026-08-07T02:12:28.682Z" }, + { url = "https://files.pythonhosted.org/packages/70/c8/5a24a99495903f594f6a199dd7beead1cbc0a13e2cb9102727bcaaf2a997/tornado-6.5.8-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9715b5eb79735b2bcd454ce216a9275b7c0470e64ea1bf5742f78b2f72b26eeb", size = 447649, upload-time = "2026-08-07T02:12:30.306Z" }, + { url = "https://files.pythonhosted.org/packages/6e/de/f2e733f386b85962d1b1dc82cd63d169b5b4580062b35397eac9244a41fe/tornado-6.5.8-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:547d63f450d570c14fe0e8db2cfb14c9bbd1c2503b4a6612586267955aa47b58", size = 450707, upload-time = "2026-08-07T02:12:31.95Z" }, + { url = "https://files.pythonhosted.org/packages/0b/94/20efeee9a01c141e9ac47c397f81679dfda24b32768fc4fff24e76d36c2c/tornado-6.5.8-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7e2360a0ffbe145eca8af0b19cb7203d79b1a98dd4cccdd6b368f6f49c2e3808", size = 451677, upload-time = "2026-08-07T02:12:33.512Z" }, + { url = "https://files.pythonhosted.org/packages/42/ec/a96ccb8ccf0de2b7bc2c5fa1608a4803735018242e90c4882365a9fd418f/tornado-6.5.8-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:5d242290bdf7ab3151bc1065fdd75c0dcc21cbc7b49f22a4c56329c2d6566d22", size = 451510, upload-time = "2026-08-07T02:12:35.346Z" }, + { url = "https://files.pythonhosted.org/packages/29/b5/93185859245ad3f00e62175f29607346788b696369347f0146e0421286bb/tornado-6.5.8-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7b94ff0e128fe0542f3bd331fb44d06260fc4ac16881545159f34ef08aad4195", size = 450917, upload-time = "2026-08-07T02:12:36.963Z" }, + { url = "https://files.pythonhosted.org/packages/97/cf/fe33cf062834487d34d1559746a4a12521033c22645b6d74d4bca702e018/tornado-6.5.8-cp39-abi3-win32.whl", hash = "sha256:67832909c4779c64942380cb5f044a5c6163d00831472d80e25e115de9917836", size = 451952, upload-time = "2026-08-07T02:12:38.512Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e1/468ad54333e92ccb62627e62cb88e5fc14a2171daa67ed47b1b8542d5b86/tornado-6.5.8-cp39-abi3-win_amd64.whl", hash = "sha256:11881db6b7c168494be2c2d12e65931451bdf7ee718535418ae1d8855dd5a0ee", size = 452391, upload-time = "2026-08-07T02:12:39.971Z" }, + { url = "https://files.pythonhosted.org/packages/ad/3e/cd5e4f06e34cde33b8ef66cf36aa2b5ad46354cc1af7d2136bbe365fee1d/tornado-6.5.8-cp39-abi3-win_arm64.whl", hash = "sha256:68a7468c7e289f8514d7d664101753903217eff1bb6822c6b5994a0b5f5bcb26", size = 451411, upload-time = "2026-08-07T02:12:41.469Z" }, +] + +[[package]] +name = "traitlets" +version = "5.16.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/2e/a7fbfe268c8a3b32546930c0297c101d65a4a14c304ad5790a9f478f0e4e/traitlets-5.16.1.tar.gz", hash = "sha256:ed900c2b631aa3a112811139fa97b8d2c3bad5e989656bba4b7e52c7852c18c1", size = 166137, upload-time = "2026-08-03T08:32:36.848Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" }, +] + +[[package]] +name = "truststore" +version = "0.10.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/a3/1585216310e344e8102c22482f6060c7a6ea0322b63e026372e6dcefcfd6/truststore-0.10.4.tar.gz", hash = "sha256:9d91bd436463ad5e4ee4aba766628dd6cd7010cf3e2461756b3303710eebc301", size = 26169, upload-time = "2025-08-12T18:49:02.73Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/97/56608b2249fe206a67cd573bc93cd9896e1efb9e98bce9c163bcdc704b88/truststore-0.10.4-py3-none-any.whl", hash = "sha256:adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981", size = 18660, upload-time = "2025-08-12T18:49:01.46Z" }, +] + +[[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 = "urllib3" +version = "2.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.51.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/65/b7c6c443ccc58678c91e1e973bbe2a878591538655d6e1d47f24ba1c51f3/uvicorn-0.51.0.tar.gz", hash = "sha256:f6f4b69b657c312f516dd2d268ab9ae6f254b11e4bac504f37b2ab58b24dd0b0", size = 94412, upload-time = "2026-07-08T10:59:05.962Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/45/ec/dbb7e5a6b91f86bfb9eb7d2988a2730907b6a729875b949c7f022e8b88fa/uvicorn-0.51.0-py3-none-any.whl", hash = "sha256:5d38af6cd620f2ae3849fb44fd4879e0890aa1febe8d47eb355fb45d93fe6a5b", size = 73219, upload-time = "2026-07-08T10:59:04.44Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +] + +[[package]] +name = "wcwidth" +version = "0.8.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/34/74/c6428f875774288bec1396f5bfcbc2d925700a4dad61727fd5f2b12f249d/wcwidth-0.8.2.tar.gz", hash = "sha256:91fbef97204b96a3d4d421609b80340b760cf33e26da123ff243d76b1fda8dda", size = 1466253, upload-time = "2026-06-29T18:11:11.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/96/42/3e5985a0a7e57de470b320c6d6a1a67c844f6737a587f3d44dd13d1819e7/wcwidth-0.8.2-py3-none-any.whl", hash = "sha256:d63947694a0539a1d51e01eda7caf800c291020e6cdd7e28ad7b14dd33ad4f85", size = 323166, upload-time = "2026-06-29T18:11:09.888Z" }, +] + +[[package]] +name = "yarl" +version = "1.24.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/31/33/ebe9e3d1f86c7a0b51094c0a146392045ca1631d2664889539dec8088a33/yarl-1.24.5.tar.gz", hash = "sha256:e81b83143bee16329c23db3c1b2d82b29892fcbcb849186d2f6e98a5abe9a57f", size = 228679, upload-time = "2026-07-20T02:07:45.435Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1b/84/71d051c850b5af41d168c679d9eb67eb7c55283ac4ee131673edf134bc4e/yarl-1.24.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d693396e5aea78db03decd60aec9ece16c9b40ba00a587f089615ff4e718a81d", size = 136035, upload-time = "2026-07-20T02:05:25.489Z" }, + { url = "https://files.pythonhosted.org/packages/03/4d/8ad27f9a1b7e69313cca5d695b925b48efe51208d3490e0844bae97cabc0/yarl-1.24.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3363fcc96e665878946ad7a106b9a13eac0541766a690ef287c0232ac768b6ec", size = 97642, upload-time = "2026-07-20T02:05:27.429Z" }, + { url = "https://files.pythonhosted.org/packages/ea/b4/05b4131c407006cd1e410e9c6539f16a0945724677e5364447313c15ea3e/yarl-1.24.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9d399bdcfb4a0f659b9b3788bbc89babe63d9a6a65aacdf4d4e7065ff2e6316c", size = 97323, upload-time = "2026-07-20T02:05:29.441Z" }, + { url = "https://files.pythonhosted.org/packages/20/16/e618c875c73e0e39611f20a581b3d5e8d59b8857bf001bee3263044c6deb/yarl-1.24.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90333fd89b43c0d08ac85f3f1447593fc2c66de18c3d6378d7125ea118dc7a54", size = 107741, upload-time = "2026-07-20T02:05:31.367Z" }, + { url = "https://files.pythonhosted.org/packages/d9/9a/c4defeaf3ed33fcb346aacf9c6e971a8d4e2bde04a0310e79abb208e7965/yarl-1.24.5-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:665b0a2c463cc9423dd647e0bfd9f4ccc9b50f768c55304d5e9f80b177c1de12", size = 103570, upload-time = "2026-07-20T02:05:33.303Z" }, + { url = "https://files.pythonhosted.org/packages/5f/e7/0e0e0de5865ebd5914537ef486f36c727a59865c3ac0cf5ff1b32aececbf/yarl-1.24.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e006d3a974c4ee19512e5f058abedb6eef36a5e553c14812bdeba1758d812e6d", size = 115815, upload-time = "2026-07-20T02:05:35.292Z" }, + { url = "https://files.pythonhosted.org/packages/2b/27/ca56b700cb170aba25a3893b75355b213935657dc5714d2383354a270e62/yarl-1.24.5-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e7d42c531243450ef0d4d9c172e7ed6ef052640f195629065041b5add4e058d1", size = 116025, upload-time = "2026-07-20T02:05:37.503Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d0/d56c859b8222116f5d68459199f48359e0bf121b6f65a69bf329b3602ba0/yarl-1.24.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f08c7513ecef5aad65687bfdf6bc601ae9fccd04a42904501f8f7141abad9eb9", size = 109835, upload-time = "2026-07-20T02:05:39.506Z" }, + { url = "https://files.pythonhosted.org/packages/70/a2/3a35557e4d1a79425040eba202ccaf08bdc8717680fc77e2498a1ad2e0a5/yarl-1.24.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6c95b17fe34ed802f17e205112e6e10db92275c34fee290aa9bdc55a9c724027", size = 108884, upload-time = "2026-07-20T02:05:41.584Z" }, + { url = "https://files.pythonhosted.org/packages/e4/35/ef4c26356b7913c68983bac2d72a4212b3347af551cb8d250b99b5ed7b7f/yarl-1.24.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:56b149b22de33b23b0c6077ab9518c6dcb538ad462e1830e68d06591ccf6e38b", size = 107308, upload-time = "2026-07-20T02:05:43.697Z" }, + { url = "https://files.pythonhosted.org/packages/d5/91/ff0dc66c2ccf3e0153ab97ff61eabab4400e6a5264af427ab30cd69f1857/yarl-1.24.5-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a8fe66b8f300da93798025a785a5b90b42f3810dc2b72283ff84a41aaaebc293", size = 103646, upload-time = "2026-07-20T02:05:45.895Z" }, + { url = "https://files.pythonhosted.org/packages/74/f0/33b9271c7f881766359d58266fa0811d2e5210ed860e28da7dc6d7786344/yarl-1.24.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:377fe3732edbaf78ee74efdf2c9f49f6e99f20e7f9d2649fda3eb4badd77d76e", size = 115305, upload-time = "2026-07-20T02:05:47.832Z" }, + { url = "https://files.pythonhosted.org/packages/ef/65/fd79fb1868c4a80db8661091de525bf430f63c3bea1b20e8b6a84fc7d359/yarl-1.24.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e8ffa78582120024f476a611d7befc123cee59e47e8309d470cf667d806e613b", size = 108404, upload-time = "2026-07-20T02:05:49.604Z" }, + { url = "https://files.pythonhosted.org/packages/ff/ba/dbabe6b262f17a816c70cfc09558dbf03ece3ec76684d02f911a3d3a189c/yarl-1.24.5-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:daba5e594f06114e37db186efd2dd916609071e59daca901a0a2e71f02b142ce", size = 115940, upload-time = "2026-07-20T02:05:51.741Z" }, + { url = "https://files.pythonhosted.org/packages/a5/43/fab2d1dad9d340a268cdde63756a123d069723efff6a372d123fa74a9517/yarl-1.24.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:65be18ec59496c13908f02a2472751d9ef840b4f3fb5726f129306bf6a2a7bba", size = 110006, upload-time = "2026-07-20T02:05:53.554Z" }, + { url = "https://files.pythonhosted.org/packages/c4/27/41eb51bbd1b8d89546b83897cfb0164f1e109304fd408dbb151b639eec0f/yarl-1.24.5-cp312-cp312-win_amd64.whl", hash = "sha256:a929d878fec099030c292803b31e5d5540a7b6a31e6a3cc76cb4685fc2a2f51b", size = 97618, upload-time = "2026-07-20T02:05:55.57Z" }, + { url = "https://files.pythonhosted.org/packages/3c/25/b2553764b3d65db711d8f45416351ec4f420847558eb669edcbcaadf5780/yarl-1.24.5-cp312-cp312-win_arm64.whl", hash = "sha256:7ce27823052e2013b597e0c738b13e7e36b8ccb9400df8959417b052ab0fd92c", size = 93018, upload-time = "2026-07-20T02:05:57.554Z" }, + { url = "https://files.pythonhosted.org/packages/e1/63/64ef361967cc983573149dc1515d531db5da8a4c92d22bb833d59e01b313/yarl-1.24.5-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:79af890482fc94648e8cde4c68620378f7fef60932710fa17a66abc039244da2", size = 135075, upload-time = "2026-07-20T02:05:59.671Z" }, + { url = "https://files.pythonhosted.org/packages/bb/89/55920fd853ce43e608adbc3962456f0d649d6bb15250dc2988321da0fe1c/yarl-1.24.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:46c2f213e23a04b93a392942d782eb9e413e6ef6bf7c8c53884e599a5c174dcb", size = 97225, upload-time = "2026-07-20T02:06:01.769Z" }, + { url = "https://files.pythonhosted.org/packages/15/f0/7688d3f2cfff7590df2af38ec46d969f4281a4dddb08a9ad2eafbcdddf98/yarl-1.24.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:92ab3e11448f2ff7bf53c5a26eff0edc086898ec8b21fb154b85839ce1d88075", size = 96751, upload-time = "2026-07-20T02:06:03.676Z" }, + { url = "https://files.pythonhosted.org/packages/05/1a/a851a0f94aaaf379dd4f901bfc80f634280bec51eb260b47363e2a4cd62e/yarl-1.24.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ebb0ec7f17803063d5aeb982f3b1bd2b2f4e4fae6751226cbd6ba1fcfe9e63ff", size = 107960, upload-time = "2026-07-20T02:06:05.699Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a8/faea066c12f9c77ca0de90641f1655f9dd7b412477bf28c76d692f3aecff/yarl-1.24.5-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:82632daed195dcc8ea664e8556dc9bdbd671960fb3776bd92806ce05792c2448", size = 103500, upload-time = "2026-07-20T02:06:07.556Z" }, + { url = "https://files.pythonhosted.org/packages/fb/9c/1e67084c2a6e2f2db0e3be798328cb3be42c0119b621d25461479a224d21/yarl-1.24.5-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:53e549287ef628fecba270045c9701b0c564563a9b0577d24a4ec75b8ab8040f", size = 115780, upload-time = "2026-07-20T02:06:09.599Z" }, + { url = "https://files.pythonhosted.org/packages/58/86/1f94664e147474337e3359f52012cf3d02f825f694317b178bfba1078c62/yarl-1.24.5-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fcd3b77e2f17bbe4ca56ec7bcb07992647d19d0b9c05d84886dcd6f9eb810afd", size = 115308, upload-time = "2026-07-20T02:06:11.352Z" }, + { url = "https://files.pythonhosted.org/packages/0a/43/8e55ae7538ba5f28ccb3c845c6dd4549cf7016d5992e5326512519107cdd/yarl-1.24.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d46b86567dd4e248c6c159fcbcdcce01e0a5c8a7cd2334a0fff759d0fa075b16", size = 110574, upload-time = "2026-07-20T02:06:13.129Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ba/a889ec8765cedcf2ac44dcb02d6a21e4861399b243b263c5f2dde27ee740/yarl-1.24.5-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7f72c74aa99359e27a2ee8d6613fefa28b5f76a983c083074dfc2aaa4ab46213", size = 109914, upload-time = "2026-07-20T02:06:15.243Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c3/e45f821af67b791c2dbbe4a9f4137a1d33f8d386654a05a0c3f47bdfa25d/yarl-1.24.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f45789ce415a7ec0820dc4f82925f9b5f7732070be1dec1f5f23ec381435a24", size = 107712, upload-time = "2026-07-20T02:06:17.443Z" }, + { url = "https://files.pythonhosted.org/packages/02/00/2ab0f42c9857fcb490bfaa6647b14540b53d241ab209f23220b958cc5832/yarl-1.24.5-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:6e73e7fe93f17a7b191f52ec9da9dd8c06a8fe735a1ecbd13b97d1c723bff385", size = 104251, upload-time = "2026-07-20T02:06:19.259Z" }, + { url = "https://files.pythonhosted.org/packages/7a/70/709d9a286e98af2c7fd8e4e6cada658b5c0e30d87dd7e2a63c2fb5767217/yarl-1.24.5-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4a36f9becdd4c5c52a20c3e9484128b070b1dcfc8944c006f3a528295a359a9c", size = 115319, upload-time = "2026-07-20T02:06:21.207Z" }, + { url = "https://files.pythonhosted.org/packages/5c/6c/3eaa515142991fe84cfc483ff986492211f1978f90161ccefdbec919d09b/yarl-1.24.5-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:7bcbe0fcf850eae67b6b01749815a4f7161c560a844c769ad7b48fcd99f791c4", size = 109163, upload-time = "2026-07-20T02:06:23.006Z" }, + { url = "https://files.pythonhosted.org/packages/bb/64/711dafce66c323a3144d470547a71c5384c57623308ac8bb5e4b903ac148/yarl-1.24.5-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:24e861e9630e0daddcb9191fb187f60f034e17a4426f8101279f0c475cd74144", size = 115435, upload-time = "2026-07-20T02:06:24.923Z" }, + { url = "https://files.pythonhosted.org/packages/cf/f3/9b9d0e6d84bea851eb1ba99e4bdc755b86fd813e49ec86dfe42f26befdef/yarl-1.24.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9335a099ad87287c37fe5d1a982ff392fa5efe5d14b40a730b1ec1d6a41382b4", size = 110691, upload-time = "2026-07-20T02:06:26.973Z" }, + { url = "https://files.pythonhosted.org/packages/86/e4/62a06b7e87c4246ac76b7c2da136f972eb4a3a1fc94abb07e7022d6fdb0a/yarl-1.24.5-cp313-cp313-win_amd64.whl", hash = "sha256:2dbe06fc16bc91502bca713704022182e5729861ae00277c3a23354b40929740", size = 97454, upload-time = "2026-07-20T02:06:29.163Z" }, + { url = "https://files.pythonhosted.org/packages/9e/c9/5fc8025b318ab10db413b61056bd0d95c557a70e8df4210c7511f866329c/yarl-1.24.5-cp313-cp313-win_arm64.whl", hash = "sha256:6b8536851f9f65e7f00c7a1d49ba7f2be0ffe2c11555367fc9f50d9f842410a1", size = 92813, upload-time = "2026-07-20T02:06:31.113Z" }, + { url = "https://files.pythonhosted.org/packages/a9/08/5f3085fef9564217074db9dd8573de1795bc82cde61a7ad10b6a7234a569/yarl-1.24.5-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:2729fcfc4f6a596fb0c50f32090400aa9367774ac296a00387e65098c0befa76", size = 135680, upload-time = "2026-07-20T02:06:33.273Z" }, + { url = "https://files.pythonhosted.org/packages/98/35/ba9436e579bd48a8801f2021d842d9ab4994c26e4c7dd3a4c1f1bcb57a9e/yarl-1.24.5-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ff330d3c30db4eb6b01d79e29d2d0b407a7ecad39cfd9ec993ece57396a2ec0d", size = 97395, upload-time = "2026-07-20T02:06:35.259Z" }, + { url = "https://files.pythonhosted.org/packages/18/a9/a07f76f3c44e02b25cc743af5ef93eef27f7013eadca770451b6a6ccb5db/yarl-1.24.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e42d75862735da90e7fc5a7b23db0c976f737113a54b3c9777a9b665e9cbff75", size = 97223, upload-time = "2026-07-20T02:06:37.216Z" }, + { url = "https://files.pythonhosted.org/packages/77/f7/a9a1d6fa7dd9e388f95b30f6ad3ec4e285f6c8f61f44ce16070c3fcfe414/yarl-1.24.5-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a3732e66413163e72508da9eff9ce9d2846fde51fae45d3605393d3e6cd303e9", size = 108777, upload-time = "2026-07-20T02:06:39.292Z" }, + { url = "https://files.pythonhosted.org/packages/2f/44/e0b86c302471fabd6f02808ecf2ac52b8412b624787849d4bf2cdb466f6f/yarl-1.24.5-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5b8ee53be440a0cffc991a27be3057e0530122548dbe7c0892df08822fce5ede", size = 103119, upload-time = "2026-07-20T02:06:41.456Z" }, + { url = "https://files.pythonhosted.org/packages/d1/16/9c16d180bf8faaf223225eb50e1245870ff1ae0e302a27153988e65c51fd/yarl-1.24.5-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:af3aefa655adb5869491fa907e652290386800ae99cc50095cba71e2c6aefdca", size = 116471, upload-time = "2026-07-20T02:06:43.696Z" }, + { url = "https://files.pythonhosted.org/packages/d2/8d/b219b9df28a02ce95cfbdd41d2f7caa5669d0ff979c1c9975697145e33c5/yarl-1.24.5-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2120b96872df4a117cde97d270bac96aea7cc52205d305cf4611df694a487027", size = 115974, upload-time = "2026-07-20T02:06:45.874Z" }, + { url = "https://files.pythonhosted.org/packages/9b/e8/f20557aca240d88e69850ad1ee91756821d094bb1310565c04d25c6682a2/yarl-1.24.5-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:66410eb6345d467151934b49bfa70fb32f5b35a6140baa40ad97d6436abea2e9", size = 110830, upload-time = "2026-07-20T02:06:47.852Z" }, + { url = "https://files.pythonhosted.org/packages/db/18/199b85109a53eeca64ee19c9cca228287e8e4ab0cc1a09b28f530e65cce0/yarl-1.24.5-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4af7b7e1be0a69bee8210735fe6dcfc38879adfac6d62e789d53ba432d1ffa41", size = 110054, upload-time = "2026-07-20T02:06:49.84Z" }, + { url = "https://files.pythonhosted.org/packages/aa/2f/ed28147f8cd7f48c49367c90713b30a555284b6105a6a56f3a05568da795/yarl-1.24.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa139875ff98ab97da323cfadfaff08900d1ad42f1b5087b0b812a55c5a06373", size = 108312, upload-time = "2026-07-20T02:06:51.835Z" }, + { url = "https://files.pythonhosted.org/packages/c5/c5/55e16ae0a5c227cea8df1c6871ba57d614a34243146c05729caf2a1bd9c5/yarl-1.24.5-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:0055afc45e864b92729ac7600e2d102c17bef060647e74bca75fa84d66b9ff36", size = 103662, upload-time = "2026-07-20T02:06:54.061Z" }, + { url = "https://files.pythonhosted.org/packages/8d/ea/dbd7c2caec459c9a426f18b02688ecbfb58620d0f6a3422d24769fbaf8ab/yarl-1.24.5-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f0e466ed7511fe9d459a819edbc6c2585c0b6eabde9fa8a8947552468a7a6ef0", size = 116090, upload-time = "2026-07-20T02:06:56.015Z" }, + { url = "https://files.pythonhosted.org/packages/06/84/39ce4ce3059e07fece5fbdbee8c4053406af9aca911ce9fa5f8548aab6af/yarl-1.24.5-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:f141474e85b7e54998ec5180530a7cda99ab29e282fa50e0756d89981a9b43c5", size = 109523, upload-time = "2026-07-20T02:06:57.926Z" }, + { url = "https://files.pythonhosted.org/packages/a9/8b/71ff44137b405c64a7788075669c24010019f57a7464b78c3a6cbee539d9/yarl-1.24.5-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:e2935f8c39e3b03e83519292d78f075189978f3f4adc15a78144c7c8e2a1cba5", size = 116084, upload-time = "2026-07-20T02:06:59.868Z" }, + { url = "https://files.pythonhosted.org/packages/62/c0/423078fdd4042e1862c11f0ffd977a0ffa393783c12bee94685923bc189e/yarl-1.24.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9d1216a7f6f77836617dba35687c5b78a4170afc3c3f18fc788f785ba26565c4", size = 111006, upload-time = "2026-07-20T02:07:01.907Z" }, + { url = "https://files.pythonhosted.org/packages/cf/52/6daa2ee9d95e5c98b8128f8df91eb692eb423ab274b8cf08db52152fad26/yarl-1.24.5-cp314-cp314-win_amd64.whl", hash = "sha256:5ba4f78df2bcc19f764a4b26a8a4f5049c110090ad5825993aacb052bf8003ad", size = 99215, upload-time = "2026-07-20T02:07:03.852Z" }, + { url = "https://files.pythonhosted.org/packages/ec/0e/464a847d7359e0da75dd9fc5c1d1aa35d0159ea31e5f8e66a3c1c29ff3d0/yarl-1.24.5-cp314-cp314-win_arm64.whl", hash = "sha256:9e4e16c73d717c5cf27626c524d0a2e261ad20e46932b2670f64ad5dde23e26f", size = 94566, upload-time = "2026-07-20T02:07:06.074Z" }, + { url = "https://files.pythonhosted.org/packages/e2/55/e03acc4446772660bc335e86e41ef31e4d0d838fd641531a11a5ee33b493/yarl-1.24.5-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:e1ae548a9d901adca07899a4147a7c826bbcc06239d3ce9a59f57886a28a4c88", size = 142533, upload-time = "2026-07-20T02:07:08.284Z" }, + { url = "https://files.pythonhosted.org/packages/ae/71/4acd3a1fc7cf14345cdb302665ecd2097f62c365b4f14ca17d4f37775cf9/yarl-1.24.5-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ff405d91509d88e8d44129cd87b18d70acd1f0c1aeabd7bc3c46792b1fe2acba", size = 100776, upload-time = "2026-07-20T02:07:10.197Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0b/cfb76b7fe99686db264bff829779a539d923e7564ffd7ef18da6c54c3774/yarl-1.24.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:47e98aab9d8d82ff682e7b0b5dded33bf138a32b817fcf7fa3b27b2d7c412928", size = 100913, upload-time = "2026-07-20T02:07:12.357Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3f/7116e782992abbd4fb6948488aec72078895e929a23078290739e8396fce/yarl-1.24.5-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0a658a6d3fafee5c6f63c58f3e785c8c43c93fbc02bf9f2b6663f8185e0971f", size = 106507, upload-time = "2026-07-20T02:07:14.173Z" }, + { url = "https://files.pythonhosted.org/packages/33/90/d4d2d73ee78229cc889872eb8e085d8f5c6f51abdb178409fd9b23cf74fd/yarl-1.24.5-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4377407001ca3c057773f44d8ddd6358fa5f691407c1ba92210bd3cf8d9e4c95", size = 99219, upload-time = "2026-07-20T02:07:16.019Z" }, + { url = "https://files.pythonhosted.org/packages/3e/fa/a6df1a9bccd644eec00abee0dff4277416222cec435330fd1f2858523ec1/yarl-1.24.5-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7c0494a31a1ac5461a226e7947a9c9b78c44e1dc7185164fa7e9651557a5d9bc", size = 111804, upload-time = "2026-07-20T02:07:18.141Z" }, + { url = "https://files.pythonhosted.org/packages/8a/9e/7b2a1f4bcc20e9447156dd2b1c4d01f70d9df0759025ee7d09a84ffae134/yarl-1.24.5-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a7cff474ab7cd149765bb784cf6d78b32e18e20473fb7bda860bce98ab58e9da", size = 110943, upload-time = "2026-07-20T02:07:20.06Z" }, + { url = "https://files.pythonhosted.org/packages/08/ff/22c92affb0f9b623ca753d27d968b5625b868f12c6378d049d55ae247643/yarl-1.24.5-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cbb833ccacdb5519eff9b8b71ee618cc2801c878e77e288775d77c3a2ced858a", size = 108251, upload-time = "2026-07-20T02:07:22.217Z" }, + { url = "https://files.pythonhosted.org/packages/45/44/5769b96298c1e195fb412997b6090af2a84105cf59c17613558a2d011d1f/yarl-1.24.5-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:82f75e05912e84b7a0fe57075d9c59de3cb352b928330f2eb69b2e1f54c3e1f0", size = 106025, upload-time = "2026-07-20T02:07:24.083Z" }, + { url = "https://files.pythonhosted.org/packages/4c/40/009e8e791fd9762c0e1567e69248acb4f49064597e1680874c16dd8bb798/yarl-1.24.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:16a2f5010280020e90f5330257e6944bc33e73593b136cc5a241e6c1dc292498", size = 106573, upload-time = "2026-07-20T02:07:26.248Z" }, + { url = "https://files.pythonhosted.org/packages/20/c6/b7480578f8a0a80946f36ad6df547ecec704f9ba69d2de60f8aa6f1c1cbf/yarl-1.24.5-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:ffcd54362564dc1a30fb74d8b8a6e5a6b11ebd5e27266adc3b7427a21a6c9104", size = 100751, upload-time = "2026-07-20T02:07:28.098Z" }, + { url = "https://files.pythonhosted.org/packages/d4/27/4476f3360b91a48c5cf125e91f59a3bd35299d84a431a258d57f5977bb11/yarl-1.24.5-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:0465ec8cedc2349b97a6b595ace64084a50c6e839eca40aa0626f38b8350e331", size = 111643, upload-time = "2026-07-20T02:07:30.88Z" }, + { url = "https://files.pythonhosted.org/packages/4c/4b/5cdd3e5ee944e8af31e52f6cd3d3af5fd7b937e036ccbbba2c9ffebede95/yarl-1.24.5-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:4db9aecb141cb7a5447171b57aa1ed3a8fee06af40b992ffc31206c0b0121550", size = 106312, upload-time = "2026-07-20T02:07:33.06Z" }, + { url = "https://files.pythonhosted.org/packages/18/86/f406b0c2a6f99575de2da671ef47aa06f89a5be83a27a46971c3b86cecdb/yarl-1.24.5-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:f540c013589084679a6c7fac07096b10159737918174f5dfc5e11bf5bca4dfe6", size = 110379, upload-time = "2026-07-20T02:07:35.155Z" }, + { url = "https://files.pythonhosted.org/packages/f0/6c/9f3adfbd3b30b4fa0f7ccb3a83eba2c1152d3fff554d535e640ba0f7ba2b/yarl-1.24.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a61834fb15d81322d872eaafd333838ae7c9cea84067f232656f75965933d047", size = 108497, upload-time = "2026-07-20T02:07:37.35Z" }, + { url = "https://files.pythonhosted.org/packages/dd/37/91eb2e5ca883a529c1b390348a74cd9fc0512171727f547ce70bfe02be5c/yarl-1.24.5-cp314-cp314t-win_amd64.whl", hash = "sha256:5c88e5815a49d289e599f3513aa7fde0bc2092ff188f99c940f007f90f53d104", size = 102450, upload-time = "2026-07-20T02:07:39.578Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f4/ed5c402ac8fde4403ed3366c2716bfddc8a6677ebd59f3d62772cc7fe468/yarl-1.24.5-cp314-cp314t-win_arm64.whl", hash = "sha256:cf139c02f5f23ef6532040a30ff662c00a318c952334f211046b8e60b7f17688", size = 97222, upload-time = "2026-07-20T02:07:41.55Z" }, + { url = "https://files.pythonhosted.org/packages/61/02/962c1cbfc401a30c1d034dc67ff395f64b52302c6d62de556c1fca99acc0/yarl-1.24.5-py3-none-any.whl", hash = "sha256:a33700d13d9b7d84fd10947b09ff69fb9a792e519c8cb9764a3ca70baa6c23a7", size = 58612, upload-time = "2026-07-20T02:07:43.461Z" }, +] + +[[package]] +name = "zarr" +source = { editable = "../../" } +dependencies = [ + { name = "donfig" }, + { name = "google-crc32c" }, + { name = "numcodecs" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "typing-extensions" }, +] + +[package.metadata] +requires-dist = [ + { name = "cast-value-rs", marker = "extra == 'cast-value-rs'" }, + { name = "cupy-cuda12x", marker = "sys_platform != 'darwin' and extra == 'gpu'" }, + { name = "donfig", specifier = ">=0.8" }, + { name = "fsspec", marker = "extra == 'remote'", specifier = ">=2023.10.0" }, + { name = "google-crc32c", specifier = ">=1.5" }, + { name = "numcodecs", specifier = ">=0.14" }, + { name = "numpy", specifier = ">=2" }, + { name = "obstore", marker = "extra == 'remote'", specifier = ">=0.5.1" }, + { name = "packaging", specifier = ">=22.0" }, + { name = "typer", marker = "extra == 'cli'" }, + { name = "typing-extensions", specifier = ">=4.14" }, + { name = "universal-pathlib", marker = "extra == 'optional'" }, +] +provides-extras = ["cast-value-rs", "cli", "gpu", "optional", "remote"] + +[package.metadata.requires-dev] +dev = [ + { name = "astroid", specifier = "==4.1.2" }, + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.2" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "hypothesis", specifier = "==6.164.0" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "mypy", specifier = "==2.3.0" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "ruff", specifier = "==0.16.0" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "towncrier", specifier = "==25.8.0" }, + { name = "universal-pathlib" }, + { name = "uv", specifier = "==0.12.0" }, +] +docs = [ + { name = "astroid", specifier = "==4.1.2" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "ruff", specifier = "==0.16.0" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "towncrier", specifier = "==25.8.0" }, +] +release = [{ name = "towncrier", specifier = "==25.8.0" }] +remote-tests = [ + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.2" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "hypothesis", specifier = "==6.164.0" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.0" }, +] +test = [ + { name = "coverage", specifier = "==7.15.2" }, + { name = "hypothesis", specifier = "==6.164.0" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.0" }, +] + +[[package]] +name = "zarr-http-server" +source = { editable = "." } +dependencies = [ + { name = "starlette" }, + { name = "uvicorn" }, + { name = "zarr" }, +] + +[package.dev-dependencies] +docs = [ + { name = "griffe-inherited-docstrings" }, + { name = "mkdocs" }, + { name = "mkdocs-material" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "ruff" }, +] +examples = [ + { name = "fsspec", extra = ["http"] }, + { name = "httpx" }, +] +test = [ + { name = "httpx" }, + { name = "httpx2" }, + { name = "hypothesis" }, + { name = "ipykernel" }, + { name = "nbclient" }, + { name = "nbformat" }, + { name = "pytest" }, +] + +[package.metadata] +requires-dist = [ + { name = "starlette", specifier = ">=1.0" }, + { name = "uvicorn", specifier = ">=0.29" }, + { name = "zarr", editable = "../../" }, +] + +[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.5" }, + { name = "ruff", specifier = "==0.16.0" }, +] +examples = [ + { name = "fsspec", extras = ["http"] }, + { name = "httpx" }, +] +test = [ + { name = "httpx" }, + { name = "httpx2" }, + { name = "hypothesis" }, + { name = "ipykernel" }, + { name = "nbclient" }, + { name = "nbformat" }, + { name = "pytest" }, +] diff --git a/packages/zarr-indexing/.readthedocs.yaml b/packages/zarr-indexing/.readthedocs.yaml new file mode 100644 index 0000000000..c1925182f7 --- /dev/null +++ b/packages/zarr-indexing/.readthedocs.yaml @@ -0,0 +1,43 @@ +# Read the Docs configuration for the zarr-indexing docs site, separate from +# the zarr-python site configured by the repo-root .readthedocs.yaml. The RTD +# project for zarr-indexing must set its configuration-file path to +# packages/zarr-indexing/.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. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- packages/zarr-indexing; + then + exit 183; + fi + install: + - pip install --upgrade pip + - pip install ./packages/zarr-indexing --group packages/zarr-indexing/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-indexing 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-indexing && mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html + +mkdocs: + configuration: packages/zarr-indexing/mkdocs.yml diff --git a/packages/zarr-indexing/CHANGELOG.md b/packages/zarr-indexing/CHANGELOG.md new file mode 100644 index 0000000000..7c4bc92cad --- /dev/null +++ b/packages/zarr-indexing/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release notes + + diff --git a/packages/zarr-indexing/CONTRIBUTING.md b/packages/zarr-indexing/CONTRIBUTING.md new file mode 100644 index 0000000000..632e24929f --- /dev/null +++ b/packages/zarr-indexing/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# Contributing to zarr-indexing + +Package-scoped development commands live in the [`justfile`](./justfile) +(requires [just](https://github.com/casey/just)): + +``` +just test # run the test suite (extra args go to pytest) +just lint # ruff, same invocation as CI +just typecheck # pyright, same invocation as CI +just docs-check # strict build of the docs site +just check # all of the above +just docs-serve # serve the docs site locally +``` + +Run them from this directory, or from anywhere in the repository as +`just packages/zarr-indexing/`. + +The test recipe runs against the workspace-root environment, because the +chunk-resolution tests exercise this package against `zarr`'s chunk grids and +`zarr` is deliberately not a dependency of this package. + +## License + +MIT + +The package lives at `packages/zarr-indexing` inside the +[zarr-python](https://github.com/zarr-developers/zarr-python) repository. diff --git a/packages/zarr-indexing/LICENSE.txt b/packages/zarr-indexing/LICENSE.txt new file mode 100644 index 0000000000..1e8da4d242 --- /dev/null +++ b/packages/zarr-indexing/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-indexing/README.md b/packages/zarr-indexing/README.md new file mode 100644 index 0000000000..7e2cec10dd --- /dev/null +++ b/packages/zarr-indexing/README.md @@ -0,0 +1,52 @@ +# zarr-indexing + +Composable, lazy coordinate transforms for Zarr array indexing. + +Documentation: + +This package implements TensorStore-inspired index transforms. The core idea: +every indexing operation (slicing, fancy indexing, etc.) produces a coordinate +mapping from user space to storage space. These mappings compose lazily — no +I/O until you explicitly read or write. + +Key types: + +- `LazyArray` — wraps a system-memory/basic-indexing source and adds a `.lazy` + accessor: `LazyArray.from_numpy(numpy_array).lazy[10:50, ::2].lazy.oindex[[3, 1, 1], :]` + composes a transform and returns a new view without reading data, and + `result()` materializes it into owned system memory. `LazyArray(source)` uses + the conservative basic reader; `from_numpy` explicitly selects NumPy's + optimized reader. Device arrays require an explicit custom reader responsible + for transferring values into the supplied system-memory output buffer. +- `Reader` — the explicit backend execution boundary: transforms say which + values belong in the result, while readers say how a backend obtains them +- `IndexDomain` — a rectangular region of integer coordinates +- `IndexTransform` — maps input coordinates to storage coordinates +- `ChunkPlan` and `ChunkProjection` — lazily partition a selection over a + caller-selected grid and pair each chunk-local transform with its placement in + the request, without binding a storage backend or scheduler +- `ConstantMap`, `DimensionMap`, `ArrayMap` — the three ways a single output + dimension can depend on the input +- `compose` — chain two transforms into one + +The package depends only on NumPy and the standard library; it does not import +`zarr`. It is developed in the [zarr-python](https://github.com/zarr-developers/zarr-python) +repository and consumed by `zarr` to resolve array indexing operations. + +## Installation + +```bash +pip install zarr-indexing +``` + +## Examples + +- [Lazy indexing a NumPy array](examples/lazy_indexing_numpy/README.md) +- [Lazy indexing with Dask](examples/lazy_indexing_dask/README.md) + +## Contributing + +Development commands, the test suite and the docs build are described in +[CONTRIBUTING.md](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CONTRIBUTING.md) +in the repository. Issues and pull requests go to +[zarr-developers/zarr-python](https://github.com/zarr-developers/zarr-python). diff --git a/packages/zarr-indexing/changes/3906.feature.md b/packages/zarr-indexing/changes/3906.feature.md new file mode 100644 index 0000000000..4a4b754bd8 --- /dev/null +++ b/packages/zarr-indexing/changes/3906.feature.md @@ -0,0 +1 @@ +Reworked the JSON layer to conform to the [ndsel](https://github.com/zarr-developers/ndsel) draft wire format, which adapts TensorStore's `IndexTransform`. A new `zarr_indexing.messages` module (`parse_ndsel`, `normalize_ndsel`, `NdselError`) is a pure JSON-to-JSON layer that accepts all five message kinds (`point`/`box`/`slice`/`points`/`transform`) and normalizes them to the canonical transform body, enforcing the full ndsel error taxonomy. The package is checked against the vendored, language-agnostic ndsel conformance corpus. Serialization produces and consumes the canonical body (`IndexTransform.to_json`/`from_json`, and the `IndexDomain` pair). On serialization, orthogonal (`oindex`) `index_array` maps no longer emit `input_dimension` alongside `index_array` (a combination both ndsel and TensorStore reject), and degenerate all-singleton index arrays collapse to constant maps; the in-memory `input_dimension` is reconstructed from the array's dependency axes on load. diff --git a/packages/zarr-indexing/changes/4222.bugfix.1.md b/packages/zarr-indexing/changes/4222.bugfix.1.md new file mode 100644 index 0000000000..8cff5be6e4 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.bugfix.1.md @@ -0,0 +1,39 @@ +Correctness fixes to indexing and resolution, all reachable from 0.1.0: + +- An integer index applied to an axis a previous `oindex`/`vindex` step had + already indexed left an all-singleton `ArrayMap` still naming the axis the + integer removed, which after renumbering aliased a different one. Such a map + now collapses to a `ConstantMap` at composition time. +- A `vindex` selection whose coordinate arrays are not on the leading axes + (`vindex[..., i, j]`, `vindex[..., mask]`) laid out its result incorrectly and + raised a shape mismatch on a partitioned read. Gathered dimensions now follow + NumPy's placement rule, and the per-part gather is realigned to the scatter. +- An `oindex`/`vindex` step whose entries are all slices, applied to a view with + a fancy-indexed axis, applied those slices positionally to every axis of the + existing index array — including broadcast singletons — truncating it to size + 0, so `result()` returned an unwritten buffer. Reindexing is now + dependency-aware. +- `parts()` raised on a view emptied by a slice over an axis of extent 1; an + empty domain now yields no parts, matching `result()`. +- Negative-stride chunk projection swapped the endpoints while keeping the step + negative, selecting nothing where the reversed axis was meant. Composition + evaluated an inner index array over `range(size)` rather than the outer + domain's own range, resolving every coordinate wrongly whenever that domain + did not start at 0 — which both step-1 and negative-step slices produce. +- A domain dimension no output map depends on, left behind when a later basic + index consumes the axis a `vindex` array varied over, was miscounted in three + places: the partition walk's out-selection rank, the lowering engine's axis + restoration, and the correlated gather's broadcast. +- The parts of a correlated view narrowed to a single point came back rank 1 + where the view was rank 0, so the documented + `out[part.out_selection] = part.view.result()` assembly raised `ValueError`. +- `result()` could return memory shared with the wrapped array: an unpartitioned + read of a basic selection lowered to plain slicing and handed back a view of + the source, and `numpy.array(view, copy=True)` inherited the alias. It now + always allocates, and verifies the parts covered the output before returning. +- `IndexTransform.from_json` rejects a non-integer `index_array` with an + `NdselError` carrying `invalid_json`, rather than truncating a float array, + coercing booleans, or leaking NumPy's conversion error for strings. +- `result(parts=...)` raises `ValueError` rather than `AssertionError` when the + supplied parts do not tile the view, and `with_parts` / `with_parts_per_axis` + raise the documented `ValueError` for non-iterable input. diff --git a/packages/zarr-indexing/changes/4222.bugfix.md b/packages/zarr-indexing/changes/4222.bugfix.md new file mode 100644 index 0000000000..0717e1e384 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.bugfix.md @@ -0,0 +1,9 @@ +An adversarial review of the whole package found, and this fixes, several +defects at its boundaries: `result()` and `__array__(copy=True)` could hand back +a live view of a source that merely stored its data in NumPy; the wire format +emitted a document nothing could load for a selection that selects nothing, and +its domain loader validated nothing; chunk-selection lowering described a +transposed block in two separate cases; a map derived from a vectorized +selection carried a stale `input_dimension`, which made one view's answer depend +on how it was partitioned; and `oindex` over a correlated view applied NumPy's +vectorized rule instead of the outer product. diff --git a/packages/zarr-indexing/changes/4222.feature.1.md b/packages/zarr-indexing/changes/4222.feature.1.md new file mode 100644 index 0000000000..bc62baf357 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.1.md @@ -0,0 +1,7 @@ +Added `UnitStepReader` / `unit_step_reader`: a backend adapter for sources +whose basic indexing accepts only ascending step-1 slices (FFI bindings, HTTP +range endpoints). Every key it presents is `slice(start, stop, 1)` per axis; +strides, reversals, and gathers are applied to the in-memory block by the +residual lowering. The integrations guide documents the companion dense-box +re-partition idiom — resolving a unit-stride rectangular view as one backend +slab read while keeping partitioned reads for strided and fancy selections. diff --git a/packages/zarr-indexing/changes/4222.feature.2.md b/packages/zarr-indexing/changes/4222.feature.2.md new file mode 100644 index 0000000000..722f56db99 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.2.md @@ -0,0 +1,24 @@ +Added `LazyArray`, which grafts the full NumPy indexing dialect onto any source +exposing `shape`, `dtype`, and basic integer/slice `__getitem__` — a chunked +store, an FFI binding, an HTTP endpoint. `view.lazy[...]`, `.lazy.oindex[...]` +and `.lazy.vindex[...]` each compose an `IndexTransform` and return a new view +without reading anything; `result()` materializes. Selections use positional +NumPy semantics (negatives wrap, scalars drop their axis, coordinate arrays keep +order and duplicates), which the new `zarr_indexing.boundary` module translates +into the algebra's literal coordinates. The wrapper describes reads only, and +behaves as a duck array: eager `__getitem__` and `__array__` make it a +`dask.array.from_array` source. + +A read is divided along a **partitioning** — discovered from the wrapped array, +or chosen with `with_parts` / `with_parts_per_axis` / `unpartitioned`. +`parts()` yields one `Partition` per box, pairing a resolvable sub-view with +where its cells belong in the result; `result()` is the assembly of that walk, +and re-partitioning never changes what it returns. `base_shape` says which shape a partitioning is expressed in. `is_box`, `bounding_box()` +and `strides()` report whether a selection is rectangular, so a consumer can +dispatch a slab read against a gather. + +See the [guide](https://zarr-indexing.readthedocs.io/en/latest/guide/) for the +model and the +[design notes](https://zarr-indexing.readthedocs.io/en/latest/design-notes/) +for the box/query distinction, the relationship to TensorStore, and current +scope limits. diff --git a/packages/zarr-indexing/changes/4222.feature.3.md b/packages/zarr-indexing/changes/4222.feature.3.md new file mode 100644 index 0000000000..ef0e1512c2 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.3.md @@ -0,0 +1,9 @@ +Added source-independent chunk planning. `plan_chunks(transform, grids)` returns +a lazy, reusable `ChunkPlan` whose `ChunkProjection`s each pair a chunk-local +transform with a transform back to the request, over one shared cell domain, so +a consumer can read a chunk and place its values without re-deriving either. The +same representation covers basic, orthogonal and vectorized indexing, and +carries global chunk bounds plus conservative full/partial/unknown coverage. +I/O, buffering and scheduling stay with the consumer. `zarr_indexing.grid` gained +`EdgeDimensionGrid` and `dimension_grids_from_chunks` for building the per-axis +grids it takes. diff --git a/packages/zarr-indexing/changes/4222.feature.4.md b/packages/zarr-indexing/changes/4222.feature.4.md new file mode 100644 index 0000000000..623d381083 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.4.md @@ -0,0 +1,8 @@ +`LazyArray` has an explicit reader boundary: an `IndexTransform` decides which +values belong in a result, and a `Reader` decides how one backend obtains them, +preserving the transform exactly. `LazyArray(source)` is conservative and assumes +only basic indexing; `LazyArray.from_numpy(array)` selects the optimized NumPy +reader; `with_reader` selects any other. Readers do not define indexing +semantics, partitioning, scheduling, or result ownership. Both built-in readers +lower through NumPy system memory, so a device array needs a custom reader that +transfers into the supplied output buffer. diff --git a/packages/zarr-indexing/changes/4222.feature.5.md b/packages/zarr-indexing/changes/4222.feature.5.md new file mode 100644 index 0000000000..859667775f --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.5.md @@ -0,0 +1,8 @@ +Added the `zarr_indexing.testing` subpackage, behind a `testing` extra +(`pip install zarr-indexing[testing]`), carrying the Hypothesis machinery this +package tests itself with. `ChainedIndexingStateMachine` composes basic, +orthogonal and vectorized selections onto a `LazyArray` wrapping an array you +supply, then checks every view's shape, `result()`, and assembled `parts()` +against NumPy; `zarr_indexing.testing.strategies` exports the selection +strategies alone, for a project with its own harness. Nothing outside the +subpackage imports Hypothesis. diff --git a/packages/zarr-indexing/changes/4222.feature.6.md b/packages/zarr-indexing/changes/4222.feature.6.md new file mode 100644 index 0000000000..8c65f947e6 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.6.md @@ -0,0 +1,9 @@ +Negative-step slices are supported, following merged ndsel 1.0-draft.2 and +TensorStore 0.1.84: `arr[::-1]`, `arr[5:1:-2]`, and reversal composed over an +already-strided or already-gathered view. One desugaring rule covers both signs — +omitted bounds resolve on the side the traversal starts and stops, and the origin +is `trunc(start / step)` — while a reversed interval is an error rather than a +silently empty selection. A reversing slice normally yields a negative domain +origin, since the result stays anchored to the source coordinate frame; +`LazyArray` re-bases every view to origin 0, so its positional dialect is +unaffected. diff --git a/packages/zarr-indexing/changes/4222.feature.md b/packages/zarr-indexing/changes/4222.feature.md new file mode 100644 index 0000000000..c02ab54edb --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.md @@ -0,0 +1,11 @@ +Fancy selections compose without restriction, on both `LazyArray` and +`IndexTransform`: a second `oindex`/`vindex`/mask step may land on any axis of +an already-fancy view, including axes an existing index array merely broadcasts +along. Array-carrying transforms are chained through `compose`, and resolution +handles the resulting mixed, correlated and diagonal index-array structures on +one shared pointwise path, classified by `IndexTransform.index_array_structure`. +Only hand-built affine diagonals — an index array and a slice map bound to the +same axis — remain unsupported. + +`__dask_tokenize__` digests a view's canonical transform body rather than +embedding it, so tokens stay small for large fancy selections. diff --git a/packages/zarr-indexing/changes/4222.misc.md b/packages/zarr-indexing/changes/4222.misc.md new file mode 100644 index 0000000000..1bd73e1c80 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.misc.md @@ -0,0 +1,5 @@ +Restructured the documentation-contract tests: the snippet include graph is +now discovered by scanning the rendered markdown instead of hand-maintained +registries, prose and navigation assertions moved out of CI, and +`pymdownx.snippets` now sets `check_paths: true` so an unresolvable include +fails `mkdocs build --strict` instead of silently rendering nothing. diff --git a/packages/zarr-indexing/changes/4222.removal.1.md b/packages/zarr-indexing/changes/4222.removal.1.md new file mode 100644 index 0000000000..33ff9cb423 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.1.md @@ -0,0 +1,12 @@ +The canonical JSON converters are now methods on the types that own the +serialization: `IndexTransform.to_json()` / `IndexTransform.from_json()`, +`IndexDomain.to_json()` / `IndexDomain.from_json()`, and `to_json()` on each +output map kind. `output_index_map_from_json` remains a function, in +`zarr_indexing.output_map`, because the wire form is a tagged union and +loading it dispatches rather than belonging to any one kind. + +The free functions they replace — `transform_to_canonical`, +`transform_from_canonical`, `index_domain_to_json`, `index_domain_from_json`, +`output_index_map_to_json`, and the historical aliases +`index_transform_to_json` / `index_transform_from_json` — are removed. There +had been two spellings of each conversion; there is now one. diff --git a/packages/zarr-indexing/changes/4222.removal.2.md b/packages/zarr-indexing/changes/4222.removal.2.md new file mode 100644 index 0000000000..d3321ea81c --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.2.md @@ -0,0 +1,15 @@ +Operations moved onto the types that own them, following the arrangement +TensorStore uses (public headers are the types; every transform operation +lives in `internal/` and surfaces as a method): + +- `compose(outer, inner)` is now `outer.compose(inner)`, and the algorithm + moved to the private `zarr_indexing._composition`. +- `selection_to_transform(selection, transform, mode)` is now + `transform.select(selection, mode)`. +- `index_array_structure(transform)` is now the `transform.index_array_structure` + property. +- `array_map_dependent_axis(m)` is now the `ArrayMap.dependent_axis` property, + alongside a new `ArrayMap.dependency_axes` giving every axis a map varies over. + +`zarr_indexing.affine` is now the private `zarr_indexing._affine`; it was +never exported or documented. diff --git a/packages/zarr-indexing/changes/4222.removal.3.md b/packages/zarr-indexing/changes/4222.removal.3.md new file mode 100644 index 0000000000..d5210f4c8d --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.3.md @@ -0,0 +1,6 @@ +`with_parts` is now three named methods — `with_parts`, `with_parts_per_axis` +and `unpartitioned` — instead of one parameter whose meaning was decided by the +type of what it was given. `Partition.array` is `Partition.view`, no longer the +inverse of `LazyArray.array`. `ArrayMap`, `IndexTransform` and `Partition` can +be compared and hashed, which `frozen=True` had implied and neither could do. +`LazyArray.base_shape` says which shape a partitioning is expressed in. diff --git a/packages/zarr-indexing/changes/4222.removal.md b/packages/zarr-indexing/changes/4222.removal.md new file mode 100644 index 0000000000..5782c9ab4d --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.md @@ -0,0 +1,11 @@ +`ArrayMap` no longer has an `input_dimension` field: what a map depends on is +read from its full-rank index array's shape (its non-singleton axes), the +single source of truth. A selection narrowed to a single coordinate is now +built as the `ConstantMap` it equals (`array_map_or_constant`), so a length-1 +fancy selection classifies as a box; hand-built all-singleton or shared-axis +`ArrayMap`s resolve through the pointwise path. The wire format is unaffected — +it never carried the field. + +The provisional tuple resolver and selector bridge are gone with it: +`iter_chunk_transforms` and `sub_transform_to_selections` are removed, their +role taken by `plan_chunks` and the paired projections it returns. diff --git a/packages/zarr-indexing/changes/README.md b/packages/zarr-indexing/changes/README.md new file mode 100644 index 0000000000..feb3f8674e --- /dev/null +++ b/packages/zarr-indexing/changes/README.md @@ -0,0 +1,25 @@ +Writing a changelog entry for `zarr-indexing` +----------------------------------------------- + +Fragments in **this** directory are release notes for the `zarr-indexing` +package only — kept separate from the parent zarr-python `changes/` +directory so a PR touching only `packages/zarr-indexing/` 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-indexing`. + +A `zarr-indexing` release runs `towncrier build` in `packages/zarr-indexing/`, +which consumes the fragments here and updates `CHANGELOG.md`. Fragments +that describe parent zarr-python changes (not the transforms package) +belong in the top-level `changes/` directory, not here. diff --git a/packages/zarr-indexing/docs/_static/favicon-96x96.png b/packages/zarr-indexing/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000..e77977ccf4 Binary files /dev/null and b/packages/zarr-indexing/docs/_static/favicon-96x96.png differ diff --git a/packages/zarr-indexing/docs/_static/logo_bw.png b/packages/zarr-indexing/docs/_static/logo_bw.png new file mode 100644 index 0000000000..df1979d3cc Binary files /dev/null and b/packages/zarr-indexing/docs/_static/logo_bw.png differ diff --git a/packages/zarr-indexing/docs/api/boundary.md b/packages/zarr-indexing/docs/api/boundary.md new file mode 100644 index 0000000000..4f9fa99531 --- /dev/null +++ b/packages/zarr-indexing/docs/api/boundary.md @@ -0,0 +1,5 @@ +--- +title: boundary +--- + +::: zarr_indexing.boundary diff --git a/packages/zarr-indexing/docs/api/chunk_resolution.md b/packages/zarr-indexing/docs/api/chunk_resolution.md new file mode 100644 index 0000000000..0d81ec3829 --- /dev/null +++ b/packages/zarr-indexing/docs/api/chunk_resolution.md @@ -0,0 +1,5 @@ +--- +title: chunk_resolution +--- + +::: zarr_indexing.chunk_resolution diff --git a/packages/zarr-indexing/docs/api/domain.md b/packages/zarr-indexing/docs/api/domain.md new file mode 100644 index 0000000000..b039d3a7f4 --- /dev/null +++ b/packages/zarr-indexing/docs/api/domain.md @@ -0,0 +1,5 @@ +--- +title: domain +--- + +::: zarr_indexing.domain diff --git a/packages/zarr-indexing/docs/api/errors.md b/packages/zarr-indexing/docs/api/errors.md new file mode 100644 index 0000000000..994a74248a --- /dev/null +++ b/packages/zarr-indexing/docs/api/errors.md @@ -0,0 +1,5 @@ +--- +title: errors +--- + +::: zarr_indexing.errors diff --git a/packages/zarr-indexing/docs/api/grid.md b/packages/zarr-indexing/docs/api/grid.md new file mode 100644 index 0000000000..b7c376eb85 --- /dev/null +++ b/packages/zarr-indexing/docs/api/grid.md @@ -0,0 +1,22 @@ +--- +title: grid +--- + +`zarr_indexing.grid` owns compact chunk-grid metadata so indexing plans can be +constructed without importing Zarr. `FixedDimension(size, extent)` represents +regular chunks in constant memory, including a clipped final data region; +`VaryingDimension(edges, extent)` represents explicit rectilinear chunk edges. +`ChunkGrid(dimensions=...)` combines these dimensions and returns `ChunkSpec` +objects whose `shape` is the valid data size and whose `codec_shape` preserves +the full codec-buffer size at a regular-grid boundary. + +`dimension_grids_from_chunks` returns these compact dimensions: integer chunk +shapes become `FixedDimension` instances and explicit per-axis edge sequences +become `VaryingDimension` instances. `DimensionGridLike` remains the narrow +protocol used by the chunk planner, while `EdgeDimensionGrid` is kept for +explicit edge-based and coordinate-origin examples. + +Zarr's array implementation can later import these compact grid types from +`zarr_indexing`; this package intentionally has no import dependency on Zarr. + +::: zarr_indexing.grid diff --git a/packages/zarr-indexing/docs/api/index.md b/packages/zarr-indexing/docs/api/index.md new file mode 100644 index 0000000000..674c701a0f --- /dev/null +++ b/packages/zarr-indexing/docs/api/index.md @@ -0,0 +1,87 @@ +--- +title: API reference +--- + +# API reference + +Choose the guide stopping point that matches your job before following module +links: + +- **Use lazy indexing:** finish + [Lazy views compose](../guide/index.md#lazy-views-compose), + then open [`zarr_indexing.lazy_array`](lazy_array.md) for `LazyArray`. +- **Integrate a chunked source:** finish + [One cell domain, two projections](../guide/index.md#one-cell-domain-two-projections), + then open [`zarr_indexing.chunk_resolution`](chunk_resolution.md) for + `plan_chunks`. Start with + [Coordinates are addresses](../guide/index.md#coordinates-are-addresses) if + literal coordinates are unfamiliar. + +The modules are layered: the transform algebra at the bottom, chunk resolution +and the wire format built on top of it. + +**The transform algebra** + +- [`zarr_indexing.domain`](domain.md) — `IndexDomain`, a rectangular region of + integer coordinates with an explicit (possibly non-zero) origin +- [`zarr_indexing.output_map`](output_map.md) — `ConstantMap`, `DimensionMap`, + and `ArrayMap`: three representations of a set of integer coordinates, one + per storage dimension +- [`zarr_indexing.transform`](transform.md) — `IndexTransform`, which pairs a + domain with output maps, plus the indexing (`[...]`, `.oindex`, `.vindex`), + `intersect`, and `translate` operations, and `selection_to_transform` + transforms into one + +**Chunk resolution** + +- [`zarr_indexing.chunk_resolution`](chunk_resolution.md) — + `plan_chunks`, which lazily projects a request through a caller-selected grid, + plus the reusable `ChunkPlan` and paired-transform `ChunkProjection` values +- [`zarr_indexing.grid`](grid.md) — `DimensionGridLike`, the Protocol + describing the narrow chunk-grid surface chunk resolution consumes, so that + nothing here imports `zarr`, plus `EdgeDimensionGrid` and + `dimension_grids_from_chunks`, a concrete per-axis grid for callers with no + zarr grid to hand + +**Lazy arrays** + +- [`zarr_indexing.lazy_array`](lazy_array.md) — `LazyArray`, a wrapper for + system-memory/basic-indexing sources that adds a `.lazy` accessor for + TensorStore-style deferred indexing, plus `Partition` and `parts()` / + `with_parts()`, which determine the boxes a read is broken into. Device + sources require an explicit custom reader that transfers into the supplied + system-memory output +- [`zarr_indexing.reader`](reader.md) — `Reader`, the backend execution boundary + that obtains the values described by a complete transform; `basic_reader` + serves conservative duck arrays and `numpy_reader` is selected explicitly by + `LazyArray.from_numpy` +- [`zarr_indexing.boundary`](boundary.md) — the translation between NumPy's + positional dialect and the transform algebra's literal coordinates + +**The ndsel wire format** (see [the guide](../ndsel.md)) + +- [`zarr_indexing.messages`](messages.md) — `parse_ndsel` / `normalize_ndsel`, + the pure JSON→JSON message layer, and `NdselError` +- [`zarr_indexing.json`](json.md) — lowering between canonical ndsel bodies and + in-memory transforms + +**Errors** + +- [`zarr_indexing.errors`](errors.md) — the index-error types this package + raises, also exported at the top level. `zarr.errors` defines classes of the + same names, which are different objects; both subclass `IndexError` + +**Test support** (needs the `testing` extra) + +- [`zarr_indexing.testing.stateful`](testing_stateful.md) — + `ChainedIndexingStateMachine`, a Hypothesis state machine that composes + indexing steps onto a `LazyArray` wrapping your array and checks every step + against NumPy, plus `apply_selection`, the NumPy model it checks against +- [`zarr_indexing.testing.strategies`](testing_strategies.md) — the selection + strategies the machine draws from, for a project that has its own harness + +Every name listed in `zarr_indexing.__all__` is re-exported at the top level, +so `from zarr_indexing import IndexTransform` and +`from zarr_indexing.transform import IndexTransform` are equivalent. +`zarr_indexing.testing` is deliberately not among them: it imports +`hypothesis`, which the rest of the package does not. diff --git a/packages/zarr-indexing/docs/api/json.md b/packages/zarr-indexing/docs/api/json.md new file mode 100644 index 0000000000..0183ab30e7 --- /dev/null +++ b/packages/zarr-indexing/docs/api/json.md @@ -0,0 +1,5 @@ +--- +title: json +--- + +::: zarr_indexing.json diff --git a/packages/zarr-indexing/docs/api/lazy_array.md b/packages/zarr-indexing/docs/api/lazy_array.md new file mode 100644 index 0000000000..f855511d46 --- /dev/null +++ b/packages/zarr-indexing/docs/api/lazy_array.md @@ -0,0 +1,27 @@ +--- +title: lazy_array +--- + +`LazyArray.lazy[...]` is metadata-only: every derived view keeps the same +reader and composes its transform without reading data. `result()` allocates +owned system memory, then calls that reader once for each projected part. +Rectangular parts write directly into their final slices; advanced placement +may first use an owned dense temporary. `LazyArray(source)` assumes only basic +indexing, while `LazyArray.from_numpy(array)` explicitly selects NumPy's +optimized reader. + +The built-in readers lower through NumPy system memory and support sources +whose basic reads can be converted there. They do not implicitly transfer +device arrays; a device source needs an explicit custom reader that transfers +into the supplied system-memory output. Derived views and parts share their +reader and part views may be materialized concurrently, so stateful readers +must synchronize their own mutable state. + +Every public `Partition.view.transform` directly maps that view's zero-origin +coordinates into its raw `Partition.view.array`, including for non-first +partitions. `Partition.projection.chunk_transform` intentionally stays local to +the selected chunk. During materialization the reader receives both frames in +one `ReadContext`: the public global transform in `context.transform` and the +same local plan in `context.projection`. + +::: zarr_indexing.lazy_array diff --git a/packages/zarr-indexing/docs/api/messages.md b/packages/zarr-indexing/docs/api/messages.md new file mode 100644 index 0000000000..6c2a434540 --- /dev/null +++ b/packages/zarr-indexing/docs/api/messages.md @@ -0,0 +1,5 @@ +--- +title: messages +--- + +::: zarr_indexing.messages diff --git a/packages/zarr-indexing/docs/api/output_map.md b/packages/zarr-indexing/docs/api/output_map.md new file mode 100644 index 0000000000..55114a6997 --- /dev/null +++ b/packages/zarr-indexing/docs/api/output_map.md @@ -0,0 +1,5 @@ +--- +title: output_map +--- + +::: zarr_indexing.output_map diff --git a/packages/zarr-indexing/docs/api/reader.md b/packages/zarr-indexing/docs/api/reader.md new file mode 100644 index 0000000000..39129c4d47 --- /dev/null +++ b/packages/zarr-indexing/docs/api/reader.md @@ -0,0 +1,51 @@ +--- +title: Readers +--- + +# Readers + +An `IndexTransform` defines which source value belongs at every result +position. A `Reader` defines how a particular backend obtains those values. +Readers do not define indexing semantics, partitioning, scheduling, or result +ownership. + +`Reader.read_into(source, context, out)` receives a `ReadContext` whose +`transform` maps zero-origin output-buffer coordinates to global coordinates in +`source`, with `context.transform.domain.shape == out.shape`. Its optional +`projection` is the existing plan for a partitioned read. The projection's +`chunk_transform` remains chunk-local, its `cell_transform` describes result +placement, and its `chunk_domain` describes the grid cell. The global read +transform and the projection's chunk transform deliberately use different +coordinate frames. + +An implementation must fill every cell of `out` in place, preserve the global +transform's exact values, order, and dtype, and return `None`. It must neither +replace nor retain `out`, which may be a strided writable view. Backend +exceptions propagate unchanged. Derived part views share their reader and may +be resolved concurrently, so a stateful reader owns its own synchronization. + +Reader wrappers compose by intercepting this one operation and forwarding the +same source, context, and output buffer to an inner reader: + +```python +class RecordingReader: + def __init__(self, inner): + self.inner = inner + self.calls = [] + + def read_into(self, source, context, out, /): + self.calls.append((source, context, out)) + self.inner.read_into(source, context, out) + + +inner = RecordingReader(numpy_reader) +outer = RecordingReader(inner) +view = LazyArray.from_numpy(array).with_reader(outer) +values = view.result() +``` + +Both wrappers observe the same three objects, in outer-to-inner order. This +delegation pattern supports policies such as logging and caching without +library-defined wrapper primitives. + +::: zarr_indexing.reader diff --git a/packages/zarr-indexing/docs/api/testing_stateful.md b/packages/zarr-indexing/docs/api/testing_stateful.md new file mode 100644 index 0000000000..0aeb57df29 --- /dev/null +++ b/packages/zarr-indexing/docs/api/testing_stateful.md @@ -0,0 +1,5 @@ +--- +title: testing.stateful +--- + +::: zarr_indexing.testing.stateful diff --git a/packages/zarr-indexing/docs/api/testing_strategies.md b/packages/zarr-indexing/docs/api/testing_strategies.md new file mode 100644 index 0000000000..1dd7d59457 --- /dev/null +++ b/packages/zarr-indexing/docs/api/testing_strategies.md @@ -0,0 +1,5 @@ +--- +title: testing.strategies +--- + +::: zarr_indexing.testing.strategies diff --git a/packages/zarr-indexing/docs/api/transform.md b/packages/zarr-indexing/docs/api/transform.md new file mode 100644 index 0000000000..8e67a162c1 --- /dev/null +++ b/packages/zarr-indexing/docs/api/transform.md @@ -0,0 +1,18 @@ +--- +title: transform +--- + +An `IndexTransform` is a function between coordinate spaces, and its field +names follow the function, not the data: + +| the API says | in array terms | +| --- | --- | +| input space (`domain`, `input_rank`) | request coordinates — the result being built | +| output space (`output`, one map per dimension) | source coordinates — where values are read | + +`output` is not data: it is the rule, per source dimension, for producing +coordinates. Values flow source → request, against the arrow. The +[guide](../guide/index.md#a-transform-points-from-the-request-to-the-source) +demonstrates each output map form against its NumPy counterpart. + +::: zarr_indexing.transform diff --git a/packages/zarr-indexing/docs/design-notes.md b/packages/zarr-indexing/docs/design-notes.md new file mode 100644 index 0000000000..78b352d376 --- /dev/null +++ b/packages/zarr-indexing/docs/design-notes.md @@ -0,0 +1,296 @@ +--- +title: Design notes +--- + +# Design notes + +This page records advanced rationale that the API does not state directly: how +this library relates to TensorStore, why rectangular selections are a category +rather than a fast path, and what is deliberately not implemented yet. The +visual guide owns the mechanics of +[literal coordinates](guide/index.md#coordinates-are-addresses), +[view composition](guide/index.md#lazy-views-compose), +[chunk plans](guide/index.md#a-request-becomes-a-chunk-plan), and +[their paired projections](guide/index.md#one-cell-domain-two-projections). + +## Relationship to TensorStore + +The core is [TensorStore's](https://google.github.io/tensorstore/index_space.html) +index-transform model, reimplemented in Python against NumPy. The visual guide +introduces the shared model in +[Coordinates are addresses](guide/index.md#coordinates-are-addresses) and +[Lazy views compose](guide/index.md#lazy-views-compose); the comparison here is +about the deliberately matching semantics: + +- **The model.** Both use an `IndexTransform` made of an input domain and one + output index map per storage dimension, in constant, affine, and index-array + forms. +- **Slice semantics.** Slice bounds are literal domain coordinates: no + clamping, no negative wrapping, non-empty intervals must be contained in the + domain, and a strided slice's domain origin is `trunc(start/step)` rounded + toward zero. Every one of those rules was executed against tensorstore 0.1.84 + and is pinned in `tests/test_tensorstore_parity.py`. +- **The wire format.** A canonical [ndsel](ndsel.md) transform body is, + field-for-field, a TensorStore `IndexTransform` minus the `kind` + discriminator, and `tests/test_ndsel_tensorstore.py` loads our bodies into + `tensorstore.IndexTransform(json=...)` and round-trips them back through our + engine layer. + +The representations differ in one place: index arrays. Both models want an index +array at the transform's full input rank, with singleton axes for the dimensions +a map does not vary over. TensorStore enforces it — its JSON parser rejects a +rank-1 array over a rank-2 domain outright, with `Index array for output +dimension 0 has rank 1 but must have rank 2` (checked against tensorstore +0.1.84) — while our loader is the more permissive of the two and also accepts a +lower-rank array that broadcasts against the input domain. That is a +compatibility affordance, not a difference in the model: ndsel leaves index-array +rank to [the engine layer](ndsel.md#lowering-to-a-transform), and everything the +algebra builds itself is at full rank. + +The reason full rank matters here is that we *derive* meaning from those +singletons rather than merely tolerating them: an array full-sized on one axis +and singleton elsewhere is orthogonal, and one varying over several shared axes +is vectorized, so the distinction is readable off the shape — and the shape is +the *only* place it lives. An earlier `ArrayMap.input_dimension` field pinned +the orthogonal axis redundantly and was retired: the one shape it disambiguated +(a single-coordinate array, all axes singleton) is now normalized away at +construction, collapsed to the `ConstantMap` it equals, exactly as +[the serializer](api/json.md) has always collapsed it on the wire. + +Four deliberate differences: + +| | TensorStore | `zarr-indexing` | +| --- | --- | --- | +| Dialect | One strict dialect everywhere: literal coordinates, no negative wrapping | The algebra keeps that dialect; each public boundary picks its own. [`LazyArray`](api/lazy_array.md) speaks positional NumPy, `zarr.Array.lazy` speaks literal. [`zarr_indexing.boundary`](api/boundary.md) is the translation | +| Scheduling | An internal C++ scheduler owns concurrency and chunk ordering | [`parts()`](api/lazy_array.md) exposes the partition structure so the caller's own scheduler — dask, a thread pool, a task queue — drives it | +| Wire format | Implementation-defined JSON, specified by what the implementation accepts | [ndsel](ndsel.md) is spec-first, with a vendored language-agnostic conformance corpus every implementation runs | +| Backends | A driver ecosystem (zarr, N5, neuroglancer, GCS, …) built into the library | No drivers. The default reader needs `shape`, `dtype`, basic integer/slice indexing, and selected slabs convertible to NumPy system memory; other backends use explicit custom readers. A device reader owns transfer into the supplied system-memory output | + +The mechanics of a +[chunk plan](guide/index.md#a-request-becomes-a-chunk-plan) and its +[paired projections](guide/index.md#one-cell-domain-two-projections) belong to +the visual guide. +The relevant comparison is that both libraries use the paired-transform +boundary rather than a read key plus scatter indices, so slices, outer products, +and correlated gathers remain ordinary transforms that a consumer can lower to +its own execution vocabulary. + +The ownership boundary differs. `plan_chunks` retains only the logical request +and caller-supplied grid; it does not own reads, writes, buffers, locks, or +scheduling. Zarr can therefore plan reads against an inner codec-chunk grid and +writes against an atomic shard grid; napari or dask can turn the same +projections into tasks without putting a dask dependency in this package. +`coverage` is relative to that selected grid: `full` proves a blind replacement +safe, `partial` proves it is not, and `unknown` conservatively covers fancy +selections whose duplicates would require additional work to classify. + +The comparison also runs the other way. TensorStore is a mature, heavily +optimized C++ system whose performance this library cannot approach: resolution +here is Python-level bookkeeping over NumPy, and the per-part overhead is +significant. This library is small and depends on nothing beyond NumPy, so the +algebra can be adopted by a Python project that wants the model without the C++ +runtime. + +## Bounding-box selections vs query selections + +Every selection this library can express falls into exactly one of two +categories. The boundary between them is structural, not a heuristic: + +**A box** is a transform whose output maps are all `ConstantMap` or +`DimensionMap` — no `ArrayMap`. Such a map is affine and monotone: storage +coordinate `offset + stride * i` for `i` running over an interval. The whole +selection is therefore described by `O(ndim)` integers — an interval and a +stride per dimension — composition and intersection are interval arithmetic, +and the coordinates it touches form a regular lattice. Basic indexing produces +one, and composing basic indexing with basic indexing keeps one. + +**A query** is a transform with at least one `ArrayMap` — an explicit lookup +table of coordinates. It costs `O(n)` to store, it has no locality (the +coordinates may repeat, reverse, or scatter arbitrarily), and intersecting it +with a region means scanning it. `oindex`, `vindex`, and boolean masks all +produce one, and once an axis is a query, subsequent basic indexing cannot make +it a box again. A second query composes onto any axis of an existing one — +including the axes it merely broadcasts along — by evaluating the existing +lookup tables at the new coordinates. + +Those coordinate arrays are ordered sequences, never mathematical sets. Their +order and duplicate entries are part of the indexing semantics and must survive +planning and materialization. + +[ndsel](ndsel.md) encodes the same split in its message kinds: `point`, `box`, +and `slice` desugar to constant and affine output maps and are always boxes; +`points` desugars to `index_array` maps, and a `transform` body is a box +exactly when none of its output maps carries an `index_array`. A consumer can +therefore classify a selection off the wire without materializing anything: + +```python +from zarr_indexing import IndexTransform + +IndexTransform.from_shape((100, 80))[10:50, ::4].to_json()["output"] +# [{'offset': 0, 'stride': 1, 'input_dimension': 0}, +# {'offset': 0, 'stride': 4, 'input_dimension': 1}] + +import numpy as np +gather = IndexTransform.from_shape((100, 80)).oindex[np.array([90, 3, 3]), slice(None)] +gather.to_json()["output"][0] +# {'offset': 0, 'stride': 1, 'index_array': [[90], [3], [3]], +# 'index_array_bounds': ['-inf', '+inf']} +``` + +The distinction matters to consumers of a selection. A box can be tiled into +rectangular dask chunks or passed to a viewer or tile server that only accepts +rectangles; a query cannot, and has to be resolved into a gather. A box can also +be served as a single strided slab read, but the read has to be strided: reading +its bounding box and discarding the rest transfers proportionally more data as +soon as any stride exceeds 1. The two also behave differently under +partitioning: a box touches a regularly-spaced run of parts, in increasing +order, each at most once — a stride larger than a part's extent skips parts +outright, so the run is not contiguous — while a query can touch any subset of +them, in any order, more than once. + +[`LazyArray`](api/lazy_array.md) exposes the category directly: + +```python +import numpy as np +import zarr + +from zarr_indexing import LazyArray + +arr = zarr.create_array({}, shape=(100, 80), chunks=(30, 40), dtype="int32") +arr[:] = np.arange(8000).reshape(100, 80) +lazy = LazyArray(arr) + +slab = lazy.lazy[10:50, ::4] +slab.is_box # True +slab.bounding_box() # ((10, 50), (0, 77)) +slab.strides() # (1, 4) +slab.shape # (40, 20) + +gather = lazy.lazy.oindex[[90, 3, 3], :] +gather.is_box # False +gather.bounding_box() # ((3, 91), (0, 80)) +gather.strides() # None +gather.shape # (3, 80) +``` + +`bounding_box()` is defined for both: it is the hull, the smallest interval per +storage dimension containing every coordinate the selection reaches. +`strides()` is defined only for a box and gives the step per dimension. +Together the two describe a box selection completely. + +Both are needed, because a box is dense in its hull only when every stride is +1. The slab above spans a 40x77 hull over the 40x20 cells it selects, so a +consumer that issued one rectangular read of the hull and discarded the rest +would transfer 3.85x the data. A query's hull is looser still and carries no +stride at all: 88 rows of hull over three selected rows. An empty *box* touches +no coordinate to report an interval around, so `bounding_box()` is `None` while +`strides()` still answers — the step is a property of the selection's shape, not +of the region it reaches. Only a query returns `None` from both. + +There is deliberately no separate `BoxView` type today. A statically-typed +rectangular-only view is a plausible next step, but it should be introduced by +a consumer that needs the guarantee in its signatures rather than +speculatively; `is_box` is the runtime check until then. + +## Negative-origin domains and prependable grids + +Literal coordinates let a domain grow at its lower end without changing the +identity of anything already present. Prepending three cells extends `[0, 6)` +to `[-3, 6)`: the new cells receive addresses `-3`, `-2`, and `-1`, while the +old cells keep addresses `0` through `5`. Coordinate `0` does not become +coordinate `3`. + +The adjacent intervals `[-3, 0)`, `[0, 3)`, and `[3, 6)` follow the half-open +adjacency rule: each stopping boundary is included exactly once as the next +interval's starting boundary. + +```text +before [0, 6): + + | 0 1 2 | 3 4 5 | +chunk coordinate | 0 | 1 | + +after [-3, 6): + +| -3 -2 -1 | 0 1 2 | 3 4 5 | +| -1 | 0 | 1 | chunk coordinate +``` + +The same holds for chunk grids. `EdgeDimensionGrid` is the convenient +concrete grid for a zero-origin array: its chunk offsets are prefix sums +starting at zero. `DimensionGridLike` is the more general protocol consumed +by chunk planning, so it admits grids with negative chunk and cell +coordinates, including this prependable example: + +```python +--8<-- "snippets/coordinate_origins.py:prepend-grid" +``` + +Here the literal cell domain `[-3, 0)` belongs to chunk `-1`. Both public +projection transforms share the same synthetic input cell domain `[0, 3)`. +Evaluating its three points shows the two distinct outputs: +`chunk_transform` produces zero-origin chunk-local coordinates `0, 1, 2`, +while `cell_transform` produces the literal request coordinates `-3, -2, -1`. +The shared input domain is not itself the chunk-local coordinate frame. + +## Related work + +TensorStore is the prior art for the transform algebra, as described above. At +the execution boundary, this package instead gives each backend a `ReadContext` +through a `Reader`. Its global transform answers **which values?**; the reader +answers **how does this backend obtain them?** A partition view's transform +directly addresses the raw source in global coordinates. Its optional +projection retains the paired planning transforms, of which only +`chunk_transform` addresses zero-origin chunk-local coordinates. The reader +must preserve the global transform exactly, but it does not participate in +indexing semantics, partitioning, scheduling, or result ownership. + +Earlier versions used a capability taxonomy modeled on historical indexing +dialects. That model required deciding which fragment of a request a backend +could accept and finishing the rest elsewhere. A reader lowers the complete +transform and can compose through delegation instead. This resembles +[zarrita.js store extensions](https://zarrita.dev/packages/zarrita.html), where +storage-specific behavior is an explicit extension point rather than an +inferred array capability. The implementation remains independently authored: +no code is shared with TensorStore, xarray, or zarrita.js. + +## Current scope + +Negative steps are supported as of ndsel 1.0-draft.2: `a[::-1]` reverses, one +desugaring rule covers both signs, and a reversed interval is an error rather +than a silently empty selection. One consequence: a negative step normally +produces a negative domain origin. Reversing a length-20 zero-origin axis gives +the domain `[-19, 1)`, because the result stays anchored to the source +coordinate frame and a reversing map traverses that frame backwards. `LazyArray` +re-bases every view to origin 0, so the positional dialect never exposes it; a +caller working with `IndexTransform` directly will see it, and re-bases +explicitly with `translate_domain_to` for NumPy-shaped coordinates. + +Fancy selections compose without restriction: a second `oindex`/`vindex`/mask +step may land on any axis of an already-fancy view, including axes an existing +index array merely broadcasts along, so +`lazy.oindex[[2, 0], :].lazy.oindex[:, [1, 3]]` selects the outer product it +spells. An array-carrying transform is composed — the new selection is applied +to an identity transform over the current domain and chained on with `compose`, +which evaluates the existing lookup tables at the new coordinates — rather than +rewritten in place. Resolution classifies the result by structure +(`index_array_structure`): pure per-axis outer products keep the orthogonal +resolvers, and everything else — correlated maps, mixtures, index arrays +sharing an input axis (a diagonal gather, reachable only by hand-building a +transform) — takes the pointwise path that collapses the joint block. + +Three limits remain, all intentional and all expected to be lifted: + +- **Affine diagonals.** A hand-built transform in which an *index array* and a + *slice map* bind the same input dimension, or two slice maps share one, is + rejected at resolution with `NotImplementedError`. No selection dialect + produces one; supporting them means lowering the slice maps into the joint + block too. *Planned.* +- **Finite explicit bounds only.** `IndexDomain` has no implicit or unbounded + dimensions; the message layer will normalize a body with `"-inf"`/`"+inf"` + bounds, but the engine layer refuses to lower one into a transform. + TensorStore supports both. *Planned.* +- **Labels are carried, not propagated.** `IndexDomain` holds optional + dimension labels and the wire format round-trips them, but indexing + operations build new domains without them, so a label does not survive a + slice. *Planned.* diff --git a/packages/zarr-indexing/docs/examples/lazy_indexing_dask.md b/packages/zarr-indexing/docs/examples/lazy_indexing_dask.md new file mode 100644 index 0000000000..5c722fe355 --- /dev/null +++ b/packages/zarr-indexing/docs/examples/lazy_indexing_dask.md @@ -0,0 +1,7 @@ +--8<-- "lazy_indexing_dask/README.md" + +## Source Code + +```python +--8<-- "lazy_indexing_dask/lazy_indexing_dask.py" +``` diff --git a/packages/zarr-indexing/docs/examples/lazy_indexing_numpy.md b/packages/zarr-indexing/docs/examples/lazy_indexing_numpy.md new file mode 100644 index 0000000000..8a09ce4d01 --- /dev/null +++ b/packages/zarr-indexing/docs/examples/lazy_indexing_numpy.md @@ -0,0 +1,15 @@ +--8<-- "lazy_indexing_numpy/README.md" + +`LazyArray(source)` uses the conservative built-in reader: `source` must expose +`shape`, `dtype`, and basic integer/slice indexing, and every selected slab must +be convertible to NumPy system memory. Coordinate arrays passed through +`oindex` or `vindex` are ordered and duplicate-preserving; they are not sets. +When a view is partitioned, each `Partition.view.transform` addresses the raw +source globally while `Partition.projection.chunk_transform` stays +zero-origin and chunk-local. + +## Source Code + +```python +--8<-- "lazy_indexing_numpy/lazy_indexing_numpy.py" +``` diff --git a/packages/zarr-indexing/docs/examples/system_memory_chunk_cache.md b/packages/zarr-indexing/docs/examples/system_memory_chunk_cache.md new file mode 100644 index 0000000000..e4d92ba2b6 --- /dev/null +++ b/packages/zarr-indexing/docs/examples/system_memory_chunk_cache.md @@ -0,0 +1,11 @@ +--8<-- "system_memory_chunk_cache/README.md" + +`LazyArray` owns the indexing-derived result shape and assembly, while the +example's `SystemMemoryChunkReader` owns synchronous system-memory cache state +and chunk reads for each materialized part. + +## Source Code + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py" +``` diff --git a/packages/zarr-indexing/docs/guide/index.md b/packages/zarr-indexing/docs/guide/index.md new file mode 100644 index 0000000000..780cfd7e56 --- /dev/null +++ b/packages/zarr-indexing/docs/guide/index.md @@ -0,0 +1,444 @@ +# Visual guide + +The whole model in one sentence: indexing through `LazyArray.lazy` builds a +view, chunk planning partitions its coordinates, and `result()` materializes +the view. This page follows one familiar NumPy selection, `source[2:5]`, +through those stages. + +The first four sections are for anyone indexing arrays: coordinates, +transforms, composition, and result axes. **If you are using lazy indexing +rather than building a storage backend, you can stop after section four.** +The last two sections are for integrators: they turn a request into a chunk +plan and pair each chunk read with its place in the result. + +Throughout, one division of labor holds: the transform answers **which +values?** and is independent of the backend; the reader answers **how do I +obtain them?** and must preserve the transform exactly. + +## An index selects coordinates {#an-index-selects-coordinates} + +Begin with an ordinary NumPy array. `source` contains the values 10 through 15. +The selection `source[2:5]` takes source coordinates 2, 3, and 4, containing +the values 12, 13, and 14. + +```text +source coordinate | 0 1 2 3 4 5 +source value | 10 11 12 13 14 15 +selection | [12 13 14] + source[2:5] + +result coordinate | 0 1 2 +source coordinate | 2 3 4 +result value | 12 13 14 +``` + +The result defines its own coordinates: `0`, `1`, and `2`. The aligned rows +make the correspondence explicit: those result coordinates receive values +`12`, `13`, and `14` from source coordinates `2`, `3`, and `4`. + +The wrapper below gives the same familiar selection a lazy spelling. Indexing +through `.lazy` creates `view`; the last line asks for its values and checks the +observable NumPy result. + +```python +--8<-- "snippets/canonical_slice.py:canonical-slice" +``` + +The important first step is simply that an index describes which source values +fill a result in a particular order. The next section gives the numbers on both +sides of that description a precise meaning. + +## Coordinates are addresses {#coordinates-are-addresses} + +### How to read a half-open interval + +`[0, 1)` is a **half-open interval**: start at 0, inclusive, and stop at 1, exclusive. +The `[` includes the lower boundary, while the `)` excludes the upper boundary. +For integer coordinates, `[0, 1)` therefore enumerates the ordered sequence +`[0]`. + +Half-openness lets adjacent slices and chunks meet without a gap or overlap. +Concatenation is ordered: the first interval is followed by the second. When +the first interval's exclusive stop matches the second interval's inclusive +start, the shared boundary coordinate appears exactly once. + +- `[0, 1) -> [0]` — Start at 0 and stop before 1, so the sequence contains only 0. +- `[1, 3) -> [1, 2]` — Start at 1 and stop before 3, so the sequence contains 1 and 2. +- `concat([0, 1), [1, 3)) = [0, 3)` — Append the second interval after the + first. Their matching exclusive/inclusive boundary produces one continuous + interval without a gap or duplicated coordinate. + +Explicit coordinates, including coordinate arrays, are always ordered +sequences rather than mathematical sets. Their order is semantic, and repeated +coordinates remain repeated in the result. + +In the transform algebra, **coordinates are just integers**. A negative +coordinate is a real address in a domain, with the same status as zero or a +positive coordinate; it is not automatically shorthand for counting backward +from an array's end. + +```text +domain [-2, 3) + +coordinate | -2 -1 0 1 2 +status | address address address address address +``` + +`IndexDomain` makes those bounds explicit. In the example below, narrowing the +domain at `-1` selects the literal address `-1`; the wrapper at the end treats +`-1` the way NumPy does — as the last position. + +```python +--8<-- "snippets/coordinate_origins.py:coordinate-origin" +``` + +Why carry literal coordinates at all? They let independently described +regions keep stable addresses — a domain can even grow at its lower end +without renumbering what is already there. The [design +notes](../design-notes.md#negative-origin-domains-and-prependable-grids) work +through that prepending example; nothing else in this guide depends on it. + +The literal model and NumPy's positional model are both useful, but they answer +different questions: + +| Surface | Meaning of an integer index | Meaning of `-1` | +| --- | --- | --- | +| `IndexDomain` and `IndexTransform` | A literal coordinate in the current domain | The actual address `-1`, if the domain contains it | +| `LazyArray.lazy` | A NumPy-style position in the current view | The last position, normalized before it reaches the transform algebra | + +`LazyArray` uses positions because it is an array-like wrapper: each derived +view starts at position zero and negative indices wrap exactly as they do in +NumPy. The lower-level domain and transform types keep literal coordinates. + +### A transform points from the request to the source + +An `IndexTransform` records how every coordinate in a request finds its source +coordinate. For the slice from the first section, request coordinate `i` maps +to source coordinate `i + 2`. This direction is deliberate: request to source, +not source to request. + +```text +request coordinate | 0 1 2 + | | | | + i + 2 | v v v +source coordinate | 2 3 4 +source value | 12 13 14 +``` + +A transform speaks function vocabulary while this guide speaks array +vocabulary. The two line up like this: + +| the API says | this guide says | +| --- | --- | +| input space (`domain`, `input_rank`) | request coordinates — the result being built | +| output space (`output`, one map per dimension) | source coordinates — where values are read | + +`output` names the output side of the coordinate *function*, not the data: +values flow source → request, against the arrow. The neutral names exist +because transforms compose — in a chain, an interior transform's output space +is just the next transform's input space, neither a request nor a source. + +### The three map kinds, in NumPy terms + +Every output dimension is produced by one of three map forms. Each has a +NumPy counterpart, shown executably below. The examples share one helper — +and it doubles as the answer to how a bare transform meets data at all: a +reader materializes it into a buffer. + +```python +--8<-- "snippets/output_maps.py:resolve-helper" +``` + +`DimensionMap` is an arithmetic rule — the slice above is one, mapping +request `i` to source coordinate `i + 2`: + +```python +--8<-- "snippets/output_maps.py:dimension-map" +``` + +`ArrayMap` stores explicit source coordinates for irregular or fancy +indexing; order and repeats survive into the result: + +```python +--8<-- "snippets/output_maps.py:array-map" +``` + +`ConstantMap` fixes one source coordinate for every request cell. Whether an +axis appears in the result is decided by the **domain**, never by the map: +`image[2, :]` compiles to a `ConstantMap(2)` with no corresponding domain +axis (the axis is dropped), while pairing a constant map with a length-`n` +domain axis that no map consumes yields `n` cells all reading one +coordinate — a broadcast, the one arrangement with no NumPy index +counterpart: + +```python +--8<-- "snippets/output_maps.py:constant-map" +``` + +Together, the request domain and these per-source-dimension maps are the +complete reusable description of an index. + +## Lazy views compose {#lazy-views-compose} + +A lazy view can be indexed again. Each step changes the request-to-source +description, but it does not read an intermediate array. The chain is reduced +to one direct transform from the newest request to the original source. + +```text +source[2:5][::-1][1:] + +new request | intermediate view | original source +------------+-------------------+---------------- + 0 | 1 | 3 + 1 | 2 | 2 + +direct map: request i -> source (3 - i) +``` + +The executable example first selects `source[2:5]`, then reverses that view +and trims its first element: + +```python +--8<-- "snippets/lazy_composition.py:lazy-composition" +``` + +Immediately after `composed` is created—and before the final `result()` call—its +metadata is ready to inspect: + +| Available without reading | Value in this example | +| --- | --- | +| `composed.shape` | `(2,)` | +| `composed.transform` | One transform mapping request `i` to source `3 - i` | + +Neither property needs source values. Composition works only on the coordinate +description; the assertion's call to `result()` is the first operation in the +example that materializes the selected data. + +!!! warning "Stop here: the materialization boundary" + Indexing through `.lazy[...]` never reads. These do: + + - `result()` + - eager indexing of the wrapper: `view[...]` + - `numpy.asarray(view)`, or passing the view to any NumPy function + (`numpy.add(view, 1)` converts, and therefore materializes, the view) + + Python arithmetic such as `view + 1` raises `TypeError` instead: this + wrapper defers indexing, not a general compute graph. + + Nor does it write. There is no `__setitem__`, so `view[...] = values` + raises `TypeError` too, and a wrapped source needs no `__setitem__` of + its own. A consumer that writes plans the selection with `plan_chunks` + and performs its own read-modify-write, keeping chunk atomicity and + concurrent-writer policy on the backend's side of the boundary. + +## An index defines a result array {#an-index-defines-a-result-array} + +An index chooses source points and also defines how those points are arranged in +the result. In the 3-by-4 image below, `image[1, :]` and `image[1:2, :]` choose +the same four source points: values `4`, `5`, `6`, and `7`. + +```text +same selected source cells + +source coordinate | (1, 0) (1, 1) (1, 2) (1, 3) +value | 4 5 6 7 + +image[1, :] + +result coordinate | 0 1 2 3 +value | 4 5 6 7 +shape | (4,); source axis 0 is omitted + +image[1:2, :] + +result coordinate | (0, 0) (0, 1) (0, 2) (0, 3) +value | 4 5 6 7 +shape | (1, 4); source axis 0 is retained with length 1 +``` + +The integer in `image[1, :]` fixes source axis 0. No result coordinate varies +along that axis, so it is omitted and the result shape is `(4,)`. The slice in +`image[1:2, :]` preserves source axis 0 as a length-one result axis, so the +result shape is `(1, 4)`. + +```python +--8<-- "snippets/axis_manipulation.py:axis-shape-comparison" +``` + +`None` inserts a new length-one axis without selecting different source points. +Here it produces the shape `(4, 1)`: + +```python +--8<-- "snippets/axis_manipulation.py:axis-insertion" +``` + +## A request becomes a chunk plan {#a-request-becomes-a-chunk-plan} + +Continue with the 3-by-4 image and `image[1, :]` introduced above. Giving the +image a 2-by-2 chunk shape does not change the four selected values or their +order. It changes only how the work is divided: columns 0 and 1 come from chunk +`(0, 0)`, while columns 2 and 3 come from chunk `(0, 1)`. + +```text + column + 0 1 | 2 3 + ----------+---------- +row 0 0 1 | 2 3 +row 1 [4] [5]| [6] [7] <- image[1, :] + ----------+---------- +row 2 8 9 | 10 11 + + left part right part +chunk_coords (0, 0) (0, 1) +global chunk_domain [0,2) x [0,2) [0,2) x [2,4) +selected global cells (1,0), (1,1) (1,2), (1,3) +chunk-local cells (1,0), (1,1) (1,0), (1,1) +request coordinates 0, 1 2, 3 +``` + +Every planned chunk keeps three coordinate frames distinct: + +- `chunk_coords` identifies a cell in the chunk grid. Chunk coordinates are + literal integers, so a grid that grows at its lower end can hold a chunk + whose coordinate really is `-1` — not an alias for the final chunk (see the + [design notes](../design-notes.md#negative-origin-domains-and-prependable-grids)). +- `chunk_domain` gives that chunk's bounds in **global source coordinates**. + Here the two domains are `[0, 2) × [0, 2)` and `[0, 2) × [2, 4)`. +- Chunk-local positions start from zero inside each chunk. Global column 2 is + therefore local column 0 in chunk `(0, 1)`. This zero-origin local frame is + separate from both the global `chunk_domain` and the possibly negative + chunk coordinate. + +`plan_chunks` needs only a transform and the chunk layout: one grid object +per source dimension. A per-dimension grid answers four questions — which +chunk contains a source index, where a chunk starts, how long it is, and +the vectorized form of the first (`index_to_chunk`, `chunk_offset`, +`chunk_size`, `indices_to_chunks`). The library builds these from chunk +sizes via `dimension_grids_from_chunks`; the executable example hand-rolls +one instead, to show that the whole contract is those four answers. It +plans the canonical request over 2-by-2 chunks, and iterates the same plan +again to show that planning is reusable. (The two transforms it inspects on +each projection are the next section's subject.) + +```python +--8<-- "snippets/chunk_projection.py:chunk-projection" +``` + +The plan describes work but does not perform it. It contains no array source, +storage backend, codec pipeline, buffer, or scheduler. A Zarr reader, a task +queue, or a viewport can consume the same logical plan and decide independently +how and when to fetch its two chunks. + +On the wrapper, this partitioning is called **parts**: `with_parts(shape)` +gives a `LazyArray` a grid of uniform boxes to divide its reads along +(re-partitioning is a pure setter — it changes how a read is divided, never +what `result()` returns), and a wrapped array advertising its own `chunks` +is partitioned that way automatically. + +A zero-length source axis has no chunks. `LazyArray` accepts a positive uniform +part shape for that axis, or explicit per-axis spellings `()`, `(0,)`, and +`(0, 0)`; each produces no parts and the same empty result. Zero-sized parts +remain invalid on a nonempty axis. + +## One cell domain, two projections {#one-cell-domain-two-projections} + +A chunk read has to answer two questions at once: which cells belong to this +chunk, and where does each of those cells belong in the requested result? + +Think of a projection as a small table with one row per selected cell. For +each row, `chunk_transform` gives the cell's zero-origin address inside the +chunk, and `cell_transform` gives the position in the requested result that +receives its value. The row numbers of that table are the shared **cell +domain** — a synthetic input space both transforms accept, which is why one +input point can be evaluated on both sides. + +```text +left chunk (0, 0) + +shared cell coordinate | 0 1 +cell_transform | v v +request coordinate | 0 1 + +shared cell coordinate | 0 1 +chunk_transform | v v +chunk-local coordinate | (1, 0) (1, 1) + +right chunk (0, 1) + +shared cell coordinate | 0 1 +request coordinate | 2 3 +chunk-local coordinate | (1, 0) (1, 1) +``` + +The directions are exact: **shared synthetic input cell domain → request via +`cell_transform`**, and **shared cell domain → chunk-local via +`chunk_transform`**. Neither arrow starts at the request or maps one output +space into the other. + +On the wrapper, `view.parts()` returns one `Partition` per planned chunk; +each bundles a sub-view of the request (`.view`), that chunk's projection +(`.projection`), and the NumPy selection placing its values in the result +(`.out_selection`). + +Within one `Partition`, the frames divide: `Partition.view.transform` is a +different, global transform — it maps the part view directly into the raw +wrapped source — while only `Partition.projection.chunk_transform` uses +zero-origin chunk-local coordinates. Readers receive both so the global +source address and the local planning frame cannot be confused. + +| Projection field | What its output coordinates mean | +| --- | --- | +| `cell_transform` | Literal coordinates in the original request; its output rank is the request rank | +| `chunk_transform` | Zero-origin coordinates in the selected chunk's local frame; its output rank is the source rank | + +The cell domain enumerates corresponding cells; it is not itself either +output coordinate space. The canonical row selection has a one-dimensional +request and a two-dimensional source, so its paired projections have request +rank one and source rank two. + +### Order and duplicates need the request-side projection + +Orthogonal indexing (`.lazy.oindex`) applies each axis's indexer +independently, like `numpy.ix_` — an outer product; the +[pattern reference](patterns.md) develops the dialects. It can visit source +cells in an order that does not match chunk order, and it can visit one +source cell more than once. In the request below, row 4 comes first and +row 1 appears twice. + +```text +request position | 0 1 2 +source row | 4 1 1 +result row | row 4 row 1 row 1 +``` + +A source bounding box cannot reconstruct this result. The box spanning rows 1 +through 4 also includes unrequested rows 2 and 3, and its increasing coordinate +order does not record that row 4 comes first. Narrowing the read to just rows 1 +and 4 still does not record the second use of row 1. For the same reason, a +chunk-local selector alone says which cells to read inside a chunk but cannot +say which request positions receive them, especially when the chunks are +processed in a different order. + +The executable example assembles the 3-by-4 request from a 6-by-8 source with +3-by-4 chunks. Each `Partition` resolves its own sub-view — the global +transform addressing the raw source — and `out_selection` places those +values at their request-side positions; the paired projection stays +available on `part.projection` for consumers that read chunks directly. +The assertion checks the reordered, duplicated result against direct NumPy +indexing. + +```python +--8<-- "snippets/chunk_projection.py:advanced-projection" +``` + +The paired representation preserves information that a bounding box or local +selector discards: exact request order, duplicate destinations, and the +correspondence between every request position and its chunk-local source cell. + +--- + +
diff --git a/packages/zarr-indexing/docs/guide/integrations.md b/packages/zarr-indexing/docs/guide/integrations.md new file mode 100644 index 0000000000..03661ed43c --- /dev/null +++ b/packages/zarr-indexing/docs/guide/integrations.md @@ -0,0 +1,214 @@ +# Integration boundaries + +This package supplies indexing plans. It does **not** supply scheduling, +caching, codecs, or async orchestration. A consumer decides when projections +run, how decoded chunks are obtained, and where completed values are retained. +An `IndexTransform` says which source values belong in a result; a `Reader` +lowers that complete transform for one backend. The reader does not choose +indexing semantics or result ownership. + +## Zarr chunk dispatch + +A Zarr-oriented reader can consume each public `ChunkProjection` and use its +`chunk_coords` to obtain one decoded chunk from its own storage and codec +layers. This tiny source keeps four in-memory chunks keyed by their global +chunk coordinates and records the exact reads. For each projection, the +consumer enumerates the shared synthetic input cell domain, evaluates +`chunk_transform` to read zero-origin chunk-local coordinates, and evaluates +`cell_transform` to place each value at its literal request coordinate. + +```python +--8<-- "snippets/integrations.py:zarr-consumer" +``` + +The two reads are exactly `(0, 0)` and `(0, 1)`; untouched chunks `(1, 0)` and +`(1, 1)` are never read. The assembled request is `[4, 5, 6, 7]`. The +example intentionally begins with already decoded in-memory chunks: storage +keys, codecs, scheduling, caching, and asynchronous orchestration remain the +consumer's policy rather than responsibilities of the plan. + +## One slab read or many part reads + +A backend with its own native subset read — a Rust or C zarr implementation, +a database, an HTTP range endpoint — resolves a **dense box** (`is_box` with +every stride 1) best as a single read: hand it the whole selection and let it +dispatch to chunks, decode in parallel, and partial-decode shards on its own +side of the boundary. Splitting that read along this library's partitioning +only adds round-trips. Every **other** selection — a strided box, an `oindex` +or `vindex` gather — is where the partitioning earns its keep. The **cover** +of a read is the smallest step-1 slab enclosing every coordinate it needs; +partitioned, each part's cover is bounded by that part's box, so a sparse +selection can never force one read of its whole bounding hull (the smallest +rectangle containing every selected coordinate — a thousand rows for the two +of `oindex[[0, 999]]`). + +The composed view carries enough to make that call at materialization time, +and re-partitioning is a pure setter, so the policy is three lines: + +```python +--8<-- "snippets/integrations.py:dense-box-repartition" +``` + +The corner gather reads four single cells instead of the 10-by-10 hull, and +the dense box becomes exactly one backend call. Both regimes go through +`result()`; only the partitioning in force differs. + +### Sources that accept only unit-step slices + +The default `basic_reader` pushes strided and descending selections down as +positive-step slices, which reads the minimum but assumes the source accepts +any step. Many backends do not: FFI bindings and range requests often +support nothing but `slice(start, stop, 1)`. Select +[`unit_step_reader`][zarr_indexing.reader.UnitStepReader] for such a source +and every key it receives is an ascending unit-step slice per axis, with +strides, reversals, and gathers applied to the in-memory block instead: + +```python +view = LazyArray(source).with_reader(unit_step_reader) +``` + +A strided selection then over-reads its cover by the stride factor, which the +partitioning above bounds by one part. + +## napari-like consumer + +This is a **napari-like consumer**, not a napari integration. It models the +boundary a viewport could use without importing or claiming support for +napari. `RecordingArray` exposes a chunked, basic-indexing source — and its +`chunks` attribute is why the reads below split along `(2, 2)` boxes: +`LazyArray` discovers a partitioning from the wrapped array at construction +(`read_chunk_sizes`, then `chunks`), with `with_parts` as the explicit +override. Composing the +visible slice records no reads. Only `result()` materializes it, with the exact +source selectors `1:2, 0:2` and `1:2, 2:4`; neither selector crosses into an +untouched neighboring chunk. + +```python +--8<-- "snippets/integrations.py:viewport-consumer" +``` + +The viewport owns its interaction loop and any cancellation, caching, or +background execution. `LazyArray` contributes the composable selection and +the partition plan, then resolves only when the consumer asks for the result. + +### A system-memory chunk cache + +Napari accepts NumPy-like array objects and can defer materialization until an +image region is displayed. The indexing plan still deliberately owns no cache +or scheduler. A viewport adapter can place that policy around the plan, as the +executable reference below demonstrates. + +This remains a **napari-like consumer, not a napari integration**. It models +only decoded chunks resident in system memory, synchronously. + +For setup instructions and the complete executable, see the +[system-memory chunk cache example](../examples/system_memory_chunk_cache.md). + +```text + read succeeds +NEW -> QUEUED -> LOADING -------------> READY -> EVICTED + ^ | + | | read fails + | v + +--------- FAILED + retry + +EVICTED -> QUEUED + reload +``` + +The example keeps the lifecycle records and transitions explicit: + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-types" +``` + +Its source represents already decoded chunks and records each read: + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-source" +``` + +`LazyArray` converts a cache selection into transforms and partitions, then +allocates and assembles the result. The facade constructs exactly one tuple +from `view.parts()`: it derives the chunk coordinates to pin from that tuple, +then passes the same owned parts to `view.result(parts=parts)`. Planning is +therefore performed once for the request rather than repeated during +materialization. Neither pinning nor the result call rebuilds the plan; both +reuse those prepared `Partition` objects. + +`SystemMemoryChunkReader` receives one `ReadContext` for each materialized +part. Its global `context.transform` directly addresses the raw source, while +`context.projection.chunk_transform` addresses the already identified chunk +locally. The reader consumes that supplied projection directly; it never calls +the chunk planner. `LazyArray` retains responsibility for the projection's +result placement and final assembly. The reader owns only cache state and +source reads, while `SystemMemoryChunkCache` remains the thin NumPy-style facade +that prepares and pins the one plan: + +Its indexing dialects remain explicit: `cache[key]` accepts basic indexing +(integers, slices, ellipsis, and new axes), while `cache.oindex[key]` combines +per-axis index arrays as an outer product. Array keys are not silently treated +as orthogonal by plain square brackets; callers choose that behavior through +the named accessor. + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-wrapper" +``` + +### Follow one viewport through the cache + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-worked-example" +``` + +The worked example uses a 6-by-8 image, 3-by-4 chunks, and capacity for two +decoded chunks. Every read delta follows directly from the viewport request: + +| Step | Viewport | New reads | Resident afterward | Why | +| --- | --- | --- | --- | --- | +| 1 | `image[1:5, 2]` | `(0, 0)`, `(1, 0)` | `(0, 0)`, `(1, 0)` | Both projected chunks are loaded and assembled as `[10, 18, 26, 34]`. | +| 2 | `image[3:5, 2]` | None | `(0, 0)`, `(1, 0)` | The ready buffer for `(1, 0)` is reused and becomes most recently used. | +| 3 | `image[0:2, 5]` | `(0, 1)` | `(0, 1)`, `(1, 0)` | Placement returns `[5, 13]`, then LRU pressure evicts `(0, 0)`. | +| 4 | `image[1:5, 2]` | `(0, 0)` | `(0, 0)`, `(1, 0)` | The evicted chunk is reloaded while the required ready chunk is retained. | +| 5 | `image[3:5, 4:6]` | `(1, 1)` fails; no repeated read; `(1, 1)` succeeds after retry | `(0, 0)`, `(1, 1)` | Failure is retained until explicit retry; the repaired source then returns `[[28, 29], [36, 37]]`. | + +Chunks required by an active request are pinned through assembly, so a request +may temporarily span more chunks than the steady-state capacity. Capacity is +counted in decoded chunks—not records or bytes—and eviction occurs only after +all requested values have been placed. Because pinning and materialization use +the same prepared tuple, those lifecycle decisions cannot drift from the parts +that are actually read, and the cache never has to infer or reconstruct a +projection. + +The event log makes the failure boundary equally explicit: + +| Chunk | Transition | Reason | +| --- | --- | --- | +| `(1, 1)` | `NEW -> QUEUED` | requested | +| `(1, 1)` | `QUEUED -> LOADING` | queue drained | +| `(1, 1)` | `LOADING -> FAILED` | source read failed | +| `(1, 1)` | `FAILED -> QUEUED` | explicit retry | +| `(1, 1)` | `QUEUED -> LOADING` | queue drained | +| `(1, 1)` | `LOADING -> READY` | source read completed | + +A repeated request while the record is `FAILED` creates no event and performs +no source read. The retained failure forces the caller to choose when retry is +appropriate. A real viewport adapter could drain the queue in workers and +invalidate its canvas when chunks become ready without changing the selection +or projection semantics shown here. + +[Napari's image-layer documentation](https://napari.org/dev/howtos/layers/image.html) +describes its NumPy-like array boundary. Neuroglancer's +[`ChunkState`](https://github.com/google/neuroglancer/blob/master/src/chunk_manager/base.ts) +is conceptual prior art for making residency explicit. This example is a +smaller, independently authored, synchronous teaching model; it does not copy +that implementation or reproduce its full worker/GPU lifecycle. + +--- + + diff --git a/packages/zarr-indexing/docs/guide/patterns.md b/packages/zarr-indexing/docs/guide/patterns.md new file mode 100644 index 0000000000..9c3501da8a --- /dev/null +++ b/packages/zarr-indexing/docs/guide/patterns.md @@ -0,0 +1,327 @@ +# Indexing pattern reference + +Every NumPy indexing idiom is modeled by an `IndexTransform`: a domain (the +result's coordinates) and one output map per source dimension. This page +builds that model **by hand for each idiom**, so the anatomy is explicit — +which map kind an idiom needs, where the offset and stride go, and how an +index array's shape spells outer-product versus pointwise. Each model is +then proven equal to what the selection compiler derives, and its values +are checked against NumPy. + +## The idiom-to-model matrix + +Each idiom over a 6-by-8 `image`, shown two ways: the Python construction, +and the same transform in **wire form** — the [ndsel](../ndsel.md) +canonical body `to_json` produces. Both spell the whole +object: a domain whose extent is the result shape, then one output map per +source dimension. The index-array variables (`rows`, `columns`, +`mask_rows, mask_columns = np.nonzero(mask)`, and friends) are defined in +the executable matrix at the end of the page. + +**`image[1:5, ::2]`** — box. The offset picks where cell 0 reads; the +stride skips: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((4, 4)), + output=( + DimensionMap(input_dimension=0, offset=1), + DimensionMap(input_dimension=1, stride=2), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [4, 4], + "input_labels": ["", ""], + "output": [ + {"offset": 1, "stride": 1, "input_dimension": 0}, + {"offset": 0, "stride": 2, "input_dimension": 1} + ] + } + ``` + +**`image[2, :]`** — box. A rank-1 domain with two output maps: the dropped +axis survives as the wire's constant form, a bare `{"offset": 2}`: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((8,)), + output=(ConstantMap(2), DimensionMap(input_dimension=0)), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [8], + "input_labels": [""], + "output": [ + {"offset": 2}, + {"offset": 0, "stride": 1, "input_dimension": 0} + ] + } + ``` + +**`image[::-2, :]`** — box. Reversal is nothing but a negative stride, and +the offset is where cell 0 reads (row 5): + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3, 8)), + output=( + DimensionMap(input_dimension=0, offset=5, stride=-2), + DimensionMap(input_dimension=1), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 8], + "input_labels": ["", ""], + "output": [ + {"offset": 5, "stride": -2, "input_dimension": 0}, + {"offset": 0, "stride": 1, "input_dimension": 1} + ] + } + ``` + +**`image[2:2, :]`** — box. Emptiness lives in the domain +(`input_exclusive_max[0]` equals the minimum); the maps are ordinary: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((0, 8)), + output=( + DimensionMap(input_dimension=0, offset=2), + DimensionMap(input_dimension=1), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 8], + "input_labels": ["", ""], + "output": [ + {"offset": 2, "stride": 1, "input_dimension": 0}, + {"offset": 0, "stride": 1, "input_dimension": 1} + ] + } + ``` + +**`image[mask]`** — query. A mask is its nonzero coordinates: two +correlated index arrays over one flat axis, entry `i` of each pairing into +one cell: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ArrayMap(mask_rows), ArrayMap(mask_columns)), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [10], + "input_labels": [""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [0, 0, 1, 1, 2, 3, 3, 4, 5, 5], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [0, 5, 2, 7, 4, 1, 6, 3, 0, 5], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[np.ix_(rows, columns)]`** — query. The outer product is spelled by +nesting: `[[4], [1], [1]]` varies down the first axis, `[[2, 5]]` across +the second, each singleton along the other: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(rows.reshape(3, 1)), ArrayMap(columns.reshape(1, 2))), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 2], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [[4], [1], [1]], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [[2, 5]], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[vector_rows, vector_columns]`** — query. Pointwise: two flat +arrays over one shared axis: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(vector_rows), ArrayMap(vector_columns)), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [4, 1, 1], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [2, 5, 2], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[broadcast_rows, broadcast_columns]`** — query. NumPy broadcasting, +materialized: each map carries the full `(2, 3)` block: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap(np.broadcast_to(broadcast_rows, (2, 3))), + ArrayMap(np.broadcast_to(broadcast_columns, (2, 3))), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [2, 3], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [[0, 0, 0], [3, 3, 3]], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [[1, 4, 6], [1, 4, 6]], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[rows, 2:6]`** — query. One lookup table (order and repeats kept) +beside one ordinary affine map — one index array makes the whole selection +a query: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3, 4)), + output=( + ArrayMap(rows.reshape(3, 1)), + DimensionMap(input_dimension=1, offset=2), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 4], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [[4], [1], [1]], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 2, "stride": 1, "input_dimension": 1} + ] + } + ``` + +Two structural rules do all the work: + +- **Category**: `ConstantMap` and `DimensionMap` entries keep a selection a + box at any composition depth; one `ArrayMap` makes it a query permanently. + See the [design notes](../design-notes.md#bounding-box-selections-vs-query-selections) + for why consumers dispatch on this. +- **Fancy flavor is spelled by shape**: index arrays varying over distinct + axes (singleton elsewhere) form an outer product; arrays sharing their + non-singleton axes pair pointwise. + +## The executable matrix + +Each case hand-builds the model, checks shape, category, and NumPy values +(resolved through the public reader), then proves the selection compiler +derives the same transform. One wrinkle the last assert documents: compiled +*basic* selections keep literal domains (`t[1:5, ...]` starts at +coordinate 1 — see [Positions vs literal coordinates](#positions-vs-literal-coordinates)), +so they equal the zero-origin models after `translate_domain_to`: + +```python +--8<-- "snippets/indexing_patterns.py:indexing-patterns" +``` + +`LazyArray` adds nothing to these semantics: it is a regular array-like API +whose `.lazy`, `.lazy.oindex`, and `.lazy.vindex` accessors compile the same +dialects to the same transforms — the only difference is the return type, a +view instead of an array. The test suite holds the wrapper to this matrix. + +## Positions vs literal coordinates + +| Surface | Meaning of an integer index | Meaning of `-1` | +| --- | --- | --- | +| `IndexDomain` and `IndexTransform` | A literal coordinate in the current domain | The address `-1`, when the domain contains it | +| `LazyArray.lazy` | A NumPy-style position in the current view | The last position, normalized before transform composition | + +The wrapper's three indexing modes all use positions in the current view. Each +derived view begins at position zero, while the transform algebra underneath +retains literal coordinates. The +[Coordinates are addresses](index.md#coordinates-are-addresses) section develops +that distinction with non-zero and negative-origin domains. + +--- + + diff --git a/packages/zarr-indexing/docs/index.md b/packages/zarr-indexing/docs/index.md new file mode 100644 index 0000000000..1dd151d8ca --- /dev/null +++ b/packages/zarr-indexing/docs/index.md @@ -0,0 +1,53 @@ +# zarr-indexing + +This library is for modelling and transforming NumPy-style array indexing expressions. It separates +the *declaration* of an array indexing expression from the result of that expression. + +Developed for use in [`zarr`](https://zarr.readthedocs.io). + +Inspired by [TensorStore](https://google.github.io/tensorstore/), which pioneered +the approach used here. + + +## Install + +`zarr-indexing` is developed in the +[zarr-python repository](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing) +and released independently of `zarr` itself: + +``` +pip install zarr-indexing +``` + +## Quickstart + +Wrap an array, compose a lazy view through `.lazy`, and call `result()` when +you want its values: + +```python +--8<-- "snippets/canonical_slice.py:landing-quickstart" +``` + +Nothing is read until the `result()` call, however many selections are +composed. [Lazy views compose](guide/index.md#lazy-views-compose) shows how +the chain stays one description, and where the materialization boundary is. + +## Learn more + +- [Visual guide](guide/index.md) — one selection followed from coordinates to + chunk plan. Using lazy indexing, start at + [An index selects coordinates](guide/index.md#an-index-selects-coordinates); + integrating a chunked backend, start at + [A request becomes a chunk plan](guide/index.md#a-request-becomes-a-chunk-plan). +- [Indexing pattern reference](guide/patterns.md) — every selection form with + its NumPy-verified result. +- [Integration boundaries](guide/integrations.md) — what a reader, writer, or + scheduler owns, and what the plan owns. +- [Lazy indexing a NumPy array](examples/lazy_indexing_numpy.md) and + [with Dask](examples/lazy_indexing_dask.md) — runnable examples. +- [The ndsel wire format](ndsel.md) — the JSON form of a selection. +- [Design notes](design-notes.md) — TensorStore lineage, box vs query, and + deliberate limits. +- [API reference](api/index.md) +- [Changelog](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CHANGELOG.md) + · [License (MIT)](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/LICENSE.txt) diff --git a/packages/zarr-indexing/docs/ndsel.md b/packages/zarr-indexing/docs/ndsel.md new file mode 100644 index 0000000000..94971d49bf --- /dev/null +++ b/packages/zarr-indexing/docs/ndsel.md @@ -0,0 +1,159 @@ +--- +title: The ndsel wire format +--- + +# The ndsel wire format + +[ndsel](https://github.com/zarr-developers/ndsel) is a draft JSON +representation of NumPy-style n-dimensional selections, adapted from +TensorStore's `IndexTransform` model. This page documents the wire format, not +the coordinate model: [Coordinates are addresses](guide/index.md#coordinates-are-addresses) +introduces literal coordinates, and +[Lazy views compose](guide/index.md#lazy-views-compose) shows how views combine +before a transform is serialized. `zarr-indexing` implements ndsel in two layers: + +| Layer | Module | Depends on | Job | +| --- | --- | --- | --- | +| Message | [`zarr_indexing.messages`](api/messages.md) | stdlib only | JSON in, canonical JSON out. Validates and desugars. Never rounds, clamps, or drops information. | +| Engine | [`zarr_indexing.json`](api/json.md) | NumPy | Lowers a *canonical* body into an in-memory [`IndexTransform`](api/transform.md), and back. | + +Constraints that only make sense for a real array — finite bounds, index +arrays as `ndarray`s — live in the engine layer and nowhere else. As a result, +`messages` normalizes a message with `"-inf"` bounds that +`IndexTransform.from_json` refuses to lower. + +## Two entry points + +[`parse_ndsel`](api/messages.md#zarr_indexing.messages.parse_ndsel) +structurally validates a message of any kind and returns it unchanged. Use it +to confirm that a message is well formed while keeping it in its compact +shorthand form. + +[`normalize_ndsel`](api/messages.md#zarr_indexing.messages.normalize_ndsel) +desugars a message into the single deterministic **canonical transform body** +of the spec (section 4.3): a bare `IndexTransform` body without the `kind` +discriminator. + +```python +from zarr_indexing import normalize_ndsel + +normalize_ndsel({"kind": "box", "inclusive_min": [10, 5], "shape": [40, 1]}) +# {'input_rank': 2, +# 'input_inclusive_min': [10, 5], +# 'input_exclusive_max': [50, 6], +# 'input_labels': ['', ''], +# 'output': [{'offset': 0, 'stride': 1, 'input_dimension': 0}, +# {'offset': 0, 'stride': 1, 'input_dimension': 1}]} +``` + +Normalization is idempotent: re-tag the output with `kind: "transform"` and +normalizing it again returns the same body. Because the canonical body is +field-for-field a TensorStore `IndexTransform` minus `kind`, a normalized +message loads directly into `tensorstore.IndexTransform(json=...)`. + +Both entry points raise +[`NdselError`](api/messages.md#zarr_indexing.messages.NdselError), which +carries the spec `reason` code (`unknown_kind`, `rank_mismatch`, `step_zero`, +`output_map_conflict`, …) alongside a human-readable detail, so callers can +branch on the code rather than on message text. + +## The five message kinds + +Four are shorthands; the fifth is the canonical form itself. + +| `kind` | Fields | Selects | +| --- | --- | --- | +| `point` | `coords` | A single element. Normalizes to rank 0 with one `constant` output map per dimension. | +| `box` | `inclusive_min`, one of `exclusive_max` / `inclusive_max` / `shape`, `labels` | A rectangular region. Exactly one upper-bound spelling may appear. | +| `slice` | `start`, `stop`, `step`, `labels` | A strided region, one Python-style slice per dimension. | +| `points` | `coords` (a list of coordinate rows) | An explicit list of points — the `vindex` case. Normalizes to one `index_array` output map per dimension over a shared rank-1 input domain. | +| `transform` | `input_rank`, `input_inclusive_min`, one of the three `input_*` upper bounds, `input_labels`, `output` | The full canonical form. | + +Value rules the message layer enforces throughout: every integer is a 64-bit +signed value; JSON booleans are **not** integers (Python's +`isinstance(True, int)` is guarded against explicitly); the `"-inf"` / `"+inf"` +sentinels are legal only in bound positions; and an implicit bound is the +one-element `[n]`-bracket form, whose implicit/explicit flag survives +normalization intact. + +## Lowering to a transform + +The engine layer converts between canonical bodies and `IndexTransform`s: + +```python +from zarr_indexing import IndexTransform + +t = IndexTransform.from_json(canonical) +t.to_json() == canonical +``` + +`IndexDomain` carries the same pair for a bare domain body, and each output +map kind has a `to_json`; `output_index_map_from_json` dispatches the wire's +tagged union back to the right kind. + +Two engine constraints apply here and only here. A canonical body carrying a +`"-inf"` or `"+inf"` bound cannot be lowered — an `IndexDomain` addresses a +finite array — so `IndexTransform.from_json` raises. And implicit bounds lower +*by value*: the `[n]`-bracket flag is a message-layer concern, and the engine +keeps only the integer. + +### The `index_array` round trip + +ndsel and TensorStore both **reject** an output map that carries both +`input_dimension` and `index_array`. The in-memory +[`ArrayMap`](api/output_map.md#zarr_indexing.output_map.ArrayMap), though, +records an `input_dimension` to pin the axis an orthogonal (`oindex`) array +varies over. The serializer bridges that gap in both directions: + +- **On serialize**, a non-degenerate `index_array` map is emitted *without* + `input_dimension`. +- **On load**, the in-memory `input_dimension` is reconstructed from the + full-rank array's dependency axes — its non-singleton axes. An array that + solely owns a single non-singleton axis is orthogonal; arrays that share + non-singleton axes, or vary over several, are correlated (`vindex`), and get + `input_dimension = None`. A single 1-D array over a rank-1 domain is + inherently ambiguous between the two flavors and reconstructs as + orthogonal, which is behaviorally identical in that case. + +There is one deliberate exception, and it is the only place a round trip changes +representation rather than preserving it. An all-singleton `index_array` — size +1 — selects the same coordinate regardless of the input, so it is collapsed to +a `constant` map on serialize: + +```python +from zarr_indexing import IndexTransform + +IndexTransform.from_shape((100, 100)).oindex[[5], 0:2].to_json() +# {'input_rank': 2, +# 'input_inclusive_min': [0, 0], +# 'input_exclusive_max': [1, 2], +# 'input_labels': ['', ''], +# 'output': [{'offset': 5}, +# {'offset': 0, 'stride': 1, 'input_dimension': 1}]} +``` + +The size-1 input dimension stays in the domain, unconsumed by any output map. +The transform is still valid and the output shape is unchanged. A length-1 +`oindex` selection therefore round-trips behaviorally (an `ArrayMap` comes back +as a `ConstantMap`) rather than by object identity. + +## Conformance + +The package is checked against the language-agnostic ndsel conformance corpus, +vendored unmodified under +[`tests/conformance/`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing/tests/conformance) +— one JSON file per message kind plus `errors.json`, with the source commit +recorded in `PROVENANCE.md`. Each fixture is either a *success* case +(`input` + expected `normalized` body) or an *error* case (`input` + expected +reason code), and an implementation is conformant iff `normalize` reproduces +every one. `tests/test_conformance.py` runs the whole corpus as one +parametrized test per fixture, so a corpus update reports failures fixture by +fixture rather than as a single opaque assertion. + +Do not edit the vendored files; to pick up spec changes, re-vendor from a newer +ndsel commit and update the recorded SHA. + +A second, optional test (`tests/test_ndsel_tensorstore.py`, skipped unless +`tensorstore` is installed) checks against TensorStore itself by loading +canonical bodies into `tensorstore.IndexTransform` and re-loading TensorStore's +own `to_json()` output back through the engine layer. diff --git a/packages/zarr-indexing/docs/snippets/axis_manipulation.py b/packages/zarr-indexing/docs/snippets/axis_manipulation.py new file mode 100644 index 0000000000..1d1369fd87 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/axis_manipulation.py @@ -0,0 +1,29 @@ +"""Indexing defines result axes as well as selected source points.""" + +import numpy as np + +from zarr_indexing import LazyArray + +# --8<-- [start:axis-shape-comparison] +image = np.arange(12).reshape(3, 4) +lazy = LazyArray.from_numpy(image) + +integer_view = lazy.lazy[1, :] +slice_view = lazy.lazy[1:2, :] + +INTEGER_RESULT = integer_view.result() +SLICE_RESULT = slice_view.result() + +assert INTEGER_RESULT.tolist() == [4, 5, 6, 7] +assert INTEGER_RESULT.shape == (4,) +assert SLICE_RESULT.tolist() == [[4, 5, 6, 7]] +assert SLICE_RESULT.shape == (1, 4) +# --8<-- [end:axis-shape-comparison] + +# --8<-- [start:axis-insertion] +inserted_view = lazy.lazy[1, :, None] +INSERTED_RESULT = inserted_view.result() + +assert INSERTED_RESULT.tolist() == [[4], [5], [6], [7]] +assert INSERTED_RESULT.shape == (4, 1) +# --8<-- [end:axis-insertion] diff --git a/packages/zarr-indexing/docs/snippets/canonical_slice.py b/packages/zarr-indexing/docs/snippets/canonical_slice.py new file mode 100644 index 0000000000..fc4417f641 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/canonical_slice.py @@ -0,0 +1,30 @@ +"""The canonical basic-selection example used throughout the guide.""" + +import numpy as np + +from zarr_indexing import LazyArray + + +# --8<-- [start:landing-quickstart] +import numpy as np + +from zarr_indexing import LazyArray + +source = np.array([10, 11, 12, 13, 14, 15]) +view = LazyArray.from_numpy(source).lazy[2:5] + +view.result() +# array([12, 13, 14]) +# --8<-- [end:landing-quickstart] + +LANDING_QUICKSTART_RESULT = view.result() +assert LANDING_QUICKSTART_RESULT.tolist() == [12, 13, 14] + + +# --8<-- [start:canonical-slice] +source = np.array([10, 11, 12, 13, 14, 15]) +lazy = LazyArray.from_numpy(source) +view = lazy.lazy[2:5] + +assert view.result().tolist() == [12, 13, 14] +# --8<-- [end:canonical-slice] diff --git a/packages/zarr-indexing/docs/snippets/chunk_projection.py b/packages/zarr-indexing/docs/snippets/chunk_projection.py new file mode 100644 index 0000000000..5c56aafbbd --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/chunk_projection.py @@ -0,0 +1,57 @@ +"""Use public chunk projections without choosing a storage backend.""" + +import numpy as np +from numpy.typing import NDArray +from typing import cast + +from zarr_indexing import DimensionGridLike, IndexTransform, LazyArray, plan_chunks + + +# --8<-- [start:chunk-projection] +class RegularGrid: + """A small parameterized implementation of the public grid protocol.""" + + def __init__(self, size: int) -> None: + self.size = size + + def index_to_chunk(self, index: int) -> int: + return index // self.size + + def chunk_offset(self, chunk: int) -> int: + return chunk * self.size + + def chunk_size(self, chunk: int) -> int: + return self.size + + def indices_to_chunks(self, indices: NDArray[np.intp]) -> NDArray[np.intp]: + return np.floor_divide(indices, self.size).astype(np.intp) + + +transform = IndexTransform.from_shape((3, 4))[1, 0:4] +grids = cast( + tuple[DimensionGridLike, DimensionGridLike], + (RegularGrid(2), RegularGrid(2)), +) +plan = plan_chunks(transform, grids) +PROJECTIONS = tuple(plan) +assert tuple(projection.chunk_coords for projection in plan) == ((0, 0), (0, 1)) + +PAIRED_DOMAINS = tuple( + (projection.chunk_transform.domain, projection.cell_transform.domain) + for projection in PROJECTIONS +) +assert all(chunk_domain == cell_domain for chunk_domain, cell_domain in PAIRED_DOMAINS) +# --8<-- [end:chunk-projection] + + +# --8<-- [start:advanced-projection] +image = np.arange(48).reshape(6, 8) +advanced = LazyArray.from_numpy(image).with_parts((3, 4)).lazy.oindex[[4, 1, 1], 2:6] + +ADVANCED_EXPECTED = image[[4, 1, 1]][:, 2:6] +ADVANCED_RESULT = np.empty_like(ADVANCED_EXPECTED) +for part in advanced.parts(): + ADVANCED_RESULT[part.out_selection] = part.view.result() + +np.testing.assert_array_equal(ADVANCED_RESULT, ADVANCED_EXPECTED) +# --8<-- [end:advanced-projection] diff --git a/packages/zarr-indexing/docs/snippets/coordinate_origins.py b/packages/zarr-indexing/docs/snippets/coordinate_origins.py new file mode 100644 index 0000000000..724312e5e8 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/coordinate_origins.py @@ -0,0 +1,65 @@ +"""Literal coordinate domains and a grid that supports prepending.""" + +import numpy as np +from numpy.typing import NDArray +from typing import cast + +from zarr_indexing import ( + DimensionGridLike, + IndexDomain, + IndexTransform, + LazyArray, + plan_chunks, +) + + +# --8<-- [start:coordinate-origin] +domain = IndexDomain(inclusive_min=(-2,), exclusive_max=(3,)) +assert domain.contains((-1,)) +assert domain.narrow(-1).inclusive_min == (-1,) + +values = np.array([10, 20, 30, 40, 50]) +assert LazyArray.from_numpy(values).lazy[-1:].result().tolist() == [50] +# --8<-- [end:coordinate-origin] + + +# --8<-- [start:prepend-grid] +class PrependableGrid: + """A regular grid whose coordinates may extend below zero.""" + + def index_to_chunk(self, index: int) -> int: + return index // 3 + + def chunk_offset(self, chunk: int) -> int: + return chunk * 3 + + def chunk_size(self, chunk: int) -> int: + return 3 + + def indices_to_chunks(self, indices: NDArray[np.intp]) -> NDArray[np.intp]: + return np.floor_divide(indices, 3).astype(np.intp) + + +projection, = plan_chunks( + IndexTransform.identity(IndexDomain((-3,), (0,))), + cast(tuple[DimensionGridLike], (PrependableGrid(),)), +) +assert projection.chunk_coords == (-1,) +assert projection.chunk_domain == IndexDomain((-3,), (0,)) +assert projection.chunk_transform.domain == IndexDomain((0,), (3,)) + + +assert projection.chunk_transform.domain == projection.cell_transform.domain +PREPEND_SHARED_CELL_COORDS = ((0,), (1,), (2,)) +prepend_shared_cell_points = np.asarray(PREPEND_SHARED_CELL_COORDS, dtype=np.intp) +PREPEND_CHUNK_LOCAL_COORDS = tuple( + tuple(point) + for point in projection.chunk_transform.apply_many(prepend_shared_cell_points).tolist() +) +PREPEND_REQUEST_COORDS = tuple( + tuple(point) + for point in projection.cell_transform.apply_many(prepend_shared_cell_points).tolist() +) +assert PREPEND_CHUNK_LOCAL_COORDS == ((0,), (1,), (2,)) +assert PREPEND_REQUEST_COORDS == ((-3,), (-2,), (-1,)) +# --8<-- [end:prepend-grid] diff --git a/packages/zarr-indexing/docs/snippets/indexing_patterns.py b/packages/zarr-indexing/docs/snippets/indexing_patterns.py new file mode 100644 index 0000000000..86ec75e4bc --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/indexing_patterns.py @@ -0,0 +1,210 @@ +"""Every indexing idiom hand-built as an IndexTransform, proven against the compiler.""" + +from typing import Any, Literal, TypedDict + +import numpy as np + +from zarr_indexing import ( + ArrayMap, + ConstantMap, + DimensionMap, + IndexDomain, + IndexTransform, + ReadContext, + numpy_reader, +) + + +# --8<-- [start:indexing-patterns] +class PatternCase(TypedDict): + """One indexing idiom: its hand-built transform model and its NumPy result.""" + + name: str + mode: Literal["basic", "oindex", "vindex"] + selection: Any + transform: IndexTransform + expected: Any + shape: tuple[int, ...] + category: Literal["box", "query"] + + +image = np.arange(48).reshape(6, 8) +rows = np.array([4, 1, 1], dtype=np.intp) +columns = np.array([2, 5], dtype=np.intp) +mask = image % 5 == 0 +mask_rows, mask_columns = np.nonzero(mask) +vector_rows = np.array([4, 1, 1], dtype=np.intp) +vector_columns = np.array([2, 5, 2], dtype=np.intp) +broadcast_rows = np.array([[0], [3]], dtype=np.intp) +broadcast_columns = np.array([[1, 4, 6]], dtype=np.intp) + +PATTERN_CASES: tuple[PatternCase, ...] = ( + { + # image[1:5, ::2] — an offset picks where cell 0 reads; a stride skips. + "name": "basic-slice", + "mode": "basic", + "selection": (slice(1, 5), slice(None, None, 2)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((4, 4)), + output=( + DimensionMap(input_dimension=0, offset=1), + DimensionMap(input_dimension=1, stride=2), + ), + ), + "expected": image[1:5, ::2], + "shape": (4, 4), + "category": "box", + }, + { + # image[2, :] — the dropped axis survives as a ConstantMap: the result + # is rank 1, but there is still one output map per source dimension. + "name": "integer-axis-removal", + "mode": "basic", + "selection": (2, slice(None)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((8,)), + output=(ConstantMap(2), DimensionMap(input_dimension=0)), + ), + "expected": image[2, :], + "shape": (8,), + "category": "box", + }, + { + # image[::-2, :] — reversal is only a negative stride; the offset is + # where result cell 0 reads (the last selected row, 5). + "name": "negative-stride", + "mode": "basic", + "selection": (slice(None, None, -2), slice(None)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3, 8)), + output=( + DimensionMap(input_dimension=0, offset=5, stride=-2), + DimensionMap(input_dimension=1), + ), + ), + "expected": image[::-2, :], + "shape": (3, 8), + "category": "box", + }, + { + # image[2:2, :] — emptiness lives in the domain; the maps are ordinary. + "name": "empty-selection", + "mode": "basic", + "selection": (slice(2, 2), slice(None)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((0, 8)), + output=( + DimensionMap(input_dimension=0, offset=2), + DimensionMap(input_dimension=1), + ), + ), + "expected": image[2:2, :], + "shape": (0, 8), + "category": "box", + }, + { + # image[mask] — a mask is its nonzero coordinates: two correlated + # ArrayMaps over one flat result axis, row i paired with column i. + "name": "boolean-mask", + "mode": "vindex", + "selection": mask, + "transform": IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ArrayMap(mask_rows), ArrayMap(mask_columns)), + ), + "expected": image[mask], + "shape": (10,), + "category": "query", + }, + { + # image[np.ix_(rows, columns)] — the outer product is spelled by shape: + # each array varies over its own distinct axis, singleton on the other. + "name": "orthogonal", + "mode": "oindex", + "selection": (rows, columns), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(rows.reshape(3, 1)), ArrayMap(columns.reshape(1, 2))), + ), + "expected": image[np.ix_(rows, columns)], + "shape": (3, 2), + "category": "query", + }, + { + # image[vector_rows, vector_columns] — pointwise: both arrays share + # the same axis, so entry i of each pairs into one coordinate. + "name": "vectorized", + "mode": "vindex", + "selection": (vector_rows, vector_columns), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(vector_rows), ArrayMap(vector_columns)), + ), + "expected": image[vector_rows, vector_columns], + "shape": (3,), + "category": "query", + }, + { + # image[broadcast_rows, broadcast_columns] — NumPy broadcasting, + # materialized: each map carries the full (2, 3) broadcast block. + "name": "broadcasting", + "mode": "vindex", + "selection": (broadcast_rows, broadcast_columns), + "transform": IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap(np.broadcast_to(broadcast_rows, (2, 3))), + ArrayMap(np.broadcast_to(broadcast_columns, (2, 3))), + ), + ), + "expected": image[broadcast_rows, broadcast_columns], + "shape": (2, 3), + "category": "query", + }, + { + # image[rows, 2:6] — one lookup-table axis (repeats and order kept) + # beside one ordinary affine axis: one ArrayMap makes the whole + # selection a query. + "name": "repeated-out-of-order", + "mode": "oindex", + "selection": (rows, slice(2, 6)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3, 4)), + output=( + ArrayMap(rows.reshape(3, 1)), + DimensionMap(input_dimension=1, offset=2), + ), + ), + "expected": image[rows, 2:6], + "shape": (3, 4), + "category": "query", + }, +) + +base = IndexTransform.from_shape(image.shape) + + +def resolve(transform: IndexTransform) -> np.ndarray[Any, Any]: + """Materialize a transform against `image` through the public reader.""" + out = np.empty(transform.domain.shape, dtype=image.dtype) + numpy_reader.read_into(image, ReadContext(transform), out) + return out + + +for case in PATTERN_CASES: + transform = case["transform"] + + # The model is the idiom: shape, values, and category all follow from it. + assert transform.domain.shape == case["shape"] + np.testing.assert_array_equal(resolve(transform), case["expected"]) + is_query = any(isinstance(m, ArrayMap) for m in transform.output) + assert ("query" if is_query else "box") == case["category"] + + # The selection compiler derives the same transform. Compiled basic + # selections keep literal domains (t[1:5, ...] starts at 1, not 0); + # re-zeroing exposes the equality with the NumPy-shaped model. + compiled = base[case["selection"]] if case["mode"] == "basic" else ( + getattr(base, case["mode"])[case["selection"]] + ) + assert compiled.translate_domain_to((0,) * compiled.input_rank) == transform +# --8<-- [end:indexing-patterns] diff --git a/packages/zarr-indexing/docs/snippets/integrations.py b/packages/zarr-indexing/docs/snippets/integrations.py new file mode 100644 index 0000000000..5699c0d319 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/integrations.py @@ -0,0 +1,167 @@ +"""Boundaries for chunked-source and viewport consumers.""" + +from typing import Any + +import numpy as np + +from zarr_indexing import IndexDomain, LazyArray + + +# --8<-- [start:zarr-consumer] +class RecordingChunkSource: + """A decoded-chunk source keyed by public chunk coordinates.""" + + def __init__(self, chunks: dict[tuple[int, ...], np.ndarray[Any, Any]]) -> None: + self.chunks = chunks + self.reads: list[tuple[int, ...]] = [] + + def read(self, chunk_coords: tuple[int, ...]) -> np.ndarray[Any, Any]: + self.reads.append(chunk_coords) + return self.chunks[chunk_coords] + + +def _domain_points(domain: IndexDomain) -> np.ndarray[Any, np.dtype[np.intp]]: + """Enumerate a rectangular domain with a trailing coordinate axis.""" + if domain.ndim == 0: + return np.empty((1, 0), dtype=np.intp) + points = np.moveaxis(np.indices(domain.shape, dtype=np.intp), 0, -1).reshape( + -1, domain.ndim + ) + points += np.asarray(domain.inclusive_min, dtype=np.intp) + return points + + +def _gather_and_scatter( + destination: np.ndarray[Any, Any], + source: np.ndarray[Any, Any], + source_points: np.ndarray[Any, np.dtype[np.intp]], + destination_points: np.ndarray[Any, np.dtype[np.intp]], +) -> np.ndarray[Any, Any]: + """Gather and scatter a flattened point batch, including rank zero.""" + values = np.asarray(source[tuple(source_points.T)]).reshape(-1) + if destination_points.shape[-1] == 0: + destination[()] = values.reshape(destination.shape)[()] + else: + destination[tuple(destination_points.T)] = values + return values + + +zarr_image = np.arange(12).reshape(3, 4) +zarr_chunks = { + (chunk_row, chunk_column): zarr_image[ + chunk_row * 2 : (chunk_row + 1) * 2, + chunk_column * 2 : (chunk_column + 1) * 2, + ] + for chunk_row in range(2) + for chunk_column in range(2) +} +zarr_source = RecordingChunkSource(zarr_chunks) +zarr_view = LazyArray.from_numpy(zarr_image).with_parts((2, 2)).lazy[1, 0:4] +ZARR_RESULT = np.empty(zarr_view.shape, dtype=zarr_image.dtype) +shared_domains: list[tuple[IndexDomain, IndexDomain]] = [] +chunk_local_coords: list[tuple[tuple[int, ...], ...]] = [] +request_coords: list[tuple[tuple[int, ...], ...]] = [] +read_values: list[tuple[int, ...]] = [] + +for part in zarr_view.parts(): + projection = part.projection + assert projection.chunk_transform.domain == projection.cell_transform.domain + shared_domains.append( + (projection.chunk_transform.domain, projection.cell_transform.domain) + ) + domain = projection.chunk_transform.domain + cell_points = _domain_points(domain) + local_points_array = projection.chunk_transform.apply_many(cell_points) + result_points_array = projection.cell_transform.apply_many(cell_points) + chunk = zarr_source.read(projection.chunk_coords) + values_array = _gather_and_scatter( + ZARR_RESULT, chunk, local_points_array, result_points_array + ) + local_points = tuple(tuple(point) for point in local_points_array.tolist()) + result_points = tuple(tuple(point) for point in result_points_array.tolist()) + values = tuple(int(value) for value in values_array) + chunk_local_coords.append(local_points) + request_coords.append(result_points) + read_values.append(values) + +ZARR_SOURCE_KEYS = tuple(zarr_source.chunks) +ZARR_SOURCE_READS = tuple(zarr_source.reads) +ZARR_DISPATCHED_CHUNKS = ZARR_SOURCE_READS +ZARR_SHARED_DOMAINS = tuple(shared_domains) +ZARR_CHUNK_LOCAL_COORDS = tuple(chunk_local_coords) +ZARR_REQUEST_COORDS = tuple(request_coords) +ZARR_READ_VALUES = tuple(read_values) +assert ZARR_SOURCE_KEYS == ((0, 0), (0, 1), (1, 0), (1, 1)) +assert ZARR_SOURCE_READS == ((0, 0), (0, 1)) +assert ZARR_CHUNK_LOCAL_COORDS == (((1, 0), (1, 1)), ((1, 0), (1, 1))) +assert ZARR_REQUEST_COORDS == (((0,), (1,)), ((2,), (3,))) +assert ZARR_READ_VALUES == ((4, 5), (6, 7)) +assert ZARR_RESULT.tolist() == [4, 5, 6, 7] +# --8<-- [end:zarr-consumer] + + +# --8<-- [start:viewport-consumer] +class RecordingArray: + """An array-like source that records the basic reads it receives.""" + + def __init__(self, data: np.ndarray[Any, Any], chunks: tuple[int, ...]) -> None: + self._data = data + self.chunks = chunks + self.keys: list[tuple[slice, ...]] = [] + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self._data.dtype + + def __getitem__(self, key: tuple[slice, ...]) -> np.ndarray[Any, Any]: + self.keys.append(key) + return self._data[key] + + +viewport_source = RecordingArray(np.arange(12).reshape(3, 4), chunks=(2, 2)) +viewport = LazyArray(viewport_source).lazy[1, 0:4] +VIEWPORT_READS_BEFORE_RESULT = tuple(viewport_source.keys) +assert VIEWPORT_READS_BEFORE_RESULT == () +assert viewport.result().tolist() == [4, 5, 6, 7] + +VIEWPORT_SOURCE_KEYS = tuple(viewport_source.keys) +VIEWPORT_SOURCE_CHUNKS = tuple( + (key[0].start // 2, key[1].start // 2) for key in VIEWPORT_SOURCE_KEYS +) +assert VIEWPORT_SOURCE_KEYS == ( + (slice(1, 2, 1), slice(0, 2, 1)), + (slice(1, 2, 1), slice(2, 4, 1)), +) +assert VIEWPORT_SOURCE_CHUNKS == ((0, 0), (0, 1)) +# --8<-- [end:viewport-consumer] + + +# --8<-- [start:dense-box-repartition] +def materialize(view: LazyArray) -> Any: + """Read a dense box as one slab; resolve everything else per part.""" + strides = view.strides() + if view.is_box and strides is not None and all(s == 1 for s in strides): + view = view.with_parts(view.base_shape) + return view.result() + + +slab_source = RecordingArray(np.arange(100).reshape(10, 10), chunks=(4, 4)) +slab = LazyArray(slab_source) + +dense = slab.lazy[2:9, 1:8] # a dense box: every stride 1 +assert materialize(dense).shape == (7, 7) +assert len(slab_source.keys) == 1 # one slab read; the source dispatches + +slab_source.keys.clear() +gather = slab.lazy.oindex[[0, 9], [0, 9]] # a query: keep the chunk parts +assert materialize(gather).tolist() == [[0, 9], [90, 99]] +assert len(slab_source.keys) == 4 # four covers, each inside one chunk +assert all( + (key[0].stop - key[0].start) * (key[1].stop - key[1].start) == 1 + for key in slab_source.keys +) +# --8<-- [end:dense-box-repartition] diff --git a/packages/zarr-indexing/docs/snippets/lazy_composition.py b/packages/zarr-indexing/docs/snippets/lazy_composition.py new file mode 100644 index 0000000000..a4d9884b2b --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/lazy_composition.py @@ -0,0 +1,14 @@ +"""Composing views keeps indexing lazy until the final result call.""" + +import numpy as np + +from zarr_indexing import LazyArray + + +# --8<-- [start:lazy-composition] +source = np.array([10, 11, 12, 13, 14, 15]) +view = LazyArray.from_numpy(source).lazy[2:5] +composed = view.lazy[::-1].lazy[1:] + +assert composed.result().tolist() == source[2:5][::-1][1:].tolist() +# --8<-- [end:lazy-composition] diff --git a/packages/zarr-indexing/docs/snippets/output_maps.py b/packages/zarr-indexing/docs/snippets/output_maps.py new file mode 100644 index 0000000000..a78fc73b50 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/output_maps.py @@ -0,0 +1,67 @@ +"""The three output map kinds, each demonstrated against its NumPy counterpart.""" + +from typing import Any + +import numpy as np + +from zarr_indexing import ( + ArrayMap, + ConstantMap, + DimensionMap, + IndexDomain, + IndexTransform, + ReadContext, + numpy_reader, +) + +# --8<-- [start:resolve-helper] +source = np.array([10, 11, 12, 13, 14, 15]) + + +def resolve(transform: IndexTransform, values: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]: + """Materialize `transform` against `values` through the public reader.""" + out = np.empty(transform.domain.shape, dtype=values.dtype) + numpy_reader.read_into(values, ReadContext(transform), out) + return out +# --8<-- [end:resolve-helper] + + +# --8<-- [start:dimension-map] +# DimensionMap is an affine rule: request i reads source offset + stride * i. +# Its NumPy counterpart is a basic slice. +sliced = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=2, stride=1),), +) +assert resolve(sliced, source).tolist() == source[2:5].tolist() + +# A negative stride walks the source backward, like a negative-step slice. +reversed_view = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=4, stride=-2),), +) +assert resolve(reversed_view, source).tolist() == source[4::-2].tolist() +# --8<-- [end:dimension-map] + +# --8<-- [start:array-map] +# ArrayMap is an explicit list of source coordinates; order and duplicates +# are semantic. Its NumPy counterpart is fancy indexing. +gather = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=np.array([4, 1, 1])),), +) +assert resolve(gather, source).tolist() == source[[4, 1, 1]].tolist() +# --8<-- [end:array-map] + +# --8<-- [start:constant-map] +# ConstantMap reads one source coordinate for every request cell. No NumPy +# selection spells this operation: source[0] drops the axis, and a repeated +# fancy index source[[0, 0, 0, 0]] matches the values but degrades the +# description to a coordinate list. The value-faithful counterpart is a +# broadcast. +repeat = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ConstantMap(offset=0),), +) +assert resolve(repeat, source).tolist() == np.broadcast_to(source[0:1], (4,)).tolist() +# --8<-- [end:constant-map] diff --git a/packages/zarr-indexing/examples/lazy_indexing_dask/README.md b/packages/zarr-indexing/examples/lazy_indexing_dask/README.md new file mode 100644 index 0000000000..c9edb903ef --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_dask/README.md @@ -0,0 +1,55 @@ +# Lazy Indexing with Dask + +This example demonstrates how to use `zarr_indexing.LazyArray` with Dask, both as +an array Dask can wrap and as a source of independent tasks, and compares the two +ways of deferring an indexing operation. + +The example shows how to: + +- Pass a `LazyArray` — over a Zarr array or over a view of one — to + `dask.array.from_array` +- Build one Dask task per partition from `parts()`, compute them in parallel, and + place each result with the partition's `out_selection` +- Read `is_complete` to tell which partitions cover a stored chunk completely +- Rely on `__dask_tokenize__`, so that equal selections produce equal tokens and + Dask can cache and deduplicate the work +- Measure what a task graph costs for indexing-only work, against composing the + same selections into one transform + +A `LazyArray` exposes no `chunks` attribute, so `dask.array.from_array` chooses +its own block size unless one is given. The partitioning that `parts()` reports +is discovered from the wrapped array and is independent of Dask's blocks. + +## Choosing Between Them + +If Dask is doing arithmetic across chunks, reductions, rechunking, or distributed +execution, it is the right tool, and its task graph is what makes that work. + +If Dask is used *only* to defer indexing — take a view now, read it later, with +no computation in between — then the graph is overhead. Dask slices the chunk +grid on every indexing operation and records another layer, so composing +selections costs time proportional to both the depth of the chain and the number +of chunks in the array, and reading walks what was accumulated. `LazyArray` +composes each selection into the single transform it already holds, so composing +is independent of the depth of the chain, and reading enumerates only the +partitions the selection touches. The last test in this example prints both, and +the gap widens with the number of chunks and the number of selections. + +## Running the Example + +The script declares its dependencies inline +([PEP 723](https://peps.python.org/pep-0723/)), so the easiest way to run it is +with [uv](https://docs.astral.sh/uv/), which installs them automatically: + +```bash +cd packages/zarr-indexing +uv run --with-editable . examples/lazy_indexing_dask/lazy_indexing_dask.py +``` + +Alternatively, run it with plain Python, in which case you must first install +`zarr`, `zarr-indexing`, `dask[array]`, `numpy`, and `pytest` yourself: + +```bash +cd packages/zarr-indexing +python examples/lazy_indexing_dask/lazy_indexing_dask.py +``` diff --git a/packages/zarr-indexing/examples/lazy_indexing_dask/lazy_indexing_dask.py b/packages/zarr-indexing/examples/lazy_indexing_dask/lazy_indexing_dask.py new file mode 100644 index 0000000000..d6ed43f322 --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_dask/lazy_indexing_dask.py @@ -0,0 +1,181 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", +# "zarr-indexing>=0.1", +# "dask[array]==2025.3.0", +# "numpy==2.4.3", +# "pytest==9.0.2" +# ] +# /// +# + +""" +Demonstrate using zarr_indexing.LazyArray with Dask +""" + +import sys +import time + +import dask +import dask.array as da +import numpy as np +import pytest +import zarr +from dask.base import tokenize + +from zarr_indexing import LazyArray + + +@pytest.fixture +def source() -> zarr.Array: + """A chunked Zarr array to wrap.""" + array = zarr.create_array(store={}, shape=(40, 30), chunks=(10, 10), dtype="i4") + array[:] = np.arange(40 * 30).reshape(40, 30) + return array + + +def test_from_array(source: zarr.Array) -> None: + """Hand a LazyArray to `dask.array.from_array`.""" + lazy = LazyArray(source) + + # `from_array` needs `shape`, `dtype`, and `__getitem__`, which the wrapper + # provides. Each Dask block reads its own region through the wrapper. + array = da.from_array(lazy, chunks=(10, 10)) + print(array) + assert np.array_equal(array.compute(scheduler="threads"), source[:]) + + # A view works the same way, and its shape is the shape of the selection. + view = LazyArray(source).lazy[5:35, 3:27] + array = da.from_array(view, chunks=(10, 10)) + assert array.shape == (30, 24) + assert np.array_equal(array.compute(scheduler="threads"), source[5:35, 3:27]) + + +def test_parts_as_tasks(source: zarr.Array) -> None: + """Build one task per partition and compute them in parallel.""" + view = LazyArray(source).lazy[5:35, 3:27] + + # The partitioning is discovered from the wrapped array's chunks, so each + # partition of the view lies within one stored chunk. + parts = list(view.parts()) + print(f"{len(parts)} parts for a {view.shape} view of a {source.shape} array") + + # A partition carries a sub-view to resolve and where its result belongs, so + # the reads are independent and the placement needs no coordination. + @dask.delayed + def read(part: object) -> np.ndarray: + return part.view.result() + + blocks = dask.compute(*[read(part) for part in parts], scheduler="threads") + + result = np.empty(view.shape, dtype=view.dtype) + for part, block in zip(parts, blocks, strict=True): + result[part.out_selection] = block + assert np.array_equal(result, source[5:35, 3:27]) + + # `is_complete` reports whether a partition covers its whole partition of + # the base array, which a writer uses to choose between overwriting a chunk + # and reading it first. + complete = [part.box for part in parts if part.is_complete] + print(f"{len(complete)} of {len(parts)} parts cover their chunk completely") + + +def test_tokenize(source: zarr.Array) -> None: + """Deterministic tokens let Dask cache and deduplicate work.""" + lazy = LazyArray(source) + + # Two wrappers over the same array and the same selection are the same task + # to Dask, whether or not they are the same Python object. + assert tokenize(lazy) == tokenize(LazyArray(source)) + assert tokenize(lazy.lazy[0:10]) == tokenize(LazyArray(source).lazy[0:10]) + + # Different selections are different tasks. + assert tokenize(lazy.lazy[0:10]) != tokenize(lazy.lazy[10:20]) + + # Selections that describe the same region are the same task, however they + # were composed. + assert tokenize(lazy.lazy[0:20].lazy[5:10]) == tokenize(lazy.lazy[5:10]) + + +def test_indexing_only_workload() -> None: + """Compare an accumulating task graph with a fused transform. + + Dask records each indexing operation as another graph layer, and slices the + chunk grid to build it, so composing selections costs time proportional to + the number of selections and the number of chunks. `LazyArray` composes each + selection into the single transform it already holds, so the cost of + composing does not grow with the depth of the chain, and reading resolves + that one transform rather than walking a graph. + + Timings are printed rather than asserted, since they depend on the machine. + """ + data = np.zeros((2000, 4), dtype="i4") # 2000 chunks, one row each + + def dask_chain(depth: int) -> da.Array: + array = da.from_array(data, chunks=(1, 4)) + for _ in range(depth): + array = array[1:] + return array + + def lazy_chain(depth: int) -> LazyArray: + view = LazyArray.from_numpy(data) + for _ in range(depth): + view = view.lazy[1:] + return view + + # Read once through each path first, so the timings below exclude the cost + # of importing and initializing the machinery. + dask_chain(1)[:2].compute(scheduler="synchronous") + lazy_chain(1).lazy[:2].result() + + header = ( + f"{'selections':>10} {'dask compose':>13} {'dask read':>10} {'layers':>7}" + f" {'LazyArray compose':>18} {'LazyArray read':>15}" + ) + print(header) + for depth in (1, 5, 20): + start = time.perf_counter() + chained = dask_chain(depth) + dask_compose = time.perf_counter() - start + + start = time.perf_counter() + from_dask = chained[:2].compute(scheduler="synchronous") + dask_read = time.perf_counter() - start + + start = time.perf_counter() + view = lazy_chain(depth) + lazy_compose = time.perf_counter() - start + + start = time.perf_counter() + from_lazy = view.lazy[:2].result() + lazy_read = time.perf_counter() - start + + # Both paths describe the same selection, so they read the same data. + assert np.array_equal(from_dask, from_lazy) + + layers = len(chained.__dask_graph__().layers) + print( + f"{depth:>10} {dask_compose * 1e3:>12.2f}ms {dask_read * 1e3:>9.2f}ms {layers:>7}" + f" {lazy_compose * 1e3:>17.3f}ms {lazy_read * 1e3:>14.3f}ms" + ) + + +if __name__ == "__main__": + # Run the example with printed output, and a dummy pytest configuration file specified. + # Without the dummy configuration file, at test time pytest will attempt to use the + # configuration file in the project root, which will error because Zarr is using some + # plugins that are not installed in this example. + sys.exit( + pytest.main( + [ + "-s", + __file__, + f"-c {__file__}", + # Suppress: "PytestAssertRewriteWarning: Module already imported so + # cannot be rewritten; zarr" + "-W", + "ignore::pytest.PytestAssertRewriteWarning", + ] + ) + ) diff --git a/packages/zarr-indexing/examples/lazy_indexing_numpy/README.md b/packages/zarr-indexing/examples/lazy_indexing_numpy/README.md new file mode 100644 index 0000000000..e76e065047 --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_numpy/README.md @@ -0,0 +1,38 @@ +# Lazy Indexing a NumPy Array + +This example demonstrates how to wrap an array in `zarr_indexing.LazyArray` and +index it without reading data. + +The example shows how to: + +- Wrap a NumPy array and read the forwarded `shape`, `dtype`, and `ndim` +- Compose selections through `.lazy[...]`, `.lazy.oindex[...]`, and + `.lazy.vindex[...]`, and materialize the composed view once with `result()` +- Tell a box selection (slices and integers, described by an interval and a step + per dimension) from a query selection (points gathered through an index array) + using `is_box`, `bounding_box()`, and `strides()` +- Declare a partitioning with `with_parts()`, iterate it with `parts()`, and + assemble a result from the partitions + +`LazyArray` wraps any object exposing `shape`, `dtype`, and `__getitem__`, so the +same API applies to a Zarr array, and the partitioning is then discovered from +the array's chunks. The Dask example covers that case. + +## Running the Example + +The script declares its dependencies inline +([PEP 723](https://peps.python.org/pep-0723/)), so the easiest way to run it is +with [uv](https://docs.astral.sh/uv/), which installs them automatically: + +```bash +cd packages/zarr-indexing +uv run --with-editable . examples/lazy_indexing_numpy/lazy_indexing_numpy.py +``` + +Alternatively, run it with plain Python, in which case you must first install +`zarr-indexing`, `numpy`, and `pytest` yourself: + +```bash +cd packages/zarr-indexing +python examples/lazy_indexing_numpy/lazy_indexing_numpy.py +``` diff --git a/packages/zarr-indexing/examples/lazy_indexing_numpy/lazy_indexing_numpy.py b/packages/zarr-indexing/examples/lazy_indexing_numpy/lazy_indexing_numpy.py new file mode 100644 index 0000000000..ae29a7fc51 --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_numpy/lazy_indexing_numpy.py @@ -0,0 +1,133 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr-indexing>=0.1", +# "numpy==2.4.3", +# "pytest==9.0.2" +# ] +# /// +# + +""" +Demonstrate lazy indexing over a plain NumPy array with zarr_indexing.LazyArray +""" + +import sys + +import numpy as np +import pytest + +from zarr_indexing import LazyArray + + +def test_wrap_and_compose() -> None: + """Wrap an array, compose selections without reading, then materialize once.""" + data = np.arange(12 * 8).reshape(12, 8) + lazy = LazyArray.from_numpy(data) + + # The wrapper forwards the attributes an array consumer expects. + assert lazy.shape == (12, 8) + assert lazy.dtype == data.dtype + assert lazy.ndim == 2 + + # `.lazy[...]` returns another LazyArray. No element of `data` is read. + view = lazy.lazy[2:10, ::2] + print(view) + assert view.shape == (8, 4) + + # Selections compose. Each step narrows the view; still nothing is read. + smaller = view.lazy[1:5, 1:3] + + # `result()` performs the read. NumPy is the reference for the whole chain. + assert np.array_equal(smaller.result(), data[2:10, ::2][1:5, 1:3]) + + # Selections use positional NumPy semantics: indices count from zero within + # the current view, and negative indices count from the end. + assert np.array_equal(lazy.lazy[-1].result(), data[-1]) + assert np.array_equal(lazy.lazy[::-1].result(), data[::-1]) + + # Orthogonal and vectorized indexing are available under the same accessor. + rows = np.array([9, 1, 4]) + assert np.array_equal(lazy.lazy.oindex[rows, :].result(), data[rows, :]) + cols = np.array([0, 3, 7]) + assert np.array_equal(lazy.lazy.vindex[rows, cols].result(), data[rows, cols]) + + # A LazyArray is also an ordinary duck array: __getitem__ reads immediately, + # and np.asarray materializes the view. + assert np.array_equal(lazy[2:4, 0], data[2:4, 0]) + assert np.array_equal(np.asarray(view), data[2:10, ::2]) + + +def test_box_and_query_selections() -> None: + """Distinguish selections that describe a region from selections that gather points.""" + data = np.arange(12 * 8).reshape(12, 8) + lazy = LazyArray.from_numpy(data) + + # A box selection is built from slices and integers alone. It is described + # completely by an interval and a step per dimension, so a consumer can + # serve it as one strided read. + box = lazy.lazy[2:10, ::2] + print(f"box: is_box={box.is_box} bounding_box={box.bounding_box()} strides={box.strides()}") + assert box.is_box + assert box.bounding_box() == ((2, 10), (0, 7)) + assert box.strides() == (1, 2) + + # A query selection gathers points through an index array. Its coordinates + # are a lookup table, so `strides()` is undefined and `bounding_box()` is + # the hull of the points rather than an exact description. + query = lazy.lazy.oindex[np.array([9, 1, 4]), :] + print(f"query: is_box={query.is_box} bounding_box={query.bounding_box()}") + assert not query.is_box + assert query.strides() is None + assert query.bounding_box() == ((1, 10), (0, 8)) + + # Composing a box onto a query keeps it a query. + assert not query.lazy[0:2, 0:2].is_box + + +def test_parts() -> None: + """Iterate the partitions a view covers, and assemble the result from them.""" + data = np.arange(12 * 8).reshape(12, 8) + + # A plain NumPy array declares no partitioning, so `with_parts` states one. + # Partitioning changes the granularity of reads, never the result. + lazy = LazyArray.from_numpy(data).with_parts((4, 4)) + view = lazy.lazy[2:10, ::2] + + parts = list(view.parts()) + print(f"{len(parts)} parts") + for part in parts[:2]: + print(f" base_coords={part.base_coords} box={part.box} complete={part.is_complete}") + + # Each part carries a sub-view of its own, where that sub-view lands in the + # result, and whether it covers its partition completely. Resolving the + # parts and placing them is what `result()` does. + assembled = np.empty(view.shape, dtype=view.dtype) + for part in parts: + assembled[part.out_selection] = part.view.result() + assert np.array_equal(assembled, view.result()) + + # The partitioning is a read strategy, so a different one gives the same data. + assert np.array_equal( + LazyArray.from_numpy(data).with_parts((5, 3)).lazy[2:10, ::2].result(), assembled + ) + + +if __name__ == "__main__": + # Run the example with printed output, and a dummy pytest configuration file specified. + # Without the dummy configuration file, at test time pytest will attempt to use the + # configuration file in the project root, which will error because Zarr is using some + # plugins that are not installed in this example. + sys.exit( + pytest.main( + [ + "-s", + __file__, + f"-c {__file__}", + # Suppress: "PytestAssertRewriteWarning: Module already imported so + # cannot be rewritten; zarr" + "-W", + "ignore::pytest.PytestAssertRewriteWarning", + ] + ) + ) diff --git a/packages/zarr-indexing/examples/system_memory_chunk_cache/README.md b/packages/zarr-indexing/examples/system_memory_chunk_cache/README.md new file mode 100644 index 0000000000..d6271f9401 --- /dev/null +++ b/packages/zarr-indexing/examples/system_memory_chunk_cache/README.md @@ -0,0 +1,46 @@ +# System-memory chunk cache + +This executable reference architecture demonstrates a small, synchronous +system-memory chunk cache for a NumPy-like image consumer. It is inspired by +Neuroglancer's explicit chunk lifecycle: + +```text +NEW -> QUEUED -> LOADING -> READY + | + v + FAILED + +READY -> EVICTED +FAILED -> QUEUED (explicit retry) +``` + +`RecordingChunkSource` owns decoded source-chunk reads and records them for the +example. `LazyArray` converts NumPy-style indexing into transforms and +partitions, then assembles the final result. `SystemMemoryChunkReader` +intercepts each materialized part and owns the lifecycle records, queue +draining, resident ready buffers, LRU eviction, retained load failures, and +explicit retry. The reader owns cache state and source reads, but not result +shape or assembly. + +Each request calls `view.parts()` once and keeps the resulting tuple. The cache +pins the tuple's chunk coordinates, then materializes with +`view.result(parts=parts)`, so scheduling and assembly reuse one plan. Every +reader call consumes the exact projection attached to its `ReadContext`; the +reader does not invoke the chunk planner again. + +The requests demonstrate lazy selections, paired chunk projections, overlapping +viewport requests that reuse resident chunks, eviction under capacity pressure, +a retained failure that does not retry implicitly, and an explicit retry after +the source is repaired. The integration guide contains the detailed request +table. + +This is synchronous system-memory reference architecture, not a +production-ready cache, scheduler, renderer, or complete napari integration. +Its types are intentionally not exported by `zarr_indexing`. + +## Running the example + +```bash +cd packages/zarr-indexing +uv run --with-editable . examples/system_memory_chunk_cache/system_memory_chunk_cache.py +``` diff --git a/packages/zarr-indexing/examples/system_memory_chunk_cache/system_memory_chunk_cache.py b/packages/zarr-indexing/examples/system_memory_chunk_cache/system_memory_chunk_cache.py new file mode 100644 index 0000000000..1645d89b2c --- /dev/null +++ b/packages/zarr-indexing/examples/system_memory_chunk_cache/system_memory_chunk_cache.py @@ -0,0 +1,432 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr-indexing>=0.1", +# "numpy==2.4.3", +# ] +# /// +# +from __future__ import annotations + +from contextlib import contextmanager +from dataclasses import dataclass +from enum import StrEnum +from typing import TYPE_CHECKING, Any + +import numpy as np + +from zarr_indexing import ( + IndexDomain, + LazyArray, + ReadContext, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + +type ChunkCoords = tuple[int, ...] + + +# --8<-- [start:chunk-cache-types] +class ChunkState(StrEnum): + NEW = "new" + QUEUED = "queued" + LOADING = "loading" + READY = "ready" + FAILED = "failed" + EVICTED = "evicted" + + +@dataclass(slots=True) +class ChunkRecord: + state: ChunkState = ChunkState.NEW + buffer: np.ndarray[Any, Any] | None = None + error: Exception | None = None + last_access: int = -1 + + +@dataclass(frozen=True, slots=True) +class ChunkEvent: + chunk_coords: ChunkCoords + previous: ChunkState + current: ChunkState + reason: str + + +class ChunkLoadError(RuntimeError): + pass + + +# --8<-- [end:chunk-cache-types] + + +# --8<-- [start:chunk-cache-source] +class RecordingChunkSource: + def __init__(self, data: np.ndarray[Any, Any], chunks: tuple[int, ...]) -> None: + self._data = data + self.chunks = chunks + self.reads: list[ChunkCoords] = [] + self.failures: set[ChunkCoords] = set() + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self._data.dtype + + def __getitem__(self, key: Any) -> np.ndarray[Any, Any]: + raise AssertionError("the cache must read complete chunks through read_chunk") + + def read_chunk(self, chunk_coords: ChunkCoords) -> np.ndarray[Any, Any]: + self.reads.append(chunk_coords) + if chunk_coords in self.failures: + raise OSError(f"source read failed for chunk {chunk_coords}") + key = tuple( + slice(coord * size, min((coord + 1) * size, extent)) + for coord, size, extent in zip(chunk_coords, self.chunks, self.shape, strict=True) + ) + return self._data[key].copy() + + +def _domain_points(domain: IndexDomain) -> np.ndarray[Any, np.dtype[np.intp]]: + """Enumerate a rectangular domain with a trailing coordinate axis.""" + if domain.ndim == 0: + return np.empty((1, 0), dtype=np.intp) + points = np.moveaxis(np.indices(domain.shape, dtype=np.intp), 0, -1).reshape(-1, domain.ndim) + points += np.asarray(domain.inclusive_min, dtype=np.intp) + return points + + +def _gather_and_scatter( + destination: np.ndarray[Any, Any], + source: np.ndarray[Any, Any], + source_points: np.ndarray[Any, np.dtype[np.intp]], + destination_points: np.ndarray[Any, np.dtype[np.intp]], +) -> np.ndarray[Any, Any]: + """Gather and scatter a flattened point batch, including rank zero.""" + values = np.asarray(source[tuple(source_points.T)]).reshape(-1) + if destination_points.shape[-1] == 0: + destination[()] = values.reshape(destination.shape)[()] + else: + destination[tuple(destination_points.T)] = values + return values + + +# --8<-- [end:chunk-cache-source] + + +# --8<-- [start:chunk-cache-wrapper] +LEGAL_TRANSITIONS: dict[ChunkState, frozenset[ChunkState]] = { + ChunkState.NEW: frozenset({ChunkState.QUEUED}), + ChunkState.QUEUED: frozenset({ChunkState.LOADING}), + ChunkState.LOADING: frozenset({ChunkState.READY, ChunkState.FAILED}), + ChunkState.READY: frozenset({ChunkState.EVICTED}), + ChunkState.FAILED: frozenset({ChunkState.QUEUED}), + ChunkState.EVICTED: frozenset({ChunkState.QUEUED}), +} + + +class _OrthogonalIndexer: + """Expose outer-product indexing without changing ``cache[key]`` semantics.""" + + def __init__(self, getitem: Callable[[Any], np.ndarray[Any, Any]]) -> None: + self._getitem = getitem + + def __getitem__(self, key: Any) -> np.ndarray[Any, Any]: + return self._getitem(key) + + +class SystemMemoryChunkReader: + def __init__(self, *, capacity: int) -> None: + self.capacity = capacity + self._records: dict[ChunkCoords, ChunkRecord] = {} + self._queue: list[ChunkCoords] = [] + self._clock = 0 + self._requests = 0 + self.events: list[ChunkEvent] = [] + self.projection_uses: list[tuple[str, str]] = [] + + def state(self, chunk_coords: ChunkCoords) -> ChunkState: + return self._record(chunk_coords).state + + def resident(self) -> tuple[ChunkCoords, ...]: + return tuple( + sorted( + coords + for coords, record in self._records.items() + if record.state is ChunkState.READY + ) + ) + + def _record(self, chunk_coords: ChunkCoords) -> ChunkRecord: + return self._records.setdefault(chunk_coords, ChunkRecord()) + + def _transition(self, chunk_coords: ChunkCoords, current: ChunkState, reason: str) -> None: + record = self._record(chunk_coords) + if current not in LEGAL_TRANSITIONS[record.state]: + raise ValueError(f"illegal chunk transition {record.state} -> {current}") + previous = record.state + record.state = current + self.events.append(ChunkEvent(chunk_coords, previous, current, reason)) + + def retry(self, chunk_coords: ChunkCoords) -> None: + record = self._record(chunk_coords) + if record.state is not ChunkState.FAILED: + raise ValueError(f"retry requires failed chunk {chunk_coords}, got {record.state}") + record.error = None + self._transition(chunk_coords, ChunkState.QUEUED, "explicit retry") + self._queue.append(chunk_coords) + + @contextmanager + def request(self, required: tuple[ChunkCoords, ...]) -> Iterator[None]: + """Prepare every part and defer eviction until one request completes.""" + self._prepare(required) + self._requests += 1 + try: + yield + except Exception: + self._requests -= 1 + raise + else: + self._requests -= 1 + if self._requests == 0: + self._evict(pinned=frozenset()) + + def _touch(self, record: ChunkRecord) -> None: + self._clock += 1 + record.last_access = self._clock + + def _queue_once(self, chunk_coords: ChunkCoords) -> None: + record = self._record(chunk_coords) + if record.state in {ChunkState.QUEUED, ChunkState.LOADING, ChunkState.READY}: + return + if record.state is ChunkState.FAILED: + raise ValueError(f"failed chunk {chunk_coords} requires explicit retry") + self._transition(chunk_coords, ChunkState.QUEUED, "requested") + self._queue.append(chunk_coords) + + def _prepare(self, required: tuple[ChunkCoords, ...]) -> None: + for chunk_coords in required: + record = self._record(chunk_coords) + if record.state is ChunkState.FAILED: + assert record.error is not None + raise ChunkLoadError( + f"chunk {chunk_coords} is failed; call retry first" + ) from record.error + + for chunk_coords in required: + record = self._record(chunk_coords) + if record.state is ChunkState.READY: + self._touch(record) + else: + self._queue_once(chunk_coords) + + def _ensure_ready( + self, + source: RecordingChunkSource, + required: tuple[ChunkCoords, ...], + ) -> None: + if self._requests == 0: + self._prepare(required) + self._drain(source, frozenset(required)) + + def _drain(self, source: RecordingChunkSource, required: frozenset[ChunkCoords]) -> None: + pending = self._queue + self._queue = [] + for index, chunk_coords in enumerate(pending): + if chunk_coords not in required: + self._queue.append(chunk_coords) + continue + record = self._record(chunk_coords) + self._transition(chunk_coords, ChunkState.LOADING, "queue drained") + try: + record.buffer = source.read_chunk(chunk_coords) + except OSError as error: + record.buffer = None + record.error = error + self._transition(chunk_coords, ChunkState.FAILED, "source read failed") + self._queue.extend(pending[index + 1 :]) + raise ChunkLoadError(f"could not load chunk {chunk_coords}") from error + record.error = None + self._transition(chunk_coords, ChunkState.READY, "source read completed") + self._touch(record) + + def _evict(self, *, pinned: frozenset[ChunkCoords]) -> None: + while len(self.resident()) > self.capacity: + candidates = ( + (record.last_access, chunk_coords) + for chunk_coords, record in self._records.items() + if record.state is ChunkState.READY and chunk_coords not in pinned + ) + _, chunk_coords = min(candidates) + record = self._record(chunk_coords) + record.buffer = None + self._transition(chunk_coords, ChunkState.EVICTED, "LRU capacity") + + def read_into( + self, + source: RecordingChunkSource, + context: ReadContext, + out: np.ndarray[Any, Any], + /, + ) -> None: + projection = context.projection + if projection is None: + raise ValueError("SystemMemoryChunkReader requires context.projection") + required = (projection.chunk_coords,) + self._ensure_ready(source, required) + record = self._record(projection.chunk_coords) + assert record.buffer is not None + cell_points = _domain_points(projection.chunk_transform.domain) + chunk_points = projection.chunk_transform.apply_many(cell_points) + destination_points = _domain_points(context.transform.domain) + _gather_and_scatter(out, record.buffer, chunk_points, destination_points) + self.projection_uses.append(("chunk_transform", "context.transform")) + if self._requests == 0: + self._evict(pinned=frozenset()) + + +class SystemMemoryChunkCache: + def __init__(self, source: RecordingChunkSource, *, capacity: int) -> None: + self.source = source + self.reader = SystemMemoryChunkReader(capacity=capacity) + self._lazy = LazyArray(source).with_reader(self.reader) + + @property + def shape(self) -> tuple[int, ...]: + return self.source.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self.source.dtype + + @property + def oindex(self) -> _OrthogonalIndexer: + return _OrthogonalIndexer(lambda key: self._read(key, orthogonal=True)) + + @property + def events(self) -> list[ChunkEvent]: + return self.reader.events + + @property + def projection_uses(self) -> tuple[tuple[str, str], ...]: + return tuple(self.reader.projection_uses) + + def state(self, chunk_coords: ChunkCoords) -> ChunkState: + return self.reader.state(chunk_coords) + + def resident(self) -> tuple[ChunkCoords, ...]: + return self.reader.resident() + + def retry(self, chunk_coords: ChunkCoords) -> None: + self.reader.retry(chunk_coords) + + def __getitem__(self, key: Any) -> np.ndarray[Any, Any]: + return self._read(key, orthogonal=False) + + def _read(self, key: Any, *, orthogonal: bool) -> np.ndarray[Any, Any]: + self.reader.projection_uses.clear() + lazy = self._lazy.lazy + view = lazy.oindex[key] if orthogonal else lazy[key] + # One prepared tuple is the request plan: pin from it, then hand the + # same owned parts back to LazyArray for assembly without replanning. + parts = tuple(view.parts()) + required = tuple(dict.fromkeys(part.base_coords for part in parts)) + with self.reader.request(required): + return np.asarray(view.result(parts=parts)) + + +# --8<-- [end:chunk-cache-wrapper] + + +# --8<-- [start:chunk-cache-worked-example] +image = np.arange(48).reshape(6, 8) +source = RecordingChunkSource(image, chunks=(3, 4)) +cache = SystemMemoryChunkCache(source, capacity=2) + +READS_BEFORE_SELECTION = tuple(source.reads) +INITIAL_RESULT = cache[1:5, 2] +INITIAL_READS = tuple(source.reads) + +before_overlap = len(source.reads) +OVERLAP_RESULT = cache[3:5, 2] +OVERLAP_NEW_READS = tuple(source.reads[before_overlap:]) + +before_eviction = len(source.reads) +EVICTION_RESULT = cache[0:2, 5] +EVICTION_NEW_READS = tuple(source.reads[before_eviction:]) +AFTER_EVICTION_RESIDENT = cache.resident() + +before_reload = len(source.reads) +RELOAD_RESULT = cache[1:5, 2] +RELOAD_NEW_READS = tuple(source.reads[before_reload:]) +AFTER_RELOAD_RESIDENT = cache.resident() + +source.failures.add((1, 1)) +failed_once = False +try: + cache[3:5, 4:6] +except ChunkLoadError: + failed_once = True +assert failed_once +FAILED_READ_COUNT = source.reads.count((1, 1)) +failed_twice = False +try: + cache[3:5, 4:6] +except ChunkLoadError: + failed_twice = True +assert failed_twice +FAILED_REPEAT_READ_COUNT = source.reads.count((1, 1)) +FAILURE_READ_COUNTS = (FAILED_READ_COUNT, FAILED_REPEAT_READ_COUNT) + +source.failures.remove((1, 1)) +cache.retry((1, 1)) +before_retry = len(source.reads) +RETRY_RESULT = cache[3:5, 4:6] +RETRY_NEW_READS = tuple(source.reads[before_retry:]) +RETRY_STATE = cache.state((1, 1)).value +WORKED_EVENTS = tuple(cache.events) +FAILED_TRANSITIONS = tuple( + event.current.value for event in WORKED_EVENTS if event.chunk_coords == (1, 1) +) +FAILED_EVENT_ROWS = tuple( + (event.previous.value, event.current.value, event.reason) + for event in WORKED_EVENTS + if event.chunk_coords == (1, 1) +) +# --8<-- [end:chunk-cache-worked-example] + +assert READS_BEFORE_SELECTION == () +assert INITIAL_RESULT.tolist() == [10, 18, 26, 34] +assert INITIAL_READS == ((0, 0), (1, 0)) +assert OVERLAP_RESULT.tolist() == [26, 34] +assert OVERLAP_NEW_READS == () +assert EVICTION_RESULT.tolist() == [5, 13] +assert EVICTION_NEW_READS == ((0, 1),) +assert AFTER_EVICTION_RESIDENT == ((0, 1), (1, 0)) +assert RELOAD_RESULT.tolist() == [10, 18, 26, 34] +assert RELOAD_NEW_READS == ((0, 0),) +assert AFTER_RELOAD_RESIDENT == ((0, 0), (1, 0)) +assert FAILURE_READ_COUNTS == (1, 1) +assert RETRY_RESULT.tolist() == [[28, 29], [36, 37]] +assert RETRY_NEW_READS == ((1, 1),) +assert RETRY_STATE == "ready" +assert FAILED_TRANSITIONS == ( + "queued", + "loading", + "failed", + "queued", + "loading", + "ready", +) +assert FAILED_EVENT_ROWS == ( + ("new", "queued", "requested"), + ("queued", "loading", "queue drained"), + ("loading", "failed", "source read failed"), + ("failed", "queued", "explicit retry"), + ("queued", "loading", "queue drained"), + ("loading", "ready", "source read completed"), +) diff --git a/packages/zarr-indexing/justfile b/packages/zarr-indexing/justfile new file mode 100644 index 0000000000..1b7164f647 --- /dev/null +++ b/packages/zarr-indexing/justfile @@ -0,0 +1,67 @@ +# Development verbs for the zarr-indexing package. Recipes run with this +# directory as the working directory regardless of where `just` is invoked. + +# List available recipes +default: + @just --list + +# The chunk-resolution tests exercise this package against zarr's ChunkGrid, so +# they need an environment that has both `zarr` and this package installed. +# `zarr` is deliberately not a dependency of this package, and the repo is not +# a uv workspace, so run against the repo-root environment (which provides +# `zarr`) with this package layered in as an editable overlay — the same +# invocation CI uses. +# Run the test suite; extra args are passed to pytest +test *args: + uv run --project ../.. --group test --with-editable . python -m pytest tests src/zarr_indexing {{ args }} + +# TensorStore is the oracle for the parity suites, which skip without it. It +# ships binary wheels only, so it rides in as a run-time overlay rather than +# joining a dependency group; if a future Python lacks a tensorstore wheel, +# gate the CI job that calls this on the matrix version. +# Run the tensorstore parity suites; extra args are passed to pytest +test-tensorstore *args: + uv run --project ../.. --group test --with-editable . --with 'tensorstore>=0.1.84' python -m pytest tests/test_ndsel_tensorstore.py tests/test_tensorstore_parity.py {{ args }} + +# Lint with the same invocation CI uses. Ruff is pinned to the repo-wide +# version (see pyproject.toml [dependency-groups] docs); bump together. +lint: + uvx ruff@0.16.0 check . + +# Type-check the package sources, documentation Python, and their contract tests +typecheck: + uv run --group test --with pyright pyright + +# Run everything CI runs for this package +check: lint typecheck test test-tensorstore 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-indexing/mkdocs.yml b/packages/zarr-indexing/mkdocs.yml new file mode 100644 index 0000000000..d97e63b150 --- /dev/null +++ b/packages/zarr-indexing/mkdocs.yml @@ -0,0 +1,155 @@ +site_name: zarr-indexing +# 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-indexing +repo_url: https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing +# 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-indexing/docs/ +site_description: Composable, lazy coordinate transforms for Zarr array indexing. +site_author: Davis Bennett +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr-indexing.readthedocs.io/'] +docs_dir: docs +use_directory_urls: true +exclude_docs: | + snippets/*.py + +# --strict promotes warnings to errors, but broken link anchors and pages +# missing from nav are only INFO by default — a strict build passed with +# both breakages. Warn so strict actually fails on them. +validation: + links: + anchors: warn + nav: + omitted_files: warn + +# Top-level rank is consistent: collections (Guide, Examples, API Reference) +# and standalone artifacts (landing, ndsel spec, design notes, changelog). +# Guide mirrors the docs/guide/ directory — its three pages are one +# collection (learn / look up / integrate), pydantic's Concepts pattern at +# small scale; navigation.indexes makes the Guide entry itself land on the +# visual guide. No tabs: at eight content pages, hiding sections costs more +# than it organizes. +nav: + - index.md + - Guide: + - guide/index.md + - Indexing patterns: guide/patterns.md + - Integration boundaries: guide/integrations.md + - Examples: + - Lazy indexing a NumPy array: examples/lazy_indexing_numpy.md + - Lazy indexing with Dask: examples/lazy_indexing_dask.md + - System-memory chunk cache: examples/system_memory_chunk_cache.md + - The ndsel wire format: ndsel.md + - Design notes: design-notes.md + - API Reference: + - api/index.md + - ' zarr_indexing.transform': api/transform.md + - ' zarr_indexing.domain': api/domain.md + - ' zarr_indexing.output_map': api/output_map.md + - ' zarr_indexing.chunk_resolution': api/chunk_resolution.md + - ' zarr_indexing.grid': api/grid.md + - ' zarr_indexing.lazy_array': api/lazy_array.md + - ' zarr_indexing.reader': api/reader.md + - ' zarr_indexing.boundary': api/boundary.md + - ' zarr_indexing.json': api/json.md + - ' zarr_indexing.messages': api/messages.md + - ' zarr_indexing.errors': api/errors.md + - ' zarr_indexing.testing.stateful': api/testing_stateful.md + - ' zarr_indexing.testing.strategies': api/testing_strategies.md + - Changelog: https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CHANGELOG.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/ + +watch: + - src + +theme: + language: en + name: material + logo: _static/logo_bw.png + favicon: _static/favicon-96x96.png + + palette: + # Light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + font: + text: Roboto + code: Roboto Mono + + features: + - content.code.annotate + - content.code.copy + - content.tabs.link + - navigation.indexes + - navigation.instant + - navigation.tracking + - search.suggest + - search.share + +plugins: + - autorefs + - search + - mkdocstrings: + enable_inventory: true + handlers: + python: + paths: [src] + options: + allow_inspection: true + docstring_section_style: list + docstring_style: numpy + inherited_members: true + line_length: 60 + separate_signature: true + show_root_heading: true + show_signature_annotations: true + show_source: true + show_symbol_type_toc: true + signature_crossrefs: true + show_if_no_docstring: true + extensions: + - griffe_inherited_docstrings + + inventories: + - https://docs.python.org/3/objects.inv + - https://numpy.org/doc/stable/objects.inv + - https://zarr.readthedocs.io/en/stable/objects.inv + +markdown_extensions: + - admonition + - attr_list + - def_list + - footnotes + - md_in_html + - pymdownx.details + - pymdownx.superfences + - toc: + permalink: true + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite + # Content tabs (Python/JSON pairs in the pattern matrix); content.tabs.link + # in the theme features keeps every pair switched together. + - pymdownx.tabbed: + alternate_style: true + - pymdownx.snippets: + base_path: [docs, examples] + # Fail the build on an unresolvable include or missing region instead + # of silently rendering nothing. tests/test_doc_examples.py mirrors + # base_path when it verifies the include graph. + check_paths: true diff --git a/packages/zarr-indexing/pyproject.toml b/packages/zarr-indexing/pyproject.toml new file mode 100644 index 0000000000..60f69a1dbb --- /dev/null +++ b/packages/zarr-indexing/pyproject.toml @@ -0,0 +1,171 @@ +[build-system] +requires = ["hatchling>=1.29.0", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "zarr-indexing" +dynamic = ["version"] +description = "Composable, lazy coordinate transforms for Zarr array indexing." +readme = "README.md" +requires-python = ">=3.12" +license = "MIT" +license-files = ["LICENSE.txt"] +authors = [ + { name = "Davis Bennett", email = "davis.v.bennett@gmail.com" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "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.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering", + "Topic :: Software Development :: Libraries :: Python Modules", + "Typing :: Typed", +] +keywords = ["zarr"] +dependencies = [ + "numpy>=2", +] + +[project.optional-dependencies] +# `zarr_indexing.testing` — a Hypothesis state machine and selection strategies +# for projects checking their own array against this package. Nothing else in +# the package imports hypothesis. +testing = ["hypothesis>=6.160.0"] + +[project.urls] +Homepage = "https://github.com/zarr-developers/zarr-python" +Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing" +Issues = "https://github.com/zarr-developers/zarr-python/issues" +Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CHANGELOG.md" +Documentation = "https://zarr-indexing.readthedocs.io/" + +[dependency-groups] +# The transform tests exercise chunk resolution against zarr's ChunkGrid +# (tests/test_chunk_resolution.py) and are collected by the parent zarr-python +# test suite, which already has zarr installed. `zarr` is intentionally NOT +# listed here to avoid a workspace dependency cycle; run these tests from the +# repo root (`uv run pytest packages/zarr-indexing/tests`), not in isolation. +# `hypothesis` arrives via the `testing` extra, which is what +# `zarr_indexing.testing` needs; the repo-root `test` group pins the exact +# version CI runs against. Bump the two together. +test = ["pytest", "hypothesis>=6.160.0"] +docs = [ + # Pins match the zarr-python docs environment in the repo-root + # pyproject.toml so the two sites render with the same toolchain. + "mkdocs-material==9.7.7", + "mkdocs==1.6.1", + "mkdocstrings==1.0.6", + "mkdocstrings-python==2.0.5", + "griffe-inherited-docstrings==1.1.3", + # mkdocstrings uses ruff to format rendered signatures + "ruff==0.15.22", +] + +[tool.hatch.version] +source = "vcs" +tag-pattern = '^zarr_indexing-v(?P.+)$' +# `git_describe_command` ensures we get the zarr_indexing tags instead of latest. +# `local_scheme` strips the git commit info so the appending info is just a counter from latest tag. +# test-pypi doesn't accept git commit info in tags, and the count should be enough to distinguish unique runs. +raw-options = { root = "../..", git_describe_command = "git describe --dirty --tags --long --match zarr_indexing-v*", local_scheme = "no-local-version" } + +[tool.hatch.build.targets.wheel] +packages = ["src/zarr_indexing"] + +# An allowlist, so nothing that merely happens to sit in the package directory +# — a scratch script, a stray notebook — can ride along in a release. The list +# keeps an sdist self-testing: `tests/` carries the vendored ndsel conformance +# corpus, and `tests/test_doc_examples.py` executes `docs/snippets/*.py` and +# `examples/*/*.py`, so those are part of the suite rather than decoration. +# `pyproject.toml`, `README.md` and `LICENSE.txt` are added by hatchling itself. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/docs", + "/examples", + "/mkdocs.yml", + "/justfile", + "/CHANGELOG.md", + "/CONTRIBUTING.md", +] + +[tool.ruff] +extend = "../../pyproject.toml" +target-version = "py312" + +[tool.ruff.lint.per-file-ignores] +# Chunk discovery and __dask_tokenize__ deliberately catch Exception: a +# foreign source's attributes may fail arbitrarily and discovery must degrade +# to "no information"; a token call must never raise. Configured here (not as +# noqa comments) because the pinned pre-commit ruff and the floating CI ruff +# disagree on whether these rules fire, and RUF100 strips the comments. +"src/zarr_indexing/lazy_array.py" = ["BLE001", "S110"] + +[tool.pytest.ini_options] +minversion = "7" +# src is collected for its doctests: every public object's Examples section +# executes under --doctest-modules, so the documented examples cannot rot. +testpaths = ["tests", "src/zarr_indexing"] +pythonpath = ["."] +xfail_strict = true +addopts = ["-ra", "--strict-config", "--strict-markers", "--doctest-modules"] +doctest_optionflags = [ + "NORMALIZE_WHITESPACE", + "ELLIPSIS", + "IGNORE_EXCEPTION_DETAIL", +] +filterwarnings = [ + "error", +] + +[tool.pyright] +include = [ + "src", + "docs/snippets", + "tests/test_doc_examples.py", +] +enableExperimentalFeatures = true +typeCheckingMode = "strict" +pythonVersion = "3.12" +# This strict config was written for zarr-metadata's JSON/dataclass-shaped +# code. zarr-indexing is numpy-heavy, and numpy's stubs return partially +# unknown types (e.g. `ndarray[Unknown, Unknown]`, `dtype[Unknown]`) even for +# fully-typed call sites, so the reportUnknown* family below cannot reasonably +# be satisfied here. Downgraded to warnings (not silenced) rather than +# disabled outright, and CI (which only fails the pyright job on errors, not +# warnings) still surfaces them for visibility. +reportUnknownVariableType = "warning" +reportUnknownArgumentType = "warning" +reportUnknownMemberType = "warning" +reportUnknownParameterType = "warning" + +[tool.numpydoc_validation] +checks = [ + "GL10", + "SS04", + "PR02", + "PR03", + "PR05", + "PR06", +] + +[tool.towncrier] +# Fragments for this package live alongside the package source, separate +# from the parent zarr-python `changes/` directory, so a PR touching only +# `packages/zarr-indexing/` produces a release note for this package only. +directory = "changes" +filename = "CHANGELOG.md" +package = "zarr_indexing" +underlines = ["", "", ""] +title_format = "## {version} ({project_date})" +issue_format = "[#{issue}](https://github.com/zarr-developers/zarr-python/issues/{issue})" +start_string = "\n" diff --git a/packages/zarr-indexing/src/zarr_indexing/__init__.py b/packages/zarr-indexing/src/zarr_indexing/__init__.py new file mode 100644 index 0000000000..9acfd28a21 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/__init__.py @@ -0,0 +1,116 @@ +"""Composable, lazy coordinate transforms for zarr array indexing. + +This package implements TensorStore-inspired index transforms. The core idea: +every indexing operation (slicing, fancy indexing, etc.) produces a coordinate +mapping from user space to storage space. These mappings compose lazily — no +I/O until you explicitly read or write. + +Key types: + +- `IndexDomain` — a rectangular region of integer coordinates +- `IndexTransform` — maps input coordinates to storage coordinates +- `ConstantMap`, `DimensionMap`, `ArrayMap` — the three ways a single + output dimension can depend on the input (see `output_map.py`) +- `IndexTransform.compose` — chain two transforms into one + +`LazyArray` wraps a system-memory/basic-indexing source and gives it deferred +indexing through `.lazy[...]`, yielding its reads as `Partition`s. Other +backends use an explicit `Reader` adapter. + +`plan_chunks` projects a transform through a caller-selected chunk grid without +coupling the result to a storage backend or scheduler. `selection_to_transform` +is also exported for consumers starting with a NumPy-style selection. The +`DimensionGridLike` Protocol describes the narrow grid surface chunk resolution +consumes without importing zarr. +""" + +from importlib.metadata import version + +from zarr_indexing.chunk_resolution import ( + ChunkCoverage, + ChunkPlan, + ChunkProjection, + plan_chunks, +) +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError, VindexInvalidSelectionError +from zarr_indexing.grid import ( + ChunkGrid, + ChunkSpec, + DimensionGrid, + DimensionGridLike, + EdgeDimensionGrid, + FixedDimension, + VaryingDimension, + dimension_grids_from_chunks, +) +from zarr_indexing.json import ( + IndexDomainJSON, + IndexTransformJSON, + OutputIndexMapJSON, +) +from zarr_indexing.lazy_array import LazyArray, Partition +from zarr_indexing.messages import NdselError, normalize_ndsel, parse_ndsel +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + OutputIndexMap, + output_index_map_from_json, +) +from zarr_indexing.reader import ( + BasicReader, + NumPyReader, + ReadContext, + Reader, + UnitStepReader, + basic_reader, + numpy_reader, + unit_step_reader, +) +from zarr_indexing.transform import ( + IndexTransform, +) + +__version__ = version("zarr-indexing") + +__all__ = [ + "ArrayMap", + "BasicReader", + "BoundsCheckError", + "ChunkCoverage", + "ChunkGrid", + "ChunkPlan", + "ChunkProjection", + "ChunkSpec", + "ConstantMap", + "DimensionGrid", + "DimensionGridLike", + "DimensionMap", + "EdgeDimensionGrid", + "FixedDimension", + "IndexDomain", + "IndexDomainJSON", + "IndexTransform", + "IndexTransformJSON", + "LazyArray", + "NdselError", + "NumPyReader", + "OutputIndexMap", + "OutputIndexMapJSON", + "Partition", + "ReadContext", + "Reader", + "UnitStepReader", + "VaryingDimension", + "VindexInvalidSelectionError", + "__version__", + "basic_reader", + "dimension_grids_from_chunks", + "normalize_ndsel", + "numpy_reader", + "output_index_map_from_json", + "parse_ndsel", + "plan_chunks", + "unit_step_reader", +] diff --git a/packages/zarr-indexing/src/zarr_indexing/_affine.py b/packages/zarr-indexing/src/zarr_indexing/_affine.py new file mode 100644 index 0000000000..d1846ffe2d --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_affine.py @@ -0,0 +1,77 @@ +"""Checked affine coordinate arithmetic.""" + +from __future__ import annotations + +from typing import Any, overload + +import numpy as np +import numpy.typing as npt + +_INTP_INFO = np.iinfo(np.intp) + + +def _fits_intp(value: int) -> bool: + return _INTP_INFO.min <= value <= _INTP_INFO.max + + +@overload +def checked_affine(offset: int, stride: int, coordinates: int) -> int: ... + + +@overload +def checked_affine( + offset: int, + stride: int, + coordinates: npt.NDArray[np.integer[Any]], +) -> npt.NDArray[np.intp]: ... + + +def checked_affine( + offset: int, + stride: int, + coordinates: int | npt.NDArray[np.integer[Any]], +) -> int | npt.NDArray[np.intp]: + """Evaluate ``offset + stride * coordinates`` without integer overflow. + + Bounds are established with Python integers before coordinates are cast or + NumPy performs fixed-width arithmetic. The common representable case then + uses an ``np.intp`` fast path whose multiplication and addition were proven + safe; cancellation cases use exact object arithmetic. + """ + offset = int(offset) + stride = int(stride) + if not isinstance(coordinates, np.ndarray): + mapped = offset + stride * int(coordinates) + if not _fits_intp(mapped): + raise OverflowError(f"output coordinate {mapped} is outside np.intp range") + return mapped + + if coordinates.size == 0: + return np.empty(coordinates.shape, dtype=np.intp) + + coordinate_min = int(np.min(coordinates)) + coordinate_max = int(np.max(coordinates)) + product_at_min = stride * coordinate_min + product_at_max = stride * coordinate_max + mapped_at_min = offset + product_at_min + mapped_at_max = offset + product_at_max + mapped_min = min(mapped_at_min, mapped_at_max) + mapped_max = max(mapped_at_min, mapped_at_max) + if not _fits_intp(mapped_min) or not _fits_intp(mapped_max): + invalid = mapped_min if not _fits_intp(mapped_min) else mapped_max + raise OverflowError(f"output coordinate {invalid} is outside np.intp range") + + safe_fixed_width = ( + _fits_intp(coordinate_min) + and _fits_intp(coordinate_max) + and _fits_intp(offset) + and _fits_intp(stride) + and _fits_intp(product_at_min) + and _fits_intp(product_at_max) + ) + if safe_fixed_width: + intp_coordinates = coordinates.astype(np.intp, copy=False) + return np.asarray(offset + stride * intp_coordinates, dtype=np.intp) + + exact = offset + stride * coordinates.astype(object) + return np.asarray(exact, dtype=np.intp) diff --git a/packages/zarr-indexing/src/zarr_indexing/_composition.py b/packages/zarr-indexing/src/zarr_indexing/_composition.py new file mode 100644 index 0000000000..f90ea26fa7 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_composition.py @@ -0,0 +1,242 @@ +"""Composition — chaining two transforms into one. + +`compose(outer, inner)` is the operation that makes views stack. `outer` maps +user coordinates to intermediate coordinates, `inner` maps those intermediate +coordinates to output coordinates, and the result maps user coordinates +straight through — so a view of a view of an array is still a single +`IndexTransform`, and indexing never accumulates layers to walk at read time. + +Composition works one output map at a time, and each case reduces to +substituting the outer map into the inner one: + +- A `ConstantMap` inner map ignores its input, so it survives unchanged. +- A `DimensionMap` inner map is affine, so composing it with an outer + `ConstantMap` or `DimensionMap` folds into new `offset`/`stride` values; + composing it with an outer `ArrayMap` leaves the index array alone and + rescales around it. +- An `ArrayMap` inner map must be *evaluated* at the coordinates the outer + transform produces, which is the only case that touches array data. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + OutputIndexMap, + array_map_or_constant, +) +from zarr_indexing.transform import IndexTransform + + +def compose(outer: IndexTransform, inner: IndexTransform) -> IndexTransform: + """Compose two IndexTransforms. + + `outer` maps user coords (rank m) to intermediate coords (rank n). + `inner` maps intermediate coords (rank n) to output coords (rank p). + The result maps user coords (rank m) to output coords (rank p). + + Precondition: `outer.output_rank == inner.domain.ndim`. + + Examples + -------- + Chained indexing — `source[2:5]`, then `[::-1]` on the result — collapses + to a single transform (a reversed axis keeps literal coordinates, so the + composed domain is `[-4, -1)`): + + >>> inner = IndexTransform.from_shape((10,))[2:5] + >>> outer = IndexTransform.identity(inner.domain)[::-1] + >>> chained = compose(outer, inner) + >>> chained == inner[::-1] + True + >>> [chained.apply((i,)) for i in (-4, -3, -2)] + [(4,), (3,), (2,)] + >>> np.arange(10)[2:5][::-1].tolist() + [4, 3, 2] + """ + if outer.output_rank != inner.domain.ndim: + raise ValueError( + f"outer output rank ({outer.output_rank}) must match inner input rank " + f"({inner.domain.ndim})" + ) + + _validate_outer_outputs(outer, inner) + + result_output = [ + _compose_single(outer, inner_map, inner.domain.inclusive_min) for inner_map in inner.output + ] + + return IndexTransform(domain=outer.domain, output=tuple(result_output)) + + +def _validate_outer_outputs(outer: IndexTransform, inner: IndexTransform) -> None: + """Prove that every intermediate coordinate is in the inner domain. + + An empty outer domain has no points, so containment is vacuously true. For + a nonempty domain, each map form has an exact, constant-space range proof: + constants are singletons, dimension maps are affine intervals, and array + maps need only their extrema. + """ + if any(extent == 0 for extent in outer.domain.shape): + return + + for axis, (outer_map, inner_lo, inner_hi) in enumerate( + zip( + outer.output, + inner.domain.inclusive_min, + inner.domain.exclusive_max, + strict=True, + ) + ): + output_lo, output_hi = _output_bounds(outer, outer_map) + if output_lo < inner_lo or output_hi >= inner_hi: + raise BoundsCheckError( + f"outer output dimension {axis} produces coordinates " + f"[{output_lo}, {output_hi}] outside the inner input domain " + f"[{inner_lo}, {inner_hi})" + ) + + +def _output_bounds(outer: IndexTransform, output_map: OutputIndexMap) -> tuple[int, int]: + """Return the exact inclusive bounds of one output map on a nonempty domain.""" + if isinstance(output_map, ConstantMap): + return output_map.offset, output_map.offset + + if isinstance(output_map, DimensionMap): + input_lo = outer.domain.inclusive_min[output_map.input_dimension] + input_hi = outer.domain.exclusive_max[output_map.input_dimension] + first = output_map.offset + output_map.stride * input_lo + last = output_map.offset + output_map.stride * (input_hi - 1) + return min(first, last), max(first, last) + + index_lo = int(output_map.index_array.min()) + index_hi = int(output_map.index_array.max()) + first = output_map.offset + output_map.stride * index_lo + last = output_map.offset + output_map.stride * index_hi + return min(first, last), max(first, last) + + +def _compose_single( + outer: IndexTransform, inner_map: OutputIndexMap, inner_origin: tuple[int, ...] +) -> OutputIndexMap: + """Compose a single inner output map with the full outer transform.""" + if isinstance(inner_map, ConstantMap): + return ConstantMap(offset=inner_map.offset) + + if isinstance(inner_map, DimensionMap): + return _compose_dimension(outer, inner_map) + + # inner_map: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + return _compose_array(outer, inner_map, inner_origin) + + +def _compose_dimension(outer: IndexTransform, inner_map: DimensionMap) -> OutputIndexMap: + """Compose when inner is a DimensionMap. + + storage = offset_i + stride_i * intermediate[dim_i] + where intermediate[dim_i] = outer.output[dim_i](user_input) + """ + dim_i = inner_map.input_dimension + offset_i = inner_map.offset + stride_i = inner_map.stride + outer_map = outer.output[dim_i] + + if isinstance(outer_map, ConstantMap): + return ConstantMap(offset=checked_affine(offset_i, stride_i, outer_map.offset)) + + if isinstance(outer_map, DimensionMap): + return DimensionMap( + input_dimension=outer_map.input_dimension, + offset=offset_i + stride_i * outer_map.offset, + stride=stride_i * outer_map.stride, + ) + + # outer_map: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + # Affine post-composition leaves the index array (and hence its full + # input rank and dependency axes) untouched. + return ArrayMap( + index_array=outer_map.index_array, + offset=offset_i + stride_i * outer_map.offset, + stride=stride_i * outer_map.stride, + ) + + +def _dimension_positions( + outer: IndexTransform, outer_map: DimensionMap, inner_origin: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Build exact positional indices for an affine outer map.""" + dimension = outer_map.input_dimension + extent = outer.domain.shape[dimension] + start = checked_affine( + outer_map.offset - inner_origin, + outer_map.stride, + outer.domain.inclusive_min[dimension], + ) + shape = (1,) * dimension + (extent,) + (1,) * (outer.input_rank - dimension - 1) + if extent == 0: + return np.empty(shape, dtype=np.intp) + if extent == 1: + return np.full(shape, start, dtype=np.intp) + steps = np.arange(extent, dtype=np.intp) + return checked_affine(start, outer_map.stride, steps).reshape(shape) + + +def _array_positions(outer_map: ArrayMap, inner_origin: int) -> np.ndarray[Any, np.dtype[np.intp]]: + """Build exact positional indices without fixed-width affine overflow.""" + return checked_affine(outer_map.offset - inner_origin, outer_map.stride, outer_map.index_array) + + +def _positions_for_axis( + outer: IndexTransform, outer_map: OutputIndexMap, inner_origin: int +) -> int | np.ndarray[Any, np.dtype[np.intp]]: + """Convert one intermediate coordinate map to inner-array positions.""" + if isinstance(outer_map, ConstantMap): + return outer_map.offset - inner_origin + if isinstance(outer_map, DimensionMap): + return _dimension_positions(outer, outer_map, inner_origin) + return _array_positions(outer_map, inner_origin) + + +def _compose_array( + outer: IndexTransform, inner_map: ArrayMap, inner_origin: tuple[int, ...] +) -> OutputIndexMap: + """Compose when inner is an ArrayMap. + + storage = offset_i + stride_i * arr_i[intermediate] + We need to evaluate arr_i at the intermediate coordinates produced by outer. + + Both domains carry their own origin, and neither is necessarily 0 — a step-1 + slice keeps its literal bounds and a negative step produces a negative + origin, so non-zero origins are the ordinary case here rather than the exotic + one. The intermediate coordinates are read over the *outer* domain's own + range, and the inner array is addressed positionally from the *inner* + domain's origin. + """ + arr_i = inner_map.index_array + if any(extent == 0 for extent in outer.domain.shape): + # The empty map is singleton on every non-empty axis: it varies over no + # axis at all, and the emptiness lives in the domain emitted alongside. + empty_shape = tuple(0 if extent == 0 else 1 for extent in outer.domain.shape) + return ArrayMap( + index_array=np.empty(empty_shape, dtype=arr_i.dtype), + offset=inner_map.offset, + stride=inner_map.stride, + ) + + positions = tuple( + 0 if size == 1 else _positions_for_axis(outer, outer_map, origin) + for outer_map, origin, size in zip(outer.output, inner_origin, arr_i.shape, strict=True) + ) + # A gather narrowed to one coordinate — scalar or all-singleton — is the + # ConstantMap it equals; `array_map_or_constant` normalizes both. + gathered = np.asarray(arr_i[positions]) + if gathered.ndim == 0: + return ConstantMap(offset=checked_affine(inner_map.offset, inner_map.stride, int(gathered))) + return array_map_or_constant(gathered, offset=inner_map.offset, stride=inner_map.stride) diff --git a/packages/zarr-indexing/src/zarr_indexing/_selector.py b/packages/zarr-indexing/src/zarr_indexing/_selector.py new file mode 100644 index 0000000000..3a632ec886 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_selector.py @@ -0,0 +1,41 @@ +"""Internal scalar-selector coercion shared by indexing dialects.""" + +from __future__ import annotations + +import operator +from typing import Any, SupportsIndex, cast + +import numpy as np + + +def is_bool_scalar(value: Any) -> bool: + """Return whether ``value`` is a Python or NumPy boolean scalar.""" + return isinstance(value, (bool, np.bool_)) + + +def as_scalar_index(value: Any) -> int | None: + """Return a non-boolean scalar selector as an exact Python integer. + + Selector coercion follows Python's ``__index__`` protocol, rather than + accepting only the concrete integer classes we happen to know about. In + particular, ``operator.index`` rejects lossy ``__int__``-only objects and + validates that ``__index__`` really returned an integer. + """ + if is_bool_scalar(value): + return None + # ndarray defines ``__index__`` for its scalar-integer case, but the + # attribute also makes non-scalar and non-integer arrays look like + # ``SupportsIndex`` at runtime. Those are array selectors, not malformed + # scalar selectors, and must continue through array dtype validation. + if isinstance(value, np.ndarray): + array = cast("np.ndarray[Any, np.dtype[Any]]", value) + if array.ndim != 0 or array.dtype.kind not in "iu": + return None + if not isinstance(value, SupportsIndex): + return None + return operator.index(cast(SupportsIndex, value)) + + +def require_index(value: Any) -> int: + """Coerce a required slice component through ``__index__``.""" + return operator.index(value) diff --git a/packages/zarr-indexing/src/zarr_indexing/_wire.py b/packages/zarr-indexing/src/zarr_indexing/_wire.py new file mode 100644 index 0000000000..c3e6fd82b6 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_wire.py @@ -0,0 +1,119 @@ +"""Shared lowering rules between the canonical ndsel wire form and the engine. + +Package-private: the types that serialize themselves (`IndexDomain`, +`IndexTransform`, the output map kinds) all need these, so they cannot live in +any one of them, and they are not API. The three engine constraints named in +[`zarr_indexing.json`][zarr_indexing.json] — finite bounds, implicit bounds +lowering by value, integer `index_array` content — are enforced here. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np + +from zarr_indexing.messages import NdselError + +if TYPE_CHECKING: + from zarr_indexing.domain import IndexDomain + from zarr_indexing.json import BoundJSON + + +def lower_bound(bound: BoundJSON, where: str) -> int: + """Lower a canonical bound to a finite integer, rejecting infinities. + + Reached only with a bound the message layer has already validated as an + `index-value`, so the one thing left to rule out is a sentinel: an + `IndexDomain` addresses a finite array. + """ + value = bound[0] if isinstance(bound, list) else bound + if value == "-inf" or value == "+inf": + raise NdselError( + "invalid_json", + f"{where} is infinite ({value!r}); an IndexDomain addresses a finite " + f"array and cannot lower an infinite bound", + ) + return int(value) + + +def lower_index_array(raw: Any, where: str) -> np.ndarray[Any, np.dtype[np.intp]]: + """Lower a canonical `index_array` to `intp`, rejecting non-integer content. + + The message layer carries `index_array` verbatim — the spec defers its shape + and type to the engine — so this is where the content is checked. An index + array names output coordinates, and nothing but an integer names one: converting + `[0.9, 1.9]` would silently read cells 0 and 1, and `[true, false]` cells 1 + and 0. Strings raise here rather than leaking NumPy's own conversion error. + """ + if not isinstance(raw, list): + # A bare integer would become a rank-0 array and then be widened into a + # length-1 map, so a document that names no cells would select one. + raise NdselError( + "invalid_json", + f"{where} must be an array of integers, got {raw!r}", + ) + try: + arr = np.asarray(raw) + except (TypeError, ValueError) as exc: + raise NdselError("invalid_json", f"{where} is not an array: {exc}") from exc + if arr.size == 0 and arr.dtype.kind == "f": + # An empty JSON list carries no element type and NumPy defaults it to + # float64. An empty selection is legal, so take it as an empty index array. + return np.zeros(arr.shape, dtype=np.intp) + if arr.dtype.kind not in "iu": + raise NdselError( + "invalid_json", + f"{where} must hold integers, got an array of {arr.dtype.name}; an " + f"index array names output coordinates, which floats, booleans and " + f"strings do not", + ) + return np.asarray(arr, dtype=np.intp) + + +def lower_labels(labels: list[str]) -> tuple[str, ...] | None: + """All-empty labels collapse to `None` so a label-free domain round-trips.""" + return None if all(label == "" for label in labels) else tuple(labels) + + +def emit_labels(labels: tuple[str, ...] | None, rank: int) -> list[str]: + """Emit canonical labels: `[""]*rank` when the domain is unlabeled.""" + return [""] * rank if labels is None else list(labels) + + +def full_rank_index_array( + arr: np.ndarray[Any, np.dtype[np.intp]], + domain: IndexDomain, + where: str, +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Give an incoming `index_array` the input rank the engine requires. + + ndsel leaves index-array rank unvalidated, so a conformant producer may send + an array of lower rank that broadcasts against the domain. A non-empty one + is aligned to the *trailing* input dimensions, which is how NumPy broadcasts + and how a producer omitting leading singletons means it to be read. + + An empty array is a different matter: `[]` is the only spelling of every + empty shape once the leading axis is the zero-length one, so the axis it + varies over cannot be read off it. It is recovered from the domain, which + can only be empty on the axis in question — and rejected when the domain + leaves that ambiguous. This package never emits such a document (an empty + map is degenerate and collapses to a constant, as TensorStore's does), so + this path exists for external producers alone. + """ + if arr.size == 0 and arr.ndim != domain.ndim: + empty_axes = [k for k, extent in enumerate(domain.shape) if extent == 0] + if len(empty_axes) != 1: + raise NdselError( + "invalid_json", + f"{where}.index_array is empty, but the input domain has " + f"{len(empty_axes)} zero-length dimensions, so the axis it varies " + f"over cannot be recovered", + ) + shape = [1] * domain.ndim + shape[empty_axes[0]] = 0 + return arr.reshape(tuple(shape)) + + if arr.ndim < domain.ndim: + return arr.reshape((1,) * (domain.ndim - arr.ndim) + arr.shape) + return arr diff --git a/packages/zarr-indexing/src/zarr_indexing/boundary.py b/packages/zarr-indexing/src/zarr_indexing/boundary.py new file mode 100644 index 0000000000..e7f1b1c4bd --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/boundary.py @@ -0,0 +1,374 @@ +"""The positional (NumPy) selection dialect, lowered onto the transform algebra. + +The transform algebra uses **literal domain coordinates**: an index is a point +in the view's own coordinate system, which after `view = arr[10:50]` runs from +10 to 49, and a negative index is a negative coordinate rather than an offset +from the end (TensorStore's convention — see `zarr_indexing.transform`). + +NumPy uses **positions**: index 0 always means the first element of the object +being indexed, and `-1` means the last. This module translates between the two. +It validates a selection against the view's shape with NumPy semantics, then +shifts every coordinate by the domain's origin so the transform layer sees +literal coordinates. + +Note +---- +`zarr.Array` currently carries its own copy of this normalization, tuned to a +different boundary contract (`Array.lazy[...]` deliberately exposes the literal +dialect, so a view's coordinates keep their meaning across composition). This +module is the generic, zarr-free version used by `LazyArray`; consolidating +zarr's copy onto it is left to a follow-up. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np + +from zarr_indexing._selector import as_scalar_index, is_bool_scalar, require_index + +if TYPE_CHECKING: + from zarr_indexing.domain import IndexDomain + +SelectionMode = Literal["basic", "orthogonal", "vectorized"] + + +def _as_index_array(sel: Any) -> np.ndarray[Any, np.dtype[Any]] | None: + """Return `sel` as an ndarray if it is array-like, else None.""" + if isinstance(sel, np.ndarray): + return sel + if isinstance(sel, (list, tuple)): + arr = np.asarray(sel) + if arr.size == 0 and arr.dtype.kind == "f": + # An empty Python list carries no element type and NumPy defaults it + # to float64. Selecting nothing is legal — NumPy takes `a[np.ix_([])]` + # — so read it as the empty integer selection it spells, rather than + # rejecting it for a dtype it never had a chance to have. + return np.zeros(arr.shape, dtype=np.intp) + if arr.dtype.kind in "biu": + return arr + raise IndexError( + f"arrays used as indices must be of integer or boolean type; got dtype {arr.dtype}" + ) + return None + + +def _axes_consumed(sel: Any, mode: SelectionMode) -> int: + """How many axes of the view a single selection entry consumes.""" + if sel is None: + return 0 + arr = _as_index_array(sel) + # A multidimensional boolean mask consumes one axis per mask dimension. + # Orthogonal indexing is per-axis by construction, so a mask there is 1-D + # and consumes exactly one axis. + if mode == "vectorized" and arr is not None and arr.dtype == np.bool_: + return arr.ndim + return 1 + + +def _normalize_int(value: int, size: int, axis: int) -> int: + """Bounds-check a positional integer index, wrapping negatives NumPy-style.""" + idx = value + if idx < 0: + idx += size + if idx < 0 or idx >= size: + raise IndexError(f"index {value} is out of bounds for axis {axis} with size {size}") + return idx + + +def _normalize_slice(sel: slice, size: int, axis: int) -> tuple[int, int, int]: + """Resolve a positional slice to `(start, stop, step)`, either direction. + + `slice.indices` already applies NumPy's rules — negative bounds count from + the end, out-of-range bounds clamp, and a reversed slice runs downward with + `stop` one *below* the last selected position. The one thing it does not do + is canonicalize an empty result: it can hand back a stop on the far side of + the start (`5:2` going up, `2:5` going down), which the transform layer + reads as a direction error rather than an empty selection. Collapsing it to + `stop == start` keeps NumPy's "empty, not an error" answer. + """ + start_bound = None if sel.start is None else require_index(sel.start) + stop_bound = None if sel.stop is None else require_index(sel.stop) + step = 1 if sel.step is None else require_index(sel.step) + if step == 0: + raise ValueError(f"slice step cannot be zero (axis {axis})") # ValueError: NumPy parity + start, stop, step = slice(start_bound, stop_bound, step).indices(size) + stop = max(stop, start) if step > 0 else min(stop, start) + return start, stop, step + + +def _normalize_int_array( + arr: np.ndarray[Any, np.dtype[Any]], size: int, axis: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Bounds-check a positional integer index array, wrapping negatives.""" + if arr.dtype.kind not in "iu": + raise IndexError( + f"arrays used as indices must be of integer or boolean type; got dtype {arr.dtype}" + ) + # Cast before wrapping: an unsigned array cannot represent the intermediate + # negative values, and `intp` covers every index NumPy can address. + out = arr.astype(np.intp, copy=True) + if out.size > 0: + negative = out < 0 + if bool(negative.any()): + out = np.where(negative, out + size, out) + lo, hi = int(out.min()), int(out.max()) + if lo < 0 or hi >= size: + bad = lo if lo < 0 else hi + raise IndexError(f"index {bad} is out of bounds for axis {axis} with size {size}") + return out + + +def _expanded_axis_walk(entries: tuple[Any, ...], ndim: int, mode: SelectionMode) -> list[int]: + """The starting axis each entry addresses, with an ellipsis expanded. + + The returned list has one entry per element of `entries`; the value for an + `Ellipsis` (or a `newaxis`) is the axis it starts at, which is also the axis + the following entry resumes from once the skipped axes are accounted for. + """ + for sel in entries: + if is_bool_scalar(sel): + raise IndexError( + "boolean scalars are not valid indices; use a boolean array " + "matching the shape of the axes it selects" + ) + if sum(1 for sel in entries if sel is Ellipsis) > 1: + raise IndexError("an index can only have a single ellipsis ('...')") + consumed = sum(_axes_consumed(sel, mode) for sel in entries if sel is not Ellipsis) + if consumed > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, but {consumed} were indexed" + ) + + axes: list[int] = [] + axis = 0 + for sel in entries: + axes.append(axis) + axis += (ndim - consumed) if sel is Ellipsis else _axes_consumed(sel, mode) + return axes + + +def validate_advanced_selection( + selection: Any, + domain: IndexDomain, + mode: Literal["orthogonal", "vectorized"], +) -> None: + """Validate advanced-index selector dtypes and boolean mask extents. + + This is the validation shared by positional callers such as `LazyArray` + and direct `IndexTransform.oindex` / `.vindex` callers. It deliberately + does not normalize coordinates: direct transforms use literal coordinates, + whereas positional callers shift and wrap them separately. + """ + entries: tuple[Any, ...] = selection if isinstance(selection, tuple) else (selection,) + axes = _expanded_axis_walk(entries, domain.ndim, mode) + + for sel, axis in zip(entries, axes, strict=True): + arr = _as_index_array(sel) + if arr is None: + continue + if arr.dtype == np.bool_: + n_axes = _axes_consumed(sel, mode) + expected = domain.shape[axis : axis + n_axes] + if arr.shape != tuple(expected): + extent = ( + f"dimension {expected[0]}" + if len(expected) == 1 + else f"dimensions {tuple(expected)}" + ) + raise IndexError( + f"boolean index has shape {arr.shape} but {extent} has shape {tuple(expected)}" + ) + elif arr.dtype.kind not in "iu": + raise IndexError( + f"arrays used as indices must be of integer or boolean type; got dtype {arr.dtype}" + ) + + +def split_scalar_axes( + selection: Any, + domain: IndexDomain, + mode: SelectionMode, +) -> tuple[tuple[Any, ...] | None, Any]: + """Peel scalar integer indices out of a fancy selection. + + A scalar integer drops its axis, and neither the orthogonal nor the + vectorized path of the transform algebra models that — both widen a scalar + into a length-1 index array, which keeps the axis — so the scalars are split + off here and applied as a separate basic step first. + + Applying them *first* is this package's rule, not NumPy's. NumPy groups a + scalar with the advanced indices for the purpose of placing the broadcast + result, so the two disagree when a scalar and an index array are separated: + `a[0, ..., [1, 2]]` has shape `(2, 3)` for a `(2, 3, 4)` array, where + `a[0][..., [1, 2]]` has shape `(3, 2)`. The earlier claim here that they + always agree rested on `a[0, [1, 2], :]`, where the indices are adjacent and + they happen to. Scalar-first is the documented dialect (see the `lazy_array` + module docstring) — the divergence is deliberate, and this note exists so + that the correct end is not "fixed" later. + + Parameters + ---------- + selection + A positional orthogonal or vectorized selection. + domain + The domain of the view being indexed. + mode + `"orthogonal"` or `"vectorized"`; controls how many axes each entry + covers, which decides where the scalars sit. + + Returns + ------- + tuple[tuple[Any, ...] | None, Any] + `(basic_selection, remaining_selection)`. `basic_selection` is a + full-rank basic selection in **literal** domain coordinates that drops + the scalar axes, or `None` when the selection has no scalar entries (in + which case `remaining_selection` is `selection` unchanged). + + Raises + ------ + IndexError + If a boolean scalar is used as an index, an index is out of bounds, or + too many indices are supplied. + """ + entries = selection if isinstance(selection, tuple) else (selection,) + axes = _expanded_axis_walk(entries, domain.ndim, mode) + + scalar_axes: dict[int, int] = {} + remaining: list[Any] = [] + for sel, axis in zip(entries, axes, strict=True): + scalar = as_scalar_index(sel) + if scalar is not None: + scalar_axes[axis] = _normalize_int(scalar, domain.shape[axis], axis) + else: + remaining.append(sel) + + if len(scalar_axes) == 0: + return None, selection + + basic: list[Any] = [] + for axis in range(domain.ndim): + lo = domain.inclusive_min[axis] + if axis in scalar_axes: + basic.append(lo + scalar_axes[axis]) + else: + basic.append(slice(lo, domain.exclusive_max[axis])) + return tuple(basic), tuple(remaining) + + +def normalize_positional_selection( + selection: Any, + domain: IndexDomain, + mode: SelectionMode, +) -> Any: + """Translate a positional (NumPy-dialect) selection into literal coordinates. + + Positions are zero-based offsets into the current view; negatives wrap + from the end. The returned selection addresses the same cells in the + literal coordinate system `domain` uses, ready for + `zarr_indexing.transform.selection_to_transform`. + + Parameters + ---------- + selection + A NumPy-style selection: integers, slices, `Ellipsis`, integer arrays or + lists, or boolean arrays. + domain + The domain of the view being indexed. Its shape defines the positional + bounds and its origin the coordinate shift. + mode + Which selection dialect the entries follow: `"basic"` (integers and + slices), `"orthogonal"` (per-axis arrays, outer product), or + `"vectorized"` (correlated coordinate arrays or a single mask). + + Returns + ------- + tuple[Any, ...] + The selection with every coordinate expressed in literal domain + coordinates. + + Raises + ------ + IndexError + If a boolean scalar is used as an index, a boolean mask does not match + the shape of the axes it covers, an index is out of bounds, or too many + indices are supplied. + """ + entries = selection if isinstance(selection, tuple) else (selection,) + shape = domain.shape + origin = domain.inclusive_min + ndim = domain.ndim + + if mode in ("orthogonal", "vectorized"): + validate_advanced_selection(selection, domain, mode) + else: + for sel in entries: + if is_bool_scalar(sel): + raise IndexError( + "boolean scalars are not valid indices; use a boolean array " + "matching the shape of the axes it selects" + ) + + n_ellipsis = sum(1 for sel in entries if sel is Ellipsis) + if n_ellipsis > 1: + raise IndexError("an index can only have a single ellipsis ('...')") + consumed = sum(_axes_consumed(sel, mode) for sel in entries if sel is not Ellipsis) + if consumed > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, but {consumed} were indexed" + ) + + result: list[Any] = [] + axis = 0 + for sel in entries: + if sel is Ellipsis: + # Passed through rather than expanded: every mode of + # `selection_to_transform` expands an ellipsis (and pads short + # selections) to whole-axis slices itself, and `vectorized` mode + # rejects an explicit slice, so expanding here would turn a legal + # partial coordinate selection into an error. + result.append(Ellipsis) + axis += ndim - consumed + continue + if sel is None: + # newaxis: no axis of the view is consumed, and there is no + # coordinate to shift. The transform layer decides whether the mode + # accepts it. + result.append(None) + continue + + arr = _as_index_array(sel) + if arr is not None and arr.dtype == np.bool_: + n_axes = _axes_consumed(sel, mode) + expected = shape[axis : axis + n_axes] + if arr.shape != tuple(expected): + raise IndexError( + f"boolean index has shape {arr.shape} but the axes it " + f"covers have shape {tuple(expected)}" + ) + for offset, positions in enumerate(np.nonzero(arr)): + result.append(positions.astype(np.intp) + origin[axis + offset]) + axis += n_axes + continue + + if axis >= ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, " + f"but {consumed} were indexed" + ) + size = shape[axis] + if arr is not None: + result.append(_normalize_int_array(arr, size, axis) + origin[axis]) + elif isinstance(sel, slice): + start, stop, step = _normalize_slice(sel, size, axis) + result.append(slice(start + origin[axis], stop + origin[axis], step)) + elif (scalar := as_scalar_index(sel)) is not None: + result.append(_normalize_int(scalar, size, axis) + origin[axis]) + else: + raise IndexError(f"unsupported selection type: {type(sel)!r}") + axis += 1 + + # Axes the selection did not mention are left to `selection_to_transform`, + # which pads them with whole-axis slices in every mode. + return tuple(result) diff --git a/packages/zarr-indexing/src/zarr_indexing/chunk_resolution.py b/packages/zarr-indexing/src/zarr_indexing/chunk_resolution.py new file mode 100644 index 0000000000..af148685a0 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/chunk_resolution.py @@ -0,0 +1,595 @@ +"""Chunk resolution — mapping transforms to chunk-level I/O. + +Given an `IndexTransform` (which coordinates a user wants to access) and a +`ChunkGrid` (how storage is divided into chunks), chunk resolution answers: + + For each chunk, which storage coordinates does this transform touch, + and where do those values land in the output buffer? + +The algorithm is: + +1. **Enumerate candidate chunks** — determine which chunks could possibly + be touched by the transform's output coordinate ranges. + +2. **Intersect** — for each candidate chunk, call + `transform.intersect(chunk_domain)` to restrict the transform to + coordinates within that chunk. If the intersection is empty, skip it. + +3. **Translate** — shift the restricted transform to chunk-local coordinates + via `transform.translate(-chunk_origin)`. + +4. **Project** — pair the chunk-local storage transform with a transform back + to the request's cells. Both use the same compact, zero-origin domain. + +Sorted one-dimensional correlated array maps can be partitioned directly +because every touched chunk owns a contiguous slice of the index array. That +case bypasses candidate enumeration and repeated intersection. + +The public result is a lazy, reusable `ChunkPlan`. Each `ChunkProjection` is +source-independent: it identifies the chunk and expresses both sides of the +gather without assuming NumPy selectors, a codec pipeline, or an execution +scheduler. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing.domain import IndexDomain +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import ( + IndexTransform, +) + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + + from zarr_indexing.grid import DimensionGridLike + +_OutIndices = ( + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None +) + +_ChunkTransformResult = tuple[ + tuple[int, ...], + IndexTransform, + _OutIndices, +] + +type ChunkCoverage = Literal["full", "partial", "unknown"] + + +def _data_size(dim_grid: DimensionGridLike, chunk_ix: int) -> int: + """Return a chunk's data extent, falling back for narrow-protocol grids.""" + data_size = getattr(dim_grid, "data_size", None) + if data_size is None: + return dim_grid.chunk_size(chunk_ix) + return int(data_size(chunk_ix)) + + +@dataclass(frozen=True, slots=True) +class ChunkProjection: + """One source-independent projection of a request through a chunk. + + Both transforms share a synthetic input domain. ``chunk_transform`` maps + that domain to chunk-local storage coordinates; ``cell_transform`` maps it + to the original request domain. + + Attributes + ---------- + chunk_coords + Coordinates of the selected cell in the caller's grid. + chunk_domain + Bounds of that grid cell in global storage coordinates. + chunk_transform + Mapping from the shared synthetic domain to chunk-local storage. + cell_transform + Mapping from the shared synthetic domain to request coordinates. + coverage + Whether the request is proven to cover the whole grid cell exactly + once. Fancy selections are conservatively ``"unknown"``. + + Examples + -------- + Row 1 of a `(3, 4)` array with `(2, 2)` chunks touches only part of the + first chunk, whose domain spans rows `[0, 2)` and columns `[0, 2)`: + + >>> from zarr_indexing import IndexTransform + >>> from zarr_indexing.grid import dimension_grids_from_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> first = next(iter(plan)) + >>> first.chunk_coords + (0, 0) + >>> first.chunk_domain.shape + (2, 2) + >>> first.coverage + 'partial' + """ + + chunk_coords: tuple[int, ...] + chunk_domain: IndexDomain + chunk_transform: IndexTransform + cell_transform: IndexTransform + coverage: ChunkCoverage + + def __post_init__(self) -> None: + if self.chunk_transform.domain != self.cell_transform.domain: + raise ValueError( + "chunk_transform and cell_transform must share an input domain; " + f"got {self.chunk_transform.domain!r} and {self.cell_transform.domain!r}" + ) + + +@dataclass(frozen=True, slots=True) +class ChunkPlan: + """A reusable, lazy partition of an index transform over a chunk grid. + + Construct plans with `plan_chunks`; iterating either the plan or + `projections()` performs a fresh chunk walk. + + Examples + -------- + Row 1 of a `(3, 4)` array with `(2, 2)` chunks crosses two chunks, and + the plan can be walked again after it is exhausted: + + >>> from zarr_indexing import IndexTransform + >>> from zarr_indexing.grid import dimension_grids_from_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> [p.chunk_coords for p in plan] + [(0, 0), (0, 1)] + >>> [p.chunk_coords for p in plan.projections()] + [(0, 0), (0, 1)] + """ + + transform: IndexTransform + """The composed request this plan partitions.""" + + dimension_grids: tuple[DimensionGridLike, ...] + """One grid per storage dimension, defining the chunk layout the plan walks.""" + + def projections(self) -> Iterator[ChunkProjection]: + """Return a fresh iterator over the chunks touched by this plan.""" + return _iter_chunk_projections(self.transform, self.dimension_grids) + + def __iter__(self) -> Iterator[ChunkProjection]: + """Equivalent to `projections()`: each iteration performs a fresh chunk walk.""" + return self.projections() + + +def plan_chunks( + transform: IndexTransform, + dimension_grids: Sequence[DimensionGridLike], +) -> ChunkPlan: + """Plan a transform against a caller-selected chunk grid. + + Parameters + ---------- + transform + Mapping from the request domain to storage coordinates. + dimension_grids + One storage grid per transform output dimension. + + Returns + ------- + ChunkPlan + A reusable plan whose projections are computed lazily. + + Examples + -------- + Row 1 of a `(3, 4)` array with `(2, 2)` chunks touches the two chunks in + the top grid row, each contributing a `(2, 2)` chunk domain: + + >>> from zarr_indexing import IndexTransform + >>> from zarr_indexing.grid import dimension_grids_from_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> [p.chunk_coords for p in plan] + [(0, 0), (0, 1)] + >>> [p.chunk_domain.shape for p in plan] + [(2, 2), (2, 2)] + """ + grids = tuple(dimension_grids) + if len(grids) != transform.output_rank: + raise ValueError( + "dimension_grids must have one entry per transform output dimension; " + f"got {len(grids)} grids for output rank {transform.output_rank}" + ) + return ChunkPlan(transform=transform, dimension_grids=grids) + + +def _one_dimensional_array_map( + transform: IndexTransform, +) -> tuple[ArrayMap, np.ndarray[Any, np.dtype[np.intp]]] | None: + """Return a nonempty 1-D single-ArrayMap transform's map and storage coords. + + A one-dimensional array selection has no cross-dimensional correlation to + preserve — the orthogonal and vectorized flavors coincide there — so the + sorted fast path applies to either spelling. The computed storage + coordinates are also reused by general resolution when they are unsorted. + """ + if transform.input_rank != 1 or transform.output_rank != 1: + return None + + m = transform.output[0] + if not isinstance(m, ArrayMap) or m.index_array.ndim != 1 or m.index_array.size == 0: + return None + + return m, checked_affine(m.offset, m.stride, m.index_array) + + +def _iter_sorted_1d_array_map( + m: ArrayMap, + storage: np.ndarray[Any, np.dtype[np.intp]], + dim_grid: DimensionGridLike, +) -> Iterator[_ChunkTransformResult]: + """Resolve a sorted 1-D ArrayMap one touched chunk at a time.""" + start = 0 + while start < storage.size: + chunk = dim_grid.index_to_chunk(int(storage[start])) + chunk_start = dim_grid.chunk_offset(chunk) + chunk_stop = chunk_start + _data_size(dim_grid, chunk) + stop = int(np.searchsorted(storage, chunk_stop, side="left")) + + restricted = IndexTransform( + domain=IndexDomain(inclusive_min=(0,), exclusive_max=(stop - start,)), + output=( + ArrayMap( + index_array=m.index_array[start:stop], + offset=m.offset, + stride=m.stride, + ), + ), + ) + local = restricted.translate((-chunk_start,)) + surviving = np.arange(start, stop, dtype=np.intp) + + yield (chunk,), local, surviving + start = stop + + +def _iter_chunk_transform_results( + transform: IndexTransform, + dim_grids: Sequence[DimensionGridLike], +) -> Iterator[_ChunkTransformResult]: + """Resolve a transform into private intersection bookkeeping. + + The survivor arrays are an implementation detail immediately converted to + a public `cell_transform` by `_iter_chunk_projections`. + """ + + if any(size == 0 for size in transform.domain.shape): + # An empty view touches no chunk. Checked on the domain rather than on + # the index arrays: an axis of genuine extent 1 is stored as a broadcast + # singleton, so a slice that empties the domain does not shrink the + # array, and the emptiness shows only here. + return + + array_map_1d = _one_dimensional_array_map(transform) + if array_map_1d is not None: + sorted_map, storage = array_map_1d + if storage[0] <= storage[-1] and bool(np.all(storage[1:] >= storage[:-1])): + dim_grid = dim_grids[0] + first_chunk = dim_grid.index_to_chunk(int(storage[0])) + if dim_grid.chunk_size(first_chunk) > 0: + yield from _iter_sorted_1d_array_map(sorted_map, storage, dim_grid) + return + + # Enumerate candidate chunks via the cartesian product of per-slot candidate + # chunk ids, then for each candidate intersect the transform with the chunk + # domain (`transform.intersect` handles orthogonal and vectorized cases + # alike, filtering out combinations it does not actually touch). + # + # A slot covers one or more output dimensions and contributes exactly the + # chunk-coordinate tuples those dimensions can touch: + # + # - `ConstantMap`/`DimensionMap` dims each form their own slot with a + # contiguous range — a single chunk for a constant, and the span between + # the first and last chunk for a slice. These are already tight (or + # nearly so). + # - Orthogonal `ArrayMap` (fancy) dims each form their own slot with only + # the *distinct* chunk ids the index array actually lands in + # (`np.unique`), never the dense `range(min_chunk, max_chunk + 1)` + # between them. A sparse fancy selection (e.g. two far-apart coordinates) + # would otherwise enumerate every chunk in the bounding box, making + # resolution scale with grid size instead of with the number of selected + # coordinates. + # - Correlated (vindex) `ArrayMap` dims share one *joint* slot holding the + # distinct chunk-coordinate tuples the points actually land in. The + # cartesian product of their per-dimension distinct sets would include + # combinations no point touches — quadratic in the number of selected + # points for a diagonal selection — while the joint distinct set is + # bounded by the point count (see zarr-python gh-4174). + structure = transform.index_array_structure + correlated_dims: list[int] = [] + correlated_chunk_ids: list[np.ndarray[Any, np.dtype[np.intp]]] = [] + slot_dims: list[tuple[int, ...]] = [] + slot_candidates: list[Sequence[tuple[int, ...]]] = [] + for out_dim, m in enumerate(transform.output): + dg = dim_grids[out_dim] + if isinstance(m, ConstantMap): + # Single chunk + coordinate = checked_affine(m.offset, 0, 0) + c = dg.index_to_chunk(coordinate) + slot_dims.append((out_dim,)) + slot_candidates.append(((c,),)) + elif isinstance(m, DimensionMap): + d = m.input_dimension + dim_lo = transform.domain.inclusive_min[d] + dim_hi = transform.domain.exclusive_max[d] + if dim_lo >= dim_hi: + return # empty domain + first_storage = checked_affine(m.offset, m.stride, dim_lo) + if m.stride > 0: + s_min = first_storage + s_max = checked_affine(m.offset, m.stride, dim_hi - 1) + elif m.stride < 0: + s_min = checked_affine(m.offset, m.stride, dim_hi - 1) + s_max = first_storage + else: + s_min = s_max = first_storage + first = dg.index_to_chunk(s_min) + last = dg.index_to_chunk(s_max) + slot_dims.append((out_dim,)) + point_count = dim_hi - dim_lo + chunk_count = last - first + 1 + if point_count < chunk_count: + steps = np.arange(point_count, dtype=np.intp) + storage = checked_affine(first_storage, m.stride, steps) + chunk_ids = dg.indices_to_chunks(storage) + slot_candidates.append([(int(c),) for c in np.unique(chunk_ids)]) + else: + slot_candidates.append([(c,) for c in range(first, last + 1)]) + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap). + # Storage coordinates were already computed for a correlated 1-D map. + storage = ( + array_map_1d[1] + if array_map_1d is not None + else checked_affine(m.offset, m.stride, m.index_array) + ) + if storage.size == 0: + # Empty fancy selection: no coordinates, so no chunks are touched. + return + # Keep the index-array shape: correlated maps broadcast against each + # other below, and raveling first would lose the singleton axes. + chunk_ids = dg.indices_to_chunks(storage) + if structure == "orthogonal": + slot_dims.append((out_dim,)) + slot_candidates.append([(int(c),) for c in np.unique(chunk_ids)]) + else: + # Every index array of a general transform joins one joint + # slot: their chunk ids broadcast over the shared block, so the + # distinct tuples enumerate only combinations some point + # actually touches. + correlated_dims.append(out_dim) + correlated_chunk_ids.append(chunk_ids) + + if len(correlated_dims) == 1: + slot_dims.append((correlated_dims[0],)) + slot_candidates.append([(int(c),) for c in np.unique(correlated_chunk_ids[0])]) + elif len(correlated_dims) >= 2: + # Group the points jointly: distinct rows of the per-point chunk + # coordinates, O(points log points) regardless of grid size. + broadcast = np.broadcast_arrays(*correlated_chunk_ids) + stacked = np.stack([b.ravel() for b in broadcast], axis=1) + joint = np.unique(stacked, axis=0) + slot_dims.append(tuple(correlated_dims)) + slot_candidates.append([tuple(int(c) for c in row) for row in joint]) + + import itertools + + output_rank = len(transform.output) + for combo in itertools.product(*slot_candidates): + chunk_coords_list = [0] * output_rank + for dims, part in zip(slot_dims, combo, strict=True): + for d, c in zip(dims, part, strict=True): + chunk_coords_list[d] = c + chunk_coords = tuple(chunk_coords_list) + + # Build the chunk domain in storage space + chunk_min: list[int] = [] + chunk_max: list[int] = [] + chunk_shift: list[int] = [] + for out_dim, c in enumerate(chunk_coords): + dg = dim_grids[out_dim] + c_start = dg.chunk_offset(c) + c_size = _data_size(dg, c) + chunk_min.append(c_start) + chunk_max.append(c_start + c_size) + chunk_shift.append(-c_start) + + chunk_domain = IndexDomain( + inclusive_min=tuple(chunk_min), + exclusive_max=tuple(chunk_max), + ) + + # Intersect transform with chunk domain + result = transform.intersect(chunk_domain) + if result is None: + continue + + restricted, surviving = result + + # Translate to chunk-local coordinates + local = restricted.translate(tuple(chunk_shift)) + + yield (chunk_coords, local, surviving) + + +def _covers_whole_chunk(transform: IndexTransform, chunk_shape: tuple[int, ...]) -> bool: + """Whether an affine chunk-local transform bijects onto every chunk cell.""" + domain = transform.domain + used_nontrivial_inputs: set[int] = set() + for out_dim, m in enumerate(transform.output): + extent = chunk_shape[out_dim] + if isinstance(m, ConstantMap): + if extent != 1 or m.offset != 0: + return False + elif isinstance(m, DimensionMap): + if abs(m.stride) != 1: + return False + lo = domain.inclusive_min[m.input_dimension] + hi = domain.exclusive_max[m.input_dimension] + if hi <= lo: + if extent != 0: + return False + continue + first = m.offset + m.stride * lo + last = m.offset + m.stride * (hi - 1) + if min(first, last) != 0 or max(first, last) != extent - 1: + return False + if extent > 1: + if m.input_dimension in used_nontrivial_inputs: + return False + used_nontrivial_inputs.add(m.input_dimension) + else: + return False + nontrivial_inputs = {dimension for dimension, extent in enumerate(domain.shape) if extent > 1} + return used_nontrivial_inputs == nontrivial_inputs + + +def _orthogonal_cell_transform( + original: IndexTransform, + restricted: IndexTransform, + survivors: dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]], +) -> IndexTransform: + """Map a compacted orthogonal intersection back to request coordinates.""" + by_input_dimension: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + if isinstance(survivors, dict): + survivor_items = survivors.items() + else: + array_output_dimensions = [ + output_dimension + for output_dimension, output_map in enumerate(original.output) + if isinstance(output_map, ArrayMap) + ] + if len(array_output_dimensions) != 1: + raise ValueError( + "one survivor array requires exactly one orthogonal ArrayMap; " + f"found output dimensions {array_output_dimensions}" + ) + survivor_items = ((array_output_dimensions[0], survivors),) + + for output_dimension, positions in survivor_items: + output_map = original.output[output_dimension] + if not isinstance(output_map, ArrayMap): + raise TypeError( + f"survivors for output dimension {output_dimension} do not describe an ArrayMap" + ) + input_dimension = output_map.dependent_axis + if input_dimension is None: + raise ValueError( + f"output dimension {output_dimension} has no orthogonal input dimension" + ) + by_input_dimension[input_dimension] = np.asarray(positions, dtype=np.intp) + + output: list[ConstantMap | DimensionMap | ArrayMap] = [] + rank = original.input_rank + for input_dimension in range(rank): + positions = by_input_dimension.get(input_dimension) + if positions is None: + output.append(DimensionMap(input_dimension=input_dimension)) + continue + shape = (1,) * input_dimension + (positions.size,) + (1,) * (rank - input_dimension - 1) + output.append( + ArrayMap( + index_array=positions.reshape(shape), + offset=original.domain.inclusive_min[input_dimension], + ) + ) + return IndexTransform(domain=restricted.domain, output=tuple(output)) + + +def _correlated_cell_transform( + original: IndexTransform, + restricted: IndexTransform, + survivors: np.ndarray[Any, np.dtype[np.intp]], +) -> IndexTransform: + """Map compacted correlated points back through the request's row-major domain.""" + positions = np.asarray(survivors, dtype=np.intp) + # Correlated broadcast axes already contribute positional survivor offsets; + # residual affine axes still contribute literal coordinates. Remove only + # the latter origins before unraveling the fully positional flat offsets. + literal_axes = { + output_map.input_dimension + for output_map in original.output + if isinstance(output_map, DimensionMap) + } + origin_offset = 0 + flat_stride = 1 + for input_dimension in range(original.input_rank - 1, -1, -1): + if input_dimension in literal_axes: + origin_offset += original.domain.inclusive_min[input_dimension] * flat_stride + extent = original.domain.shape[input_dimension] + flat_stride *= extent + coordinates = np.unravel_index( + checked_affine(-origin_offset, 1, positions), original.domain.shape + ) + output = tuple( + ArrayMap( + index_array=np.asarray(coordinate, dtype=np.intp), + offset=origin, + ) + for coordinate, origin in zip(coordinates, original.domain.inclusive_min, strict=True) + ) + return IndexTransform(domain=restricted.domain, output=output) + + +def _cell_transform( + original: IndexTransform, + restricted: IndexTransform, + survivors: _OutIndices, +) -> IndexTransform: + """Convert private survivor bookkeeping into a direction-neutral transform.""" + if survivors is None: + return IndexTransform.identity(restricted.domain) + if original.index_array_structure == "general": + if isinstance(survivors, dict): + raise ValueError("general intersections require one shared survivor array") + return _correlated_cell_transform(original, restricted, survivors) + return _orthogonal_cell_transform(original, restricted, survivors) + + +def _iter_chunk_projections( + transform: IndexTransform, + dim_grids: Sequence[DimensionGridLike], +) -> Iterator[ChunkProjection]: + """Convert private intersection results into public paired projections.""" + for chunk_coords, chunk_transform, survivors in _iter_chunk_transform_results( + transform, dim_grids + ): + chunk_min = tuple( + grid.chunk_offset(coord) for grid, coord in zip(dim_grids, chunk_coords, strict=True) + ) + chunk_shape = tuple( + _data_size(grid, coord) for grid, coord in zip(dim_grids, chunk_coords, strict=True) + ) + chunk_domain = IndexDomain( + inclusive_min=chunk_min, + exclusive_max=tuple( + origin + extent for origin, extent in zip(chunk_min, chunk_shape, strict=True) + ), + ) + cell_transform = _cell_transform(transform, chunk_transform, survivors) + synthetic_origin = (0,) * chunk_transform.input_rank + chunk_transform = chunk_transform.translate_domain_to(synthetic_origin) + cell_transform = cell_transform.translate_domain_to(synthetic_origin) + if survivors is not None or any(isinstance(m, ArrayMap) for m in chunk_transform.output): + coverage: ChunkCoverage = "unknown" + elif _covers_whole_chunk(chunk_transform, chunk_shape): + coverage = "full" + else: + coverage = "partial" + yield ChunkProjection( + chunk_coords=chunk_coords, + chunk_domain=chunk_domain, + chunk_transform=chunk_transform, + cell_transform=cell_transform, + coverage=coverage, + ) diff --git a/packages/zarr-indexing/src/zarr_indexing/domain.py b/packages/zarr-indexing/src/zarr_indexing/domain.py new file mode 100644 index 0000000000..a353b81254 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/domain.py @@ -0,0 +1,325 @@ +"""Index domains — rectangular regions in N-dimensional integer space. + +An `IndexDomain` represents the set of valid coordinates for an array or +array view. It is the cartesian product of per-dimension integer ranges:: + + IndexDomain(inclusive_min=(2, 5), exclusive_max=(10, 20)) + # represents {(i, j) : 2 <= i < 10, 5 <= j < 20} + +Unlike NumPy, domains can have **non-zero origins**. After slicing +`arr[5:10]`, the result has origin 5 and shape 5 — coordinates 5 through +9 are valid. This follows the TensorStore convention. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +from zarr_indexing.errors import BoundsCheckError + +if TYPE_CHECKING: + from zarr_indexing.json import IndexDomainJSON + + +@dataclass(frozen=True, slots=True) +class IndexDomain: + """A rectangular region in N-dimensional index space. + + The valid coordinates are the integers in + `[inclusive_min[d], exclusive_max[d])` for each dimension `d`. + + Examples + -------- + >>> domain = IndexDomain(inclusive_min=(2, 5), exclusive_max=(10, 20)) + >>> domain.shape + (8, 15) + + Unlike a NumPy shape, a domain keeps literal coordinates: narrowing to + `[5, 10)` gives a region whose valid coordinates are 5 through 9, not + re-zeroed: + + >>> view = IndexDomain.from_shape((10,)).narrow(slice(5, 10)) + >>> view.origin, view.shape + ((5,), (5,)) + >>> view.contains((5,)), view.contains((0,)) + (True, False) + """ + + inclusive_min: tuple[int, ...] + """The lower corner: each dimension's smallest literal coordinate. May be negative.""" + + exclusive_max: tuple[int, ...] + """Each dimension's upper bound, excluded: valid coordinates end at `exclusive_max - 1`.""" + + labels: tuple[str, ...] | None = None + """Optional per-dimension names; carried through the wire format, never consulted by indexing.""" + # Lazily-memoized shape. Excluded from init/repr/eq/hash: it is derived + # state, not part of the domain's identity. The domain is frozen, so the + # value is computed at most once (see `shape`). `None` is the unset + # sentinel; an empty shape caches as `()`. + _shape: tuple[int, ...] | None = field(default=None, init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + if len(self.inclusive_min) != len(self.exclusive_max): + raise ValueError( + f"inclusive_min and exclusive_max must have the same length. " + f"Got {len(self.inclusive_min)} and {len(self.exclusive_max)}." + ) + for i, (lo, hi) in enumerate(zip(self.inclusive_min, self.exclusive_max, strict=True)): + if lo > hi: + raise ValueError( + f"inclusive_min must be <= exclusive_max for all dimensions. " + f"Dimension {i}: {lo} > {hi}" + ) + if self.labels is not None and len(self.labels) != len(self.inclusive_min): + raise ValueError( + f"labels must have the same length as dimensions. " + f"Got {len(self.labels)} labels for {len(self.inclusive_min)} dimensions." + ) + + @classmethod + def from_shape(cls, shape: tuple[int, ...]) -> IndexDomain: + """Create a domain with origin at zero.""" + return cls( + inclusive_min=(0,) * len(shape), + exclusive_max=shape, + ) + + @property + def ndim(self) -> int: + """Number of dimensions.""" + return len(self.inclusive_min) + + @property + def origin(self) -> tuple[int, ...]: + """The lower corner of the domain — an alias for `inclusive_min`, and may be negative.""" + return self.inclusive_min + + @property + def shape(self) -> tuple[int, ...]: + """Per-dimension extents: `exclusive_max - inclusive_min` for each dimension.""" + cached = self._shape + if cached is None: + cached = tuple( + hi - lo for lo, hi in zip(self.inclusive_min, self.exclusive_max, strict=True) + ) + object.__setattr__(self, "_shape", cached) + return cached + + def contains(self, index: tuple[int, ...]) -> bool: + """Whether the literal coordinate `index` lies inside this domain. + + Coordinates are literal, not NumPy-style offsets: a negative value is + the coordinate itself, valid only if the domain's bounds include it. + A tuple of the wrong length is simply not contained (returns `False`). + """ + if len(index) != self.ndim: + return False + return all( + lo <= idx < hi + for lo, hi, idx in zip(self.inclusive_min, self.exclusive_max, index, strict=True) + ) + + def contains_domain(self, other: IndexDomain) -> bool: + """Whether every coordinate of `other` lies inside this domain. + + An empty `other` within this domain's bounds is contained. A rank + mismatch returns `False` rather than raising. + """ + if other.ndim != self.ndim: + return False + return all( + self_lo <= other_lo and other_hi <= self_hi + for self_lo, self_hi, other_lo, other_hi in zip( + self.inclusive_min, + self.exclusive_max, + other.inclusive_min, + other.exclusive_max, + strict=True, + ) + ) + + def intersect(self, other: IndexDomain) -> IndexDomain | None: + """Return the overlap of this domain with `other`, or `None` if they are disjoint. + + Raises + ------ + ValueError + If the two domains have different ranks. + """ + if other.ndim != self.ndim: + raise ValueError( + f"Cannot intersect domains with different ranks: {self.ndim} vs {other.ndim}" + ) + new_min = tuple( + max(a, b) for a, b in zip(self.inclusive_min, other.inclusive_min, strict=True) + ) + new_max = tuple( + min(a, b) for a, b in zip(self.exclusive_max, other.exclusive_max, strict=True) + ) + if any(lo >= hi for lo, hi in zip(new_min, new_max, strict=True)): + return None + return IndexDomain(inclusive_min=new_min, exclusive_max=new_max) + + def translate(self, offset: tuple[int, ...]) -> IndexDomain: + """Return this domain shifted by `offset` per dimension; the shape is unchanged. + + Offsets may be negative, and the result may have a negative origin. + + Raises + ------ + ValueError + If `offset` does not have one entry per dimension. + """ + if len(offset) != self.ndim: + raise ValueError( + f"Offset must have same length as domain dimensions. " + f"Domain has {self.ndim} dimensions, offset has {len(offset)}." + ) + new_min = tuple(lo + off for lo, off in zip(self.inclusive_min, offset, strict=True)) + new_max = tuple(hi + off for hi, off in zip(self.exclusive_max, offset, strict=True)) + return IndexDomain(inclusive_min=new_min, exclusive_max=new_max) + + def narrow(self, selection: Any) -> IndexDomain: + """Apply a basic selection and return a narrowed domain. + + Indices are absolute coordinates, not NumPy-style offsets: `-3` names + the coordinate `-3`, and is out of bounds unless the domain contains it. + Integer indices produce a length-1 extent. Strided slices are not + supported — use `IndexTransform` for strides. + + Raises + ------ + BoundsCheckError + If a bound lies outside this domain. A slice bound used to be + clamped instead, so `narrow(slice(-3, None))` on `[0, 10)` quietly + returned the whole axis — reading as the NumPy spelling of "the last + three" and answering with something else — and `narrow(slice(20, + 30))` returned a domain its own parent did not contain. The rest of + the algebra states no clamping and no negative wrapping as an + invariant and enforces it; this is the one place that did not. + """ + normalized = _normalize_selection(selection, self.ndim) + new_inclusive_min: list[int] = [] + new_exclusive_max: list[int] = [] + for dim_idx, (sel, dim_lo, dim_hi) in enumerate( + zip(normalized, self.inclusive_min, self.exclusive_max, strict=True) + ): + if isinstance(sel, int): + if sel < dim_lo or sel >= dim_hi: + raise BoundsCheckError( + f"index {sel} is out of bounds for dimension {dim_idx} " + f"with domain [{dim_lo}, {dim_hi})" + ) + new_inclusive_min.append(sel) + new_exclusive_max.append(sel + 1) + else: + start, stop, step = sel.start, sel.stop, sel.step + if step is not None and step != 1: + raise ValueError( + "IndexDomain.narrow only supports step=1 slices. " + f"Got step={step}. Use IndexTransform for strided access." + ) + abs_start = dim_lo if start is None else start + abs_stop = dim_hi if stop is None else stop + for bound, name in ((abs_start, "start"), (abs_stop, "stop")): + if bound < dim_lo or bound > dim_hi: + raise BoundsCheckError( + f"slice {name} {bound} is out of bounds for dimension " + f"{dim_idx} with domain [{dim_lo}, {dim_hi}); indices " + f"here are absolute coordinates, so they are neither " + f"clamped to the domain nor counted from its end" + ) + # An empty interval is legal; a reversed one is the same request + # spelled backwards, and reads as empty rather than as an error. + new_inclusive_min.append(abs_start) + new_exclusive_max.append(max(abs_stop, abs_start)) + return IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + # -- serialization ------------------------------------------------------ + + def to_json(self) -> IndexDomainJSON: + """Convert to the canonical ndsel JSON representation. + + Examples + -------- + >>> IndexDomain(inclusive_min=(0,), exclusive_max=(3,)).to_json() + {'input_inclusive_min': [0], 'input_exclusive_max': [3], 'input_labels': ['']} + """ + from zarr_indexing._wire import emit_labels + + return { + "input_inclusive_min": list(self.inclusive_min), + "input_exclusive_max": list(self.exclusive_max), + "input_labels": emit_labels(self.labels, self.ndim), + } + + @classmethod + def from_json(cls, data: IndexDomainJSON) -> IndexDomain: + """Construct from the canonical ndsel JSON representation. + + The document is validated by the message layer first, exactly as a + transform body is. Reading the keys directly would be a second, + undefended way into the same objects: `int(value)` alone accepts + `3.9`, `"3"` and `True`, and each of those builds a domain that is + not the document's. + + Examples + -------- + >>> domain = IndexDomain.from_json( + ... {"input_inclusive_min": [1], "input_exclusive_max": [4], "input_labels": [""]} + ... ) + >>> (domain.inclusive_min, domain.exclusive_max, domain.shape) + ((1,), (4,), (3,)) + >>> IndexDomain.from_json(domain.to_json()) == domain + True + """ + from zarr_indexing._wire import lower_bound, lower_labels + from zarr_indexing.messages import NdselError, normalize_ndsel + + # The annotation says what a well-formed caller passes; this is a parser + # of documents that arrive from elsewhere, so the shape is checked + # rather than assumed. + if not isinstance(data, dict): # pyright: ignore[reportUnnecessaryIsInstance] + raise NdselError("invalid_json", f"an index domain must be a JSON object, got {data!r}") + body = normalize_ndsel({**data, "kind": "transform"}) + return cls( + inclusive_min=tuple( + lower_bound(b, f"input_inclusive_min[{i}]") + for i, b in enumerate(body["input_inclusive_min"]) + ), + exclusive_max=tuple( + lower_bound(b, f"input_exclusive_max[{i}]") + for i, b in enumerate(body["input_exclusive_max"]) + ), + labels=lower_labels(body["input_labels"]), + ) + + +def _normalize_selection(selection: Any, ndim: int) -> tuple[int | slice, ...]: + """Normalize a basic selection to a tuple of ints/slices with length ndim.""" + if not isinstance(selection, tuple): + selection = (selection,) + result: list[int | slice] = [] + ellipsis_seen = False + for sel in selection: + if sel is Ellipsis: + if ellipsis_seen: + raise IndexError("an index can only have a single ellipsis ('...')") + ellipsis_seen = True + num_missing = ndim - (len(selection) - 1) + result.extend([slice(None)] * num_missing) + else: + result.append(sel) + while len(result) < ndim: + result.append(slice(None)) + if len(result) > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, " + f"but {len(result)} were indexed" + ) + return tuple(result) diff --git a/packages/zarr-indexing/src/zarr_indexing/errors.py b/packages/zarr-indexing/src/zarr_indexing/errors.py new file mode 100644 index 0000000000..efd3b1ecd6 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/errors.py @@ -0,0 +1,67 @@ +"""Canonical index-error types raised by the transform algebra. + +Both subclass the built-in `IndexError`, so an `except IndexError` catch site +keeps working unchanged whichever library raised. + +`zarr.errors` defines classes of the same names, and they are *not* these +objects: `zarr.errors.BoundsCheckError is BoundsCheckError` is false. Catching +zarr's around a call into this package therefore catches nothing but their +shared `IndexError` base. Import these from here. +""" + +from __future__ import annotations + +__all__ = [ + "BoundsCheckError", + "VindexInvalidSelectionError", +] + + +class VindexInvalidSelectionError(IndexError): + """A wrapper `vindex` selection contained a slice. + + Raised by `LazyArray`'s selection validation: the wrapper's vectorized + dialect accepts coordinate selections (integer arrays, with scalars and + an ellipsis) or a single boolean mask, and rejects slices with this + error. Other invalid entries raise plain `IndexError`, and the + engine-level `IndexTransform.vindex` is wider — it accepts residual + slice dimensions without raising. + + Examples + -------- + Raised by the wrapper, not the engine — a slice inside `vindex`: + + >>> import numpy as np + >>> from zarr_indexing import LazyArray + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> view.lazy.vindex[np.array([0, 2]), :] + Traceback (most recent call last): + ... + zarr_indexing.errors.VindexInvalidSelectionError: ... + """ + + +class BoundsCheckError(IndexError): + """A selection addressed coordinates outside the domain being indexed. + + Raised for out-of-domain integer indices, slice bounds, index-array + values, and points passed to `IndexTransform.apply`. Coordinates in this + algebra are literal: they are never clamped, and a negative value below + the domain's `inclusive_min` is out of bounds rather than counted from + the end. + + Examples + -------- + >>> from zarr_indexing import IndexTransform + >>> IndexTransform.from_shape((8,)).apply((9,)) + Traceback (most recent call last): + ... + zarr_indexing.errors.BoundsCheckError: ... + + A negative index is a literal coordinate, not "from the end": + + >>> IndexTransform.from_shape((8,))[-1] + Traceback (most recent call last): + ... + zarr_indexing.errors.BoundsCheckError: ... + """ diff --git a/packages/zarr-indexing/src/zarr_indexing/grid.py b/packages/zarr-indexing/src/zarr_indexing/grid.py new file mode 100644 index 0000000000..20ad3f95c2 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/grid.py @@ -0,0 +1,826 @@ +"""Compact chunk grids and the narrow planner protocol. + +``DimensionGridLike`` describes only the per-axis operations required by +``plan_chunks``. The concrete compact grids below also retain enough metadata +to describe chunk data regions and codec buffer regions without importing +Zarr's array implementation. +""" + +from __future__ import annotations + +import bisect +import itertools +import operator +from dataclasses import dataclass, field +from functools import reduce +from typing import TYPE_CHECKING, Any, Protocol, cast, runtime_checkable + +import numpy as np + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + import numpy.typing as npt + + +class DimensionGridLike(Protocol): + """The per-dimension chunk-mapping surface consumed by chunk resolution. + + Examples + -------- + `EdgeDimensionGrid` provides this surface. Chunk sizes `(2, 3)` tile + source coordinates `[0, 5)`, so index 4 lands in the second chunk: + + >>> grid = EdgeDimensionGrid([2, 3]) + >>> grid.index_to_chunk(4) + 1 + >>> grid.chunk_offset(1), grid.chunk_size(1) + (2, 3) + """ + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the index of the chunk that contains it. + + Implementers must raise `IndexError` when `idx` lies outside `[0, extent)`. + """ + ... + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate at which chunk `chunk_ix` begins.""" + ... + + def chunk_size(self, chunk_ix: int) -> int: + """The declared length of chunk `chunk_ix`, i.e. its codec buffer size along this axis.""" + ... + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk`: map global source indices to chunk indices. + + Implementers must raise `IndexError` if any index lies outside `[0, extent)`. + """ + ... + + +def _bounded_indices(indices: npt.NDArray[np.intp], extent: int) -> npt.NDArray[np.intp]: + """Normalize a vector lookup and enforce the scalar grid bounds.""" + arr = np.asarray(indices, dtype=np.intp) + if arr.size > 0 and (int(arr.min()) < 0 or int(arr.max()) >= extent): + raise IndexError( + f"indices must lie in [0, {extent}); got [{int(arr.min())}, {int(arr.max())}]" + ) + return arr + + +@dataclass(frozen=True) +class FixedDimension: + """Uniform chunk size with a boundary chunk clipped to the axis extent. + + Examples + -------- + Chunks of size 3 on an axis of extent 10 give 4 chunks. The last chunk + still declares a codec buffer of 3 but holds only 1 valid element: + + >>> dim = FixedDimension(size=3, extent=10) + >>> dim.nchunks + 4 + >>> dim.index_to_chunk(7) + 2 + >>> dim.chunk_size(3), dim.data_size(3) + (3, 1) + """ + + size: int + """The declared chunk length along this axis; every chunk's codec buffer size.""" + + extent: int + """The axis length in global source coordinates.""" + + nchunks: int = field(init=False, repr=False) + """Derived: the number of chunks holding data within `extent`.""" + + ngridcells: int = field(init=False, repr=False) + """Derived: the number of declared grid cells; equals `nchunks` for a fixed dimension.""" + + def __post_init__(self) -> None: + if self.size < 0: + raise ValueError(f"FixedDimension size must be >= 0, got {self.size}") + if self.extent < 0: + raise ValueError(f"FixedDimension extent must be >= 0, got {self.extent}") + if self.size == 0 and self.extent > 0: + raise ValueError( + "FixedDimension size must be > 0 when extent is nonzero; " + f"got size {self.size} and extent {self.extent}" + ) + nchunks = 0 if self.size == 0 else (self.extent + self.size - 1) // self.size + object.__setattr__(self, "nchunks", nchunks) + object.__setattr__(self, "ngridcells", nchunks) + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to its chunk index (`idx // size`). + + Raises `IndexError` when `idx` lies outside `[0, extent)`. + """ + if idx < 0 or idx >= self.extent: + raise IndexError(f"index {idx} is out of bounds for extent {self.extent}") + return 0 if self.size == 0 else idx // self.size + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate where chunk `chunk_ix` begins (`chunk_ix * size`). + + Not bounds-checked: chunk indices past the last chunk extrapolate linearly. + """ + return chunk_ix * self.size + + def chunk_size(self, chunk_ix: int) -> int: + """The declared chunk length, `size` for every chunk. + + The boundary chunk is not clipped here; use `data_size` for the valid data length. + """ + return self.size + + def data_size(self, chunk_ix: int) -> int: + """The number of valid data elements in chunk `chunk_ix`, clipped to `extent`. + + Interior chunks report `size`; the boundary chunk reports the remainder, and chunk + indices at or past `nchunks` report 0. + """ + if self.size == 0: + return 0 + return max(0, min(self.size, self.extent - chunk_ix * self.size)) + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk` over an array of global source indices. + + Raises `IndexError` if any index lies outside `[0, extent)`. + """ + arr = _bounded_indices(indices, self.extent) + if self.size == 0: + return np.zeros_like(arr) + return arr // self.size + + def with_extent(self, new_extent: int) -> FixedDimension: + """Return a copy with the same chunk size and the axis extent set to `new_extent`.""" + return FixedDimension(size=self.size, extent=new_extent) + + def resize(self, new_extent: int) -> FixedDimension: + """Return a copy resized to `new_extent`; the fixed chunk size covers any new extent.""" + return FixedDimension(size=self.size, extent=new_extent) + + @property + def size_repr(self) -> str: + """The chunk size rendered as a scalar for `ChunkGrid.__repr__`.""" + return str(self.size) + + +@dataclass(frozen=True, init=False) +class VaryingDimension: + """Explicit chunk edge lengths, with trailing data clipped to ``extent``. + + Examples + -------- + Edges `(2, 3, 5)` clipped to extent 9: the last chunk declares 5 but + holds only 4 valid elements, and index 4 lands in the second chunk: + + >>> dim = VaryingDimension(edges=(2, 3, 5), extent=9) + >>> dim.nchunks + 3 + >>> dim.index_to_chunk(4) + 1 + >>> dim.chunk_offset(2) + 5 + >>> dim.chunk_size(2), dim.data_size(2) + (5, 4) + """ + + edges: tuple[int, ...] + """The declared per-chunk edge lengths, in order; codec buffer sizes, unclipped.""" + + cumulative: tuple[int, ...] + """Prefix sums of `edges`; derived, and what index lookups binary-search.""" + + extent: int + """The axis length in global source coordinates; at most the sum of `edges`.""" + nchunks: int = field(init=False, repr=False) + """Derived: the number of chunks holding data within `extent`.""" + + ngridcells: int = field(init=False, repr=False) + """Derived: the number of declared edges; exceeds `nchunks` when trailing cells are empty.""" + + def __init__(self, edges: Sequence[int], extent: int) -> None: + edges_tuple = tuple(edges) + if not edges_tuple: + raise ValueError("VaryingDimension edges must not be empty") + if any(edge <= 0 for edge in edges_tuple): + raise ValueError(f"All edge lengths must be > 0, got {edges_tuple}") + cumulative = tuple(itertools.accumulate(edges_tuple)) + if extent < 0: + raise ValueError(f"VaryingDimension extent must be >= 0, got {extent}") + if extent > cumulative[-1]: + raise ValueError( + f"VaryingDimension extent {extent} exceeds sum of edges {cumulative[-1]}" + ) + object.__setattr__(self, "edges", edges_tuple) + object.__setattr__(self, "cumulative", cumulative) + object.__setattr__(self, "extent", extent) + nchunks = 0 if extent == 0 else bisect.bisect_left(cumulative, extent) + 1 + object.__setattr__(self, "nchunks", nchunks) + object.__setattr__(self, "ngridcells", len(edges_tuple)) + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the chunk whose edge interval contains it. + + Raises `IndexError` when `idx` lies outside `[0, extent)`. + """ + if idx < 0 or idx >= self.extent: + raise IndexError(f"index {idx} is out of bounds for extent {self.extent}") + return bisect.bisect_right(self.cumulative, idx) + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate where chunk `chunk_ix` begins (sum of prior edges).""" + return self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 + + def chunk_size(self, chunk_ix: int) -> int: + """The declared edge length of chunk `chunk_ix`. + + Trailing chunks are not clipped to `extent` here; use `data_size` for that. + """ + return self.edges[chunk_ix] + + def data_size(self, chunk_ix: int) -> int: + """The number of valid data elements in chunk `chunk_ix`, clipped to `extent`. + + Grid cells that lie entirely at or past `extent` report 0. + """ + offset = self.chunk_offset(chunk_ix) + return max(0, min(self.edges[chunk_ix], self.extent - offset)) + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk` over an array of global source indices. + + Raises `IndexError` if any index lies outside `[0, extent)`. + """ + arr = _bounded_indices(indices, self.extent) + return np.searchsorted(self.cumulative, arr, side="right") + + def with_extent(self, new_extent: int) -> VaryingDimension: + """Return a copy with the same edges re-clipped to `new_extent`. + + The existing edges must already cover the new extent; raises `ValueError` when + `new_extent` exceeds the sum of edges. Use `resize` to grow past the edges. + """ + if self.cumulative[-1] < new_extent: + raise ValueError( + f"VaryingDimension edge sum {self.cumulative[-1]} is less than new extent " + f"{new_extent}" + ) + return VaryingDimension(self.edges, extent=new_extent) + + def resize(self, new_extent: int) -> VaryingDimension: + """Return a copy resized to `new_extent`. + + Shrinking (or growing within the existing edges) keeps the edges and re-clips them; + growing past the sum of edges appends one new trailing edge covering the remainder. + """ + if new_extent == self.extent: + return self + if new_extent > self.cumulative[-1]: + return VaryingDimension((*self.edges, new_extent - self.cumulative[-1]), new_extent) + return VaryingDimension(self.edges, extent=new_extent) + + @property + def size_repr(self) -> str: + """The edge lengths rendered as a tuple for `ChunkGrid.__repr__`.""" + return repr(self.edges) + + +@runtime_checkable +class DimensionGrid(Protocol): + """Structural interface shared by the compact dimension grids. + + Examples + -------- + `FixedDimension` satisfies the protocol structurally: + + >>> dim = FixedDimension(size=2, extent=5) + >>> isinstance(dim, DimensionGrid) + True + >>> dim.nchunks, dim.extent + (3, 5) + >>> dim.with_extent(4).nchunks + 2 + """ + + @property + def nchunks(self) -> int: + """The number of chunks holding data within `extent`.""" + ... + + @property + def ngridcells(self) -> int: + """The number of declared grid cells; may exceed `nchunks` when trailing cells are empty.""" + ... + + @property + def extent(self) -> int: + """The axis length in global source coordinates.""" + ... + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the chunk index that contains it. + + Implementers must raise `IndexError` when `idx` lies outside `[0, extent)`. + """ + ... + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate at which chunk `chunk_ix` begins.""" + ... + + def chunk_size(self, chunk_ix: int) -> int: + """The declared (codec buffer) length of chunk `chunk_ix`, never clipped to `extent`.""" + ... + + def data_size(self, chunk_ix: int) -> int: + """The valid data length of chunk `chunk_ix`, clipped to `extent` at the boundary.""" + ... + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk`; must raise `IndexError` for indices outside `[0, extent)`.""" + ... + + def with_extent(self, new_extent: int) -> DimensionGrid: + """Return a grid with the existing chunk layout re-clipped to `new_extent`. + + Implementers must not invent new grid cells: raise `ValueError` when the declared + layout cannot cover `new_extent`. + """ + ... + + def resize(self, new_extent: int) -> DimensionGrid: + """Return a grid covering `new_extent`, extending the chunk layout when it must grow.""" + ... + + @property + def size_repr(self) -> str: + """A compact rendering of the chunk sizes, used by `ChunkGrid.__repr__`.""" + ... + + +@dataclass(frozen=True) +class ChunkSpec: + """A chunk's valid data region and its full codec buffer shape. + + Examples + -------- + The last chunk of a size-10 axis chunked by 3 holds one valid element + (`slices`), while its codec buffer still spans 3: + + >>> spec = ChunkGrid.from_sizes((10,), (3,))[3] + >>> spec.slices + (slice(9, 10, 1),) + >>> spec.shape, spec.codec_shape + ((1,), (3,)) + >>> spec.is_boundary + True + """ + + slices: tuple[slice, ...] + """Per-dimension bounds of the valid data region, in global source coordinates.""" + + codec_shape: tuple[int, ...] + """The declared (codec buffer) chunk shape, unclipped by the array extent.""" + + @property + def shape(self) -> tuple[int, ...]: + """The shape of the valid data region described by `slices`. + + Smaller than `codec_shape` on boundary chunks, where the array extent clips the chunk. + """ + return tuple(chunk_slice.stop - chunk_slice.start for chunk_slice in self.slices) + + @property + def is_boundary(self) -> bool: + """Whether the valid data region is smaller than the full codec buffer on any axis.""" + return self.shape != self.codec_shape + + +@dataclass(frozen=True) +class ChunkGrid: + """A concrete regular or rectilinear arrangement of chunks for one array. + + Examples + -------- + A `(3, 4)` array with `(2, 2)` chunks has a `(2, 2)` grid whose bottom + row of chunks is clipped to one valid row of data: + + >>> grid = ChunkGrid.from_sizes((3, 4), (2, 2)) + >>> grid.grid_shape + (2, 2) + >>> grid.chunk_sizes + ((2, 1), (2, 2)) + >>> spec = grid[1, 0] + >>> spec.shape, spec.codec_shape, spec.is_boundary + ((1, 2), (2, 2), True) + """ + + dimensions: tuple[DimensionGrid, ...] + """One per-axis grid, each mapping that axis's source indices to chunks.""" + + _is_regular: bool = field(init=False, repr=False) + + def __post_init__(self) -> None: + object.__setattr__( + self, + "_is_regular", + all(isinstance(dimension, FixedDimension) for dimension in self.dimensions), + ) + + def __repr__(self) -> str: + sizes = ", ".join(dimension.size_repr for dimension in self.dimensions) + shape = tuple(dimension.extent for dimension in self.dimensions) + return f"ChunkGrid(chunk_sizes=({sizes}), array_shape={shape})" + + @classmethod + def from_sizes( + cls, array_shape: Sequence[int], chunk_sizes: Sequence[int | Sequence[int]] + ) -> ChunkGrid: + """Build a grid from an array shape and one chunk-size spec per dimension. + + An `int` entry gives a fixed chunk size along that axis; a sequence of ints gives + explicit per-chunk edge lengths. A uniform sequence consistent with the axis extent + collapses to a fixed dimension, so the result may report `is_regular`. + + Parameters + ---------- + array_shape : Sequence[int] + The array extent along each dimension, in global source coordinates. + chunk_sizes : Sequence[int | Sequence[int]] + Per-dimension chunk layout: a single size or explicit edge lengths. + """ + extents = _shape_tuple(array_shape) + if len(extents) != len(chunk_sizes): + raise ValueError( + f"array_shape has {len(extents)} dimensions but chunk_sizes has " + f"{len(chunk_sizes)} dimensions" + ) + dimensions: list[DimensionGrid] = [] + for dimension_spec, extent in zip(chunk_sizes, extents, strict=True): + if isinstance(dimension_spec, int): + dimensions.append(FixedDimension(size=dimension_spec, extent=extent)) + else: + edges = tuple(dimension_spec) + if not edges: + raise ValueError("Each dimension must have at least one chunk") + if ( + edges[0] > 0 + and all(edge == edges[0] for edge in edges) + and (extent == sum(edges) or len(edges) == (extent + edges[0] - 1) // edges[0]) + ): + dimensions.append(FixedDimension(size=edges[0], extent=extent)) + else: + dimensions.append(VaryingDimension(edges, extent=extent)) + return cls(dimensions=tuple(dimensions)) + + @property + def ndim(self) -> int: + """The number of dimensions.""" + return len(self.dimensions) + + @property + def is_regular(self) -> bool: + """Whether every dimension uses a single fixed chunk size. + + False when any axis carries explicit (rectilinear) per-chunk edge lengths. + """ + return self._is_regular + + @property + def grid_shape(self) -> tuple[int, ...]: + """The number of data-bearing chunks along each dimension.""" + return tuple(dimension.nchunks for dimension in self.dimensions) + + @property + def chunk_shape(self) -> tuple[int, ...]: + """The uniform declared chunk shape of a regular grid. + + Raises `ValueError` for rectilinear grids, which have no single chunk shape; + use `grid[coords]` for per-chunk sizes instead. + """ + if not self.is_regular: + raise ValueError( + "chunk_shape is only available for regular chunk grids. " + "Use grid[coords] for per-chunk sizes." + ) + return tuple( + dimension.size for dimension in self.dimensions if isinstance(dimension, FixedDimension) + ) + + @property + def chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension tuples of each chunk's valid data length. + + Boundary chunks report their clipped extent, not the declared codec size. + """ + return tuple( + tuple(dimension.data_size(index) for index in range(dimension.nchunks)) + for dimension in self.dimensions + ) + + def __getitem__(self, coords: int | tuple[int, ...]) -> ChunkSpec | None: + """Look up the `ChunkSpec` at the given chunk coordinates (grid cells, not indices). + + Returns `None` when any coordinate falls outside the grid; raises `ValueError` + when the number of coordinates does not match `ndim`. The spec's slices are in + global source coordinates. + """ + if isinstance(coords, int): + coords = (coords,) + if len(coords) != self.ndim: + raise ValueError( + f"Expected {self.ndim} coordinate(s) for a {self.ndim}-d chunk grid, " + f"got {len(coords)}." + ) + slices: list[slice] = [] + codec_shape: list[int] = [] + for dimension, index in zip(self.dimensions, coords, strict=True): + if index < 0 or index >= dimension.nchunks: + return None + offset = dimension.chunk_offset(index) + slices.append(slice(offset, offset + dimension.data_size(index), 1)) + codec_shape.append(dimension.chunk_size(index)) + return ChunkSpec(tuple(slices), tuple(codec_shape)) + + def __iter__(self) -> Iterator[ChunkSpec]: + """Yield a `ChunkSpec` for every data-bearing chunk in row-major (C) order.""" + for coords in itertools.product( + *(range(dimension.nchunks) for dimension in self.dimensions) + ): + spec = self[coords] + if spec is not None: + yield spec + + def all_chunk_coords( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[int, ...]]: + """Iterate chunk coordinates over a rectangular grid region in row-major (C) order. + + `origin` defaults to the grid origin and `selection_shape` to the rest of the grid. + The region is not bounds-checked: an oversized region yields coordinates outside + the grid, which `__getitem__` resolves to `None`. + """ + origin_parsed = (0,) * self.ndim if origin is None else tuple(origin) + selection_shape_parsed = ( + tuple( + grid_size - coordinate + for coordinate, grid_size in zip(origin_parsed, self.grid_shape, strict=True) + ) + if selection_shape is None + else tuple(selection_shape) + ) + return itertools.product( + *( + range(coordinate, coordinate + size) + for coordinate, size in zip(origin_parsed, selection_shape_parsed, strict=True) + ) + ) + + def iter_chunk_regions( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[slice, ...]]: + """Yield each chunk's valid-data slices, in global source coordinates. + + Covers the same region as `all_chunk_coords`, silently skipping coordinates + that fall outside the grid. + """ + for coords in self.all_chunk_coords(origin=origin, selection_shape=selection_shape): + spec = self[coords] + if spec is not None: + yield spec.slices + + def get_nchunks(self) -> int: + """The total number of data-bearing chunks: the product of `grid_shape` (1 if 0-d).""" + return reduce(operator.mul, (dimension.nchunks for dimension in self.dimensions), 1) + + def update_shape(self, new_shape: tuple[int, ...]) -> ChunkGrid: + """Return a grid resized to `new_shape` by resizing each dimension. + + Fixed axes keep their chunk size; rectilinear axes gain one trailing edge when + grown past their declared edges. Raises `ValueError` when `new_shape` does not + have `ndim` entries. + """ + if len(new_shape) != self.ndim: + raise ValueError( + f"new_shape has {len(new_shape)} dimensions but chunk grid has {self.ndim} dimensions" + ) + return ChunkGrid( + dimensions=tuple( + dimension.resize(new_extent) + for dimension, new_extent in zip(self.dimensions, new_shape, strict=True) + ) + ) + + +class EdgeDimensionGrid: + """An explicitly edge-based grid for coordinate-origin examples and planners. + + Examples + -------- + Chunk sizes `(2, 3)` tile source coordinates `[0, 5)`; lookups outside + that range raise: + + >>> grid = EdgeDimensionGrid([2, 3]) + >>> grid.num_chunks, grid.extent + (2, 5) + >>> grid.index_to_chunk(2) + 1 + >>> grid.index_to_chunk(5) + Traceback (most recent call last): + ... + IndexError: index 5 is out of bounds for an axis of extent 5 + """ + + __slots__ = ("_offsets", "sizes") + + sizes: tuple[int, ...] + """The length of each chunk along the axis, in order; every entry is positive.""" + + def __init__(self, sizes: Sequence[int]) -> None: + """Build a one-axis grid from explicit per-chunk sizes. + + Every size must be positive; raises `ValueError` otherwise. A zero-length axis + is spelled as an empty sequence (no chunks), not as a zero size. + + Parameters + ---------- + sizes : Sequence[int] + The length of each chunk along the axis, in order. + """ + normalized = tuple(int(size) for size in sizes) + for index, size in enumerate(normalized): + if size <= 0: + raise ValueError( + f"chunk sizes must be positive; got {size} at position {index} of {normalized}. " + "A zero-length axis is spelled as no chunks at all: EdgeDimensionGrid(())" + ) + self.sizes = normalized + offsets: np.ndarray[Any, np.dtype[np.intp]] = np.zeros(len(normalized) + 1, dtype=np.intp) + if normalized: + np.cumsum(np.asarray(normalized, dtype=np.intp), out=offsets[1:]) + self._offsets = offsets + + @property + def num_chunks(self) -> int: + """The number of chunks along the axis.""" + return len(self.sizes) + + @property + def extent(self) -> int: + """The axis length in global source coordinates: the sum of all chunk sizes.""" + return int(self._offsets[-1]) + + def __repr__(self) -> str: + return f"EdgeDimensionGrid(sizes={self.sizes})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, EdgeDimensionGrid): + return NotImplemented + return self.sizes == other.sizes + + def __hash__(self) -> int: + return hash((type(self).__name__, self.sizes)) + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the chunk whose interval contains it. + + Raises `IndexError` when `idx` lies outside `[0, extent)`. + """ + if idx < 0 or idx >= self.extent: + raise IndexError(f"index {idx} is out of bounds for an axis of extent {self.extent}") + return int(np.searchsorted(self._offsets, idx, side="right")) - 1 + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate where chunk `chunk_ix` begins. + + Raises `IndexError` when `chunk_ix` lies outside `[0, num_chunks)`. + """ + if chunk_ix < 0 or chunk_ix >= len(self.sizes): + raise IndexError( + f"chunk index {chunk_ix} is out of bounds for {len(self.sizes)} chunks" + ) + return int(self._offsets[chunk_ix]) + + def chunk_size(self, chunk_ix: int) -> int: + """The length of chunk `chunk_ix`; every chunk holds data, so no boundary clipping applies. + + Raises `IndexError` when `chunk_ix` lies outside `[0, num_chunks)`. + """ + if chunk_ix < 0 or chunk_ix >= len(self.sizes): + raise IndexError( + f"chunk index {chunk_ix} is out of bounds for {len(self.sizes)} chunks" + ) + return self.sizes[chunk_ix] + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk` over an array of global source indices. + + Raises `IndexError` if any index lies outside `[0, extent)`. + """ + arr = _bounded_indices(indices, self.extent) + return (np.searchsorted(self._offsets, arr, side="right") - 1).astype(np.intp) + + +def _shape_tuple(shape: Sequence[int]) -> tuple[int, ...]: + result = tuple(int(size) for size in shape) + if any(size < 0 for size in result): + raise ValueError(f"shape entries must be non-negative; got {result}") + return result + + +def _entry_kind(entry: Any) -> str: + if isinstance(entry, (int, np.integer)) and not isinstance(entry, bool): + return "int" + if isinstance(entry, (str, bytes)): + return "neither" + try: + iter(cast("Iterable[Any]", entry)) + except TypeError: + return "neither" + return "sequence" + + +def dimension_grids_from_chunks( + chunks: Sequence[int] | Sequence[Sequence[int]], shape: Sequence[int] +) -> tuple[DimensionGrid, ...]: + """Build compact dimensions from regular sizes or explicit per-axis edges. + + Examples + -------- + One integer per dimension builds fixed grids, ready for `plan_chunks`: + + >>> from zarr_indexing import IndexTransform, plan_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> [type(grid).__name__ for grid in grids] + ['FixedDimension', 'FixedDimension'] + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> [p.chunk_coords for p in plan] + [(0, 0), (0, 1)] + """ + shape_t = _shape_tuple(shape) + entries: tuple[Any, ...] = tuple(chunks) + if len(entries) != len(shape_t): + raise ValueError( + f"chunks must have one entry per dimension; got {len(entries)} entries for shape {shape_t}" + ) + + conventions = ( + "chunks must be either a uniform chunk shape (one integer per dimension) " + "or per-axis chunk sizes (one sequence of integers per dimension)" + ) + kinds = [_entry_kind(entry) for entry in entries] + neither = [(axis, entries[axis]) for axis, kind in enumerate(kinds) if kind == "neither"] + if neither: + described = ", ".join(f"{entry!r} at dimension {axis}" for axis, entry in neither) + verb = "is" if len(neither) == 1 else "are" + raise ValueError(f"{conventions}; {described} {verb} neither") + + integer_count = sum(kind == "int" for kind in kinds) + if entries and integer_count == len(entries): + dimensions: list[DimensionGrid] = [] + for entry, extent in zip(entries, shape_t, strict=True): + size = int(entry) + if size <= 0: + raise ValueError(f"chunk shape entries must be positive; got {size}") + dimensions.append(FixedDimension(size=size, extent=extent)) + return tuple(dimensions) + if integer_count: + raise ValueError(f"{conventions}, not a mixture; got {entries!r}") + + dimensions = [] + for axis, (entry, extent) in enumerate(zip(entries, shape_t, strict=True)): + elements: tuple[Any, ...] = tuple(cast("Iterable[Any]", entry)) + if any( + not isinstance(element, (int, np.integer)) or isinstance(element, bool) + for element in elements + ): + raise ValueError( + f"per-axis chunk sizes must be integers; dimension {axis} has {entry!r}" + ) + edges = tuple(int(element) for element in elements) + total = sum(edges) + if total != extent: + raise ValueError( + f"per-axis chunk sizes for dimension {axis} sum to {total}, but the array extent is {extent}" + ) + if extent == 0 and all(edge == 0 for edge in edges): + dimensions.append(FixedDimension(size=0, extent=0)) + continue + if any(edge <= 0 for edge in edges): + raise ValueError(f"chunk sizes must be positive; got {edges}") + dimensions.append(VaryingDimension(edges=edges, extent=extent)) + return tuple(dimensions) diff --git a/packages/zarr-indexing/src/zarr_indexing/json.py b/packages/zarr-indexing/src/zarr_indexing/json.py new file mode 100644 index 0000000000..8bf42c74a5 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/json.py @@ -0,0 +1,166 @@ +"""The canonical ndsel wire vocabulary, and the rules for lowering it. + +This is the **engine layer**. Where `messages.py` is pure JSON→JSON and imposes +no array constraints, this module holds the JSON shapes a canonical ndsel body +takes (spec section 4.3, as produced by `zarr_indexing.messages.normalize_ndsel`) +together with the lowering rules that turn one into the numpy-backed engine +representation. + +The conversions themselves are **methods on the types**, since each type owns +its one serialization: `IndexTransform.to_json` / `from_json`, +`IndexDomain.to_json` / `from_json`, and `to_json` on each output map kind, +with `output_index_map_from_json` in `zarr_indexing.output_map` dispatching the +wire's tagged union back to the right kind. This module is what they share. + +Three engine constraints live **here and only here**: + +- **Finite bounds.** An `IndexDomain` addresses a finite array, so a canonical + body carrying a `"-inf"`/`"+inf"` bound cannot be lowered; `from_json` raises. +- **Implicit bounds lower by value.** The `[n]`-bracket implicit/explicit flag + is a message-layer concern; the engine keeps only the integer value. +- **Integer `index_array` content.** The message layer carries `index_array` + verbatim (the spec defers its shape and type), so lowering is where a float, + boolean or string array is rejected — as an `NdselError`, rather than + truncating `[0.9, 1.9]` to cells 0 and 1 or leaking a raw NumPy error. + +## The `index_array` wire format (and the degenerate-collapse it documents) + +ndsel and TensorStore both **reject** an output map that carries *both* +`input_dimension` and `index_array`; `input_dimension` belongs to affine +(`single_input_dimension`) maps. The in-memory `ArrayMap` matches: what a map +depends on is read from its full-rank array's shape (its non-singleton axes), +so there is nothing to reconstruct on load. On serialize (`to_json`): + +1. An all-singleton `index_array` (size 1) selects a single coordinate + regardless of input, so it is **collapsed to a `constant` map** + `{offset: offset + stride*value}`. The size-1 input dimension stays in the + domain, unconsumed — a valid transform. The selection layer already builds + such maps as `ConstantMap` (`output_map.array_map_or_constant`); this covers + hand-built transforms. +2. An **empty** `index_array` (size 0) collapses the same way, to + `{offset: 0}`. It names no cell, and it can only be empty because an input + dimension is — the full-rank invariant makes every axis either 1 or the + domain's extent — so nothing is ever read through it and the emptiness is + carried by the domain, which is emitted separately. TensorStore does the + same: `t[ts.d[0][[]]]` is `out[0] = 0`, emitted as `{}`. Emitting the array + instead would produce a document neither implementation could load, because + `ndarray.tolist()` renders every empty array as `[]` once the leading axis + is the zero-length one, and nested lists cannot spell the shape back — + `[[]]` is `(1, 0)` and nothing spells `(0, 1)`. +3. Non-degenerate `index_array` maps are emitted with their array and bounds + only. + +""" + +from __future__ import annotations + +from typing import Any, Required, TypedDict + +# --------------------------------------------------------------------------- +# TypedDict definitions (canonical JSON shapes) +# --------------------------------------------------------------------------- + +# An `index_array` serializes via `ndarray.tolist()`, so it is a nested list of +# ints whose nesting depth equals the array rank. +NestedIntList = list[Any] + +# A canonical *lowered* body carries only finite integer bounds, but the JSON +# shape admits the full ndsel `bound` grammar: an explicit int / sentinel, or a +# one-element implicit `[value]` array. +IndexValueJSON = int | str +BoundJSON = int | str | list[IndexValueJSON] + + +class IndexDomainJSON(TypedDict, total=False): + """Canonical JSON representation of an IndexDomain. + + Examples + -------- + >>> doc: IndexDomainJSON = { + ... "input_inclusive_min": [0], + ... "input_exclusive_max": [4], + ... "input_labels": ["x"], + ... } + >>> from zarr_indexing import IndexDomain + >>> IndexDomain.from_json(doc).shape + (4,) + """ + + input_inclusive_min: Required[list[BoundJSON]] + """Per-dimension lower bounds; `"-inf"` is legal on the wire but cannot be lowered.""" + + input_exclusive_max: Required[list[BoundJSON]] + """Per-dimension exclusive upper bounds; `"+inf"` is legal on the wire but cannot be lowered.""" + + input_labels: Required[list[str]] + """Per-dimension names; the empty string marks an unlabeled dimension.""" + + +class OutputIndexMapJSON(TypedDict, total=False): + """Canonical JSON representation of a single output index map. + + Exactly one of three forms (distinguished by which fields are present): + + - `{"offset": 5}` — constant + - `{"offset": 0, "stride": 1, "input_dimension": 0}` — single_input_dimension + - `{"offset": 0, "stride": 1, "index_array": [...], + "index_array_bounds": ["-inf", "+inf"]}` — index_array + + Examples + -------- + >>> from zarr_indexing import output_index_map_from_json + >>> constant: OutputIndexMapJSON = {"offset": 5} + >>> output_index_map_from_json(constant) + ConstantMap(offset=5) + >>> affine: OutputIndexMapJSON = {"offset": 0, "stride": 2, "input_dimension": 1} + >>> output_index_map_from_json(affine) + DimensionMap(input_dimension=1, offset=0, stride=2) + """ + + offset: int + """Constant term; alone it is the whole constant form.""" + + stride: int + """Multiplier applied to the input coordinate or to each `index_array` value.""" + + input_dimension: int + """The input dimension the single_input_dimension form reads.""" + + index_array: NestedIntList + """Nested lists of output coordinates, one nesting level per input dimension.""" + + index_array_bounds: list[IndexValueJSON] + """Bounds the `index_array` values are promised to lie in; `["-inf", "+inf"]` if unconstrained.""" + + +class IndexTransformJSON(TypedDict, total=False): + """Canonical JSON representation of an IndexTransform (spec section 4.3). + + Examples + -------- + >>> doc: IndexTransformJSON = { + ... "input_rank": 1, + ... "input_inclusive_min": [0], + ... "input_exclusive_max": [2], + ... "input_labels": [""], + ... "output": [{"offset": 1, "stride": 2, "input_dimension": 0}], + ... } + >>> from zarr_indexing import IndexTransform + >>> IndexTransform.from_json(doc).domain.shape + (2,) + """ + + input_rank: Required[int] + """The number of input dimensions; the bounds and labels lists match it in length.""" + + input_inclusive_min: Required[list[BoundJSON]] + """Per-dimension lower bounds; `"-inf"` is legal on the wire but cannot be lowered.""" + + input_exclusive_max: Required[list[BoundJSON]] + """Per-dimension exclusive upper bounds; `"+inf"` is legal on the wire but cannot be lowered.""" + + input_labels: Required[list[str]] + """Per-dimension names; the empty string marks an unlabeled dimension.""" + + output: Required[list[OutputIndexMapJSON]] + """One output map per output dimension.""" diff --git a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py new file mode 100644 index 0000000000..950a97b25e --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py @@ -0,0 +1,1365 @@ +"""`LazyArray` — TensorStore-style lazy indexing over array-like sources. + +`LazyArray` wraps a source with `shape`, `dtype`, and basic integer/slice +`__getitem__`, whose reads can be lowered through NumPy system memory. It adds +a `.lazy` accessor whose indexing operations build up an +[`IndexTransform`](transform.md) instead of reading data: + +```python +view = LazyArray(source).lazy[10:50, ::2].lazy.oindex[[3, 1, 1], :] +view.shape # known without touching the data +values = view.result() +``` + +Nothing is read until `result()` (or `__array__`, or an eager `__getitem__`). +Every `.lazy` operation is metadata-only. Composition does not accumulate +layers: a view of a view is still a single transform and retains its reader. + +Parts +----- +A `LazyArray` carries a **partitioning** of the array it wraps: a grid of boxes +that a read is broken into. `parts()` walks those boxes as they fall through the +view, yielding a [`Partition`](#zarr_indexing.lazy_array.Partition) per box. Its +paired projection describes the chunk-local read and where its cells land in the +request; `view` carries that partition's transform. `result()` allocates one +fresh output buffer, then reads each partition once through the selected reader +into the final buffer or an owned temporary for fancy placement. + +The part view's transform directly addresses its raw wrapped array. The paired +projection deliberately retains the chunk-local frame; both travel together in +the `ReadContext` passed to the reader. + +The partitioning is discovered from the wrapped array at construction — first +`read_chunk_sizes` (zarr's clipped per-axis sizes, sharding-aware), then +`chunks`, read as per-axis sizes if its entries are sequences and as a uniform +box shape if they are integers. Those attribute names belong to the wrapped +array; this API refers only to parts. An array that advertises neither gets a +single whole-array part, and resolving it reads the whole view through its +selected reader in one pass. + +`with_parts` replaces the partitioning without touching the data or the view: + +```python +view.with_parts((64, 64)) # uniform boxes, tail clipped +view.with_parts_per_axis(((3, 3, 1),)) # explicit per-axis sizes +view.unpartitioned() # one whole-array part; resolve in one shot +``` + +Repartitioning changes how the read is divided, not what `result()` returns. +Parts that do not align with the source's own boxes are permitted and can be +useful (to bound peak memory, or to batch small reads); they cost extra I/O but +do not affect correctness. + +Readers +------- +Every wrapper carries a reader that owns the backend-specific request. The +transform answers **which values?** and is independent of the backend; the +reader answers **how does this backend obtain them?** and must preserve the +complete transform exactly. Readers do not define indexing semantics, +partitioning, scheduling, or result ownership. The conservative +`LazyArray(source)` uses `basic_reader`, which needs only basic slicing. +`LazyArray.from_numpy(array)` explicitly opts into `numpy_reader` for direct +NumPy indexing. `with_reader()` replaces the reader without reading or changing +the view metadata. The reader object is shared by all derived views and their +parts. Consumers may materialize part views concurrently; `LazyArray` does not +serialize calls, so a stateful reader must synchronize its own mutable state. + +Both built-in readers lower through NumPy system memory. They do not implicitly +transfer device arrays. A device source requires an explicit custom reader that +performs any needed transfer into the supplied system-memory output buffer. + +Boxes and queries +----------------- +A selection is either **rectangular** — an interval and a stride per dimension, +which is what basic indexing composes to at any depth — or a **query**, an +explicit list of coordinates, which is what `oindex`, `vindex`, and masks +produce and which subsequent basic indexing cannot undo. `is_box` reports the +category and `bounding_box()` reports the storage region touched: the exact +interval per dimension for a box, a hull for a query. A box is only *dense* in +that interval when every entry of `strides()` is 1. The distinction is +structural rather than an optimization; [the design +notes](../design-notes.md) describe why it matters to consumers of a selection. + +The positional dialect +---------------------- +Selections on `LazyArray` are **positional, NumPy-style**: index 0 is the first +element of the current view, `-1` is the last, boolean masks must match the +view's shape, and every index is bounds-checked against the view. + +This differs deliberately from `zarr.Array.lazy[...]`, which exposes the +**literal** TensorStore dialect: a zarr view keeps the coordinate system of the +array it came from, so after `v = arr.lazy[10:50]` the first element of `v` is +`v[10]` and a negative index is out of bounds rather than counted from the end. +That dialect suits zarr, where a view's coordinates stay comparable with the +parent array's. `LazyArray` is a duck array and has to behave like the array it +wraps to be usable as a NumPy drop-in or as a dask source, so it re-zeroes its +coordinates on every view and uses positions. `zarr_indexing.boundary` performs +the translation between the two. + +Two more NumPy rules the dialect keeps, in every mode: + +- A scalar integer drops its axis. Any non-boolean object implementing Python's + `SupportsIndex` protocol is accepted as one, including in slice bounds and + steps; an `__int__` method alone is deliberately not enough. A scalar is a + basic index wherever it appears, applied before any advanced index rather + than broadcast against one. So + `lazy.oindex[0]` has the shape of `x[0]`, `lazy.oindex[0, [1, 2], :]` means + `x[0][numpy.ix_([1, 2], ...)]`, and `lazy.oindex[0, 1, 2]` and + `lazy.vindex[0, 1, 2]` are both zero-rank. Use a length-1 list to keep an + axis. +- Advanced indices are placed as NumPy places them. For a `vindex` selection + that leaves some axes unindexed, the gathered dimensions sit where the + coordinate arrays sat when those arrays are adjacent, and lead when a slice + separates them — so `lazy.vindex[..., i, j]` has shape + `(x.shape[0], *broadcast)`, matching `x[..., i, j]`. + +Materializing on fallback +------------------------- +`LazyArray` implements `__array__` but deliberately implements neither +`__array_ufunc__` nor `__array_function__`. A NumPy *function* given a view +therefore materializes the whole thing through +`__array__` and works on the resulting array: `numpy.sum(view)`, +`numpy.add(view, 1)` and `numpy.stack([view, view])` all do, and so does +`numpy.ones(view.shape) + view`, where the ndarray on the left dispatches. + +Python's arithmetic *operators* do not: `view + 1` raises `TypeError`, because +the wrapper defines no arithmetic dunders and an `int` has nothing to dispatch +to. Both facts follow from the same intent — laziness here applies to indexing, +not to building a deferred compute graph — and a `LazyArray` is not a drop-in +for arithmetic on a large array either way. Use `.lazy[...]` to narrow the view +first, or pass the wrapper to `dask.array.from_array` so that dask owns the +compute graph. + +Ownership +--------- +`result()` always allocates fresh system memory before reading through the +selected reader. A `numpy.ma` source keeps its mask by receiving a masked +output buffer; other source-specific array types do not survive materializing. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import operator +import uuid +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Protocol, cast + +import numpy as np + +from zarr_indexing.boundary import ( + SelectionMode, + normalize_positional_selection, + split_scalar_axes, +) +from zarr_indexing.chunk_resolution import ( + ChunkProjection, + plan_chunks, +) +from zarr_indexing.grid import DimensionGrid, FixedDimension, dimension_grids_from_chunks +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.reader import ( + ReadContext, + Reader, + basic_reader, + numpy_reader, +) +from zarr_indexing.transform import ( + IndexTransform, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + SelectFn = Callable[[Any, SelectionMode], "LazyArray"] + +__all__ = ["LazyArray", "Partition"] + +# Above this many bytes, the no-dask token fallback describes an array +# structurally instead of digesting its contents. See `_wrapped_token`. +_TOKEN_DIGEST_LIMIT = 1 << 20 + + +def _invoke_reader( + reader: Reader, + source: Any, + context: ReadContext, + out: np.ndarray[Any, Any], +) -> None: + """Invoke a reader and enforce its in-place return contract.""" + returned = reader.read_into(source, context, out) + if returned is not None: + raise TypeError(f"reader.read_into must return None, got {type(returned).__name__}") + + +def _is_correlated(transform: IndexTransform) -> bool: + """True when the transform gathers a list of points rather than an outer product.""" + return transform.index_array_structure == "general" + + +class ArrayLike(Protocol): + """The surface `LazyArray` needs from the array it wraps.""" + + @property + def shape(self) -> tuple[int, ...]: ... + @property + def dtype(self) -> Any: ... + def __getitem__(self, key: Any) -> Any: ... + + +# NumPy's dtype-specialized ``__getitem__`` overloads do not structurally match +# the deliberately broad protocol above under strict type checking. Accept an +# ndarray explicitly so users do not have to erase its type with ``cast(Any, …)``. +_WrappedArray = ArrayLike | np.ndarray[Any, Any] + + +# --------------------------------------------------------------------------- # +# Partition discovery +# --------------------------------------------------------------------------- # + + +def _read_source_attribute(array: Any, name: str) -> Any: + """Read a partition-describing attribute, treating any failure as "absent". + + Discovery inspects an object we did not write. A missing attribute is the + common case, but zarr raises an `AttributeError` subclass from + `read_chunk_sizes` on a lazy view, and other backends compute the attribute + lazily and may fail for their own reasons. Any failure here means "this + array does not advertise a partitioning", never a hard error. + """ + try: + return getattr(array, name, None) + # Guarded properties (e.g. zarr's LazyViewError) and broken foreign + # attributes may raise anything; discovery must degrade to None. + except Exception: + return None + + +def _discover_parts(array: Any, shape: tuple[int, ...]) -> tuple[DimensionGrid, ...] | None: + """Resolve the partitioning advertised by `array`, or None for one whole part. + + Discovery parses external input: an attribute that does not describe a + partitioning of `shape` means "this object does not advertise one I + understand", and the array is treated as unpartitioned rather than rejected. + A partitioning is an I/O strategy, so reading the whole array is always a + correct fallback. `with_parts` is a public API and validates strictly. + """ + declared = _read_source_attribute(array, "read_chunk_sizes") + if declared is None: + declared = _read_source_attribute(array, "chunks") + if declared is None: + return None + try: + return dimension_grids_from_chunks(declared, shape) + except (ValueError, TypeError): + return None + + +def _whole_array_grids(shape: tuple[int, ...]) -> tuple[DimensionGrid, ...]: + """A partitioning with a single part covering the whole array.""" + return tuple(FixedDimension(size=extent, extent=extent) for extent in shape) + + +# --------------------------------------------------------------------------- # +# The lowering engine +# --------------------------------------------------------------------------- # + + +def _is_identity_transform(transform: IndexTransform, shape: tuple[int, ...]) -> bool: + """True when `transform` maps every coordinate of `shape` to itself. + + Structural rather than an `==` against `IndexTransform.from_shape`: an + `ArrayMap` holds an ndarray, so equality on two transforms that both carry + one would try to take the truth value of an array. + """ + domain = transform.domain + if domain.inclusive_min != (0,) * len(shape) or domain.exclusive_max != shape: + return False + if len(transform.output) != len(shape): + return False + return all( + isinstance(m, DimensionMap) and m.input_dimension == i and m.offset == 0 and m.stride == 1 + for i, m in enumerate(transform.output) + ) + + +# --------------------------------------------------------------------------- # +# Partitions +# --------------------------------------------------------------------------- # + + +@dataclass(frozen=True, slots=True, eq=False) +class _PartOwner: + """Opaque identity shared only by one view and the parts it prepared.""" + + +def _partition_out_selection( + cell_transform: IndexTransform, +) -> tuple[Any, ...]: + """Lower ``cell_transform`` to NumPy selectors on the request buffer.""" + domain = cell_transform.domain + if _is_correlated(cell_transform): + correlated_selectors: list[np.ndarray[Any, np.dtype[np.intp]]] = [] + for output_map in cell_transform.output: + if isinstance(output_map, ConstantMap): + coordinates = np.full(domain.shape, output_map.offset, dtype=np.intp) + elif isinstance(output_map, DimensionMap): + input_dimension = output_map.input_dimension + axis = np.arange( + domain.inclusive_min[input_dimension], + domain.exclusive_max[input_dimension], + dtype=np.intp, + ) + shape = ( + (1,) * input_dimension + + (axis.size,) + + ((1,) * (domain.ndim - input_dimension - 1)) + ) + coordinates = np.broadcast_to(axis.reshape(shape), domain.shape) + coordinates = output_map.offset + output_map.stride * coordinates + else: + coordinates = output_map.offset + output_map.stride * np.broadcast_to( + output_map.index_array, domain.shape + ) + correlated_selectors.append(np.asarray(coordinates, dtype=np.intp)) + return tuple(correlated_selectors) + + selectors: list[int | slice | np.ndarray[Any, np.dtype[np.intp]]] = [] + n_array_maps = sum(isinstance(output_map, ArrayMap) for output_map in cell_transform.output) + for output_map in cell_transform.output: + if isinstance(output_map, ConstantMap): + selectors.append(output_map.offset) + elif isinstance(output_map, DimensionMap): + input_dimension = output_map.input_dimension + lo = domain.inclusive_min[input_dimension] + hi = domain.exclusive_max[input_dimension] + selectors.append( + slice( + output_map.offset + output_map.stride * lo, + output_map.offset + output_map.stride * hi, + output_map.stride, + ) + ) + else: + selectors.append( + (output_map.offset + output_map.stride * output_map.index_array.ravel()).astype( + np.intp + ) + ) + if n_array_maps > 1: + axes = [ + np.asarray([selector], dtype=np.intp) + if isinstance(selector, int) + else ( + np.arange(selector.start, selector.stop, selector.step, dtype=np.intp) + if isinstance(selector, slice) + else selector + ) + for selector in selectors + ] + return np.ix_(*axes) + return tuple(selectors) + + +def _out_selection_cell_count(selection: tuple[Any, ...], out_shape: tuple[int, ...]) -> int: + """How many cells of an array of shape `out_shape` a `Partition.out_selection` writes. + + Counted from the selectors' own shapes, so nothing is read and no index + array is materialized. The selectors are slices and integer arrays: the + slices contribute their lengths, and the arrays broadcast against each other + exactly as NumPy's advanced indexing broadcasts them, whether they arrive as + an open mesh (`numpy.ix_`) or as parallel coordinates (`unravel_index`). + """ + total = 1 + array_shapes: list[tuple[int, ...]] = [] + if len(selection) != len(out_shape): + raise AssertionError( + f"a partition addressed {len(selection)} of the view's {len(out_shape)} " + "dimensions; this is a bug in zarr-indexing's partition walk" + ) + for selector, extent in zip(selection, out_shape, strict=True): + if isinstance(selector, slice): + start: Any = selector.start + stop: Any = selector.stop + step: Any = selector.step + if step is None and start is not None and stop is not None and 0 <= start <= stop: + # The shape a partition walk actually produces: a concrete, + # forward, in-bounds interval. Sized directly, so the common + # path allocates neither a tuple nor a range. + total *= int(stop) - int(start) + else: + total *= len(range(*selector.indices(extent))) + else: + array_shapes.append(tuple(int(s) for s in np.shape(selector))) + if len(array_shapes) > 0: + total *= math.prod(np.broadcast_shapes(*array_shapes)) + return total + + +@dataclass(frozen=True, kw_only=True) +class Partition: + """One box of a `LazyArray`'s partitioning, as it falls through the view. + + Yielded by [`LazyArray.parts`][zarr_indexing.lazy_array.LazyArray.parts]. + The parts of a view tile it exactly and disjointly: assembling every + `view.result()` at its `out_selection` reproduces the whole view's + `result()`, and each part can be resolved independently and concurrently. + Derived parts retain the same reader object; a shared stateful reader owns + synchronization for concurrent calls. + + A consumer that needs the plan before materialization can prepare it once + and reuse the same immutable parts for both scheduling and assembly: + + ```python + parts = tuple(view.parts()) + schedule(part.base_coords for part in parts) + values = view.result(parts=parts) + ``` + + Prepared parts are owned by the exact view that created them and must tile + it completely. Passing parts from another view, even an equivalent one, is + rejected without reading; omitting a part is likewise rejected rather than + returning a partly initialized result. + + Attributes + ---------- + projection + The source-independent description of this part. Its paired + `chunk_transform` and `cell_transform` share one compact synthetic + domain, mapping each selected cell to chunk-local storage and request + coordinates respectively. This is the authoritative placement model; + `base_coords` and `is_complete` are conveniences derived from it. + base_coords + Which box of the base partitioning this is, one coordinate per dimension + of the wrapped array. + box + The box itself, in the global storage coordinates of the wrapped + array: one `[inclusive_min, exclusive_max)` interval per dimension. It + describes the whole partition cell, while `view.bounding_box()` is the + global hull of only the selected values in that cell. For a nested or + repartitioned view this box may be narrower than + `projection.chunk_domain`. + view + A `LazyArray` covering exactly the cells of the view that live in this + box. Its transform directly addresses its raw wrapped `array`; only the + projection's `chunk_transform` is chunk-local. Resolving the view reads + the box once through its selected reader. Named `view` rather than + `array` because `LazyArray.array` is the opposite thing — the raw + wrapped source — and the two sat next to each other meaning inverses. + out_selection + Where `view.result()` belongs in an array of the whole view's shape — a + NumPy index tuple with one entry per dimension of the view, usable + directly as `out[part.out_selection] = ...`. + is_complete + Whether the view covers the whole box. Useful to a writer deciding + between a blind overwrite and a read-modify-write. Fancy projections + report `False` because their coverage is deliberately `unknown` until + duplicate-aware proof is added. + + Examples + -------- + Assembling every part's result at its `out_selection` reproduces the view: + + >>> import numpy as np + >>> source = np.arange(12).reshape(3, 4) + >>> view = LazyArray.from_numpy(source).with_parts((2, 2)) + >>> out = np.empty(view.shape, dtype=view.dtype) + >>> for part in view.parts(): + ... out[part.out_selection] = part.view.result() + >>> bool((out == source).all()) + True + """ + + projection: ChunkProjection + box: tuple[tuple[int, int], ...] + view: LazyArray + out_selection: tuple[Any, ...] + _owner: _PartOwner | None = field(default=None, repr=False, compare=False) + + @property + def base_coords(self) -> tuple[int, ...]: + """Coordinates of this partition in the selected base grid.""" + return self.projection.chunk_coords + + @property + def is_complete(self) -> bool: + """Whether the projection proves it covers the entire selected cell.""" + return self.projection.coverage == "full" + + +def _validate_prepared_parts(parts: Sequence[Partition], out_shape: tuple[int, ...]) -> None: + """Require `parts` to address every output cell exactly once. + + Prepared parts are caller-supplied input, so a plan that does not tile the + view is a `ValueError`, not an assertion about this library's own walk. + """ + coverage = np.zeros(out_shape, dtype=np.bool_) + addressed = 0 + try: + for part in parts: + # Name a rank mismatch explicitly instead of letting NumPy treat + # omitted selectors as implicit full slices. + addressed += _out_selection_cell_count(part.out_selection, out_shape) + if all(isinstance(selector, slice) for selector in part.out_selection): + # The common box part: plain assignment, no pointwise walk. + coverage[part.out_selection] = True + else: + # `logical_or.at` applies duplicate advanced coordinates one by + # one instead of buffering them as ordinary advanced indexing + # would. + np.logical_or.at(coverage, part.out_selection, True) + except (AssertionError, IndexError, TypeError, ValueError) as error: + raise ValueError("prepared parts do not tile the view exactly") from error + if addressed != math.prod(out_shape) or not np.all(coverage): + raise ValueError("prepared parts do not tile the view exactly") + + +# --------------------------------------------------------------------------- # +# Tokenization +# --------------------------------------------------------------------------- # + + +def _wrapped_token(array: Any) -> Any: + """A token for the wrapped array. + + In order of preference: the array's own `__dask_tokenize__`; + `dask.base.tokenize` when dask is importable (imported lazily — this package + never requires it); otherwise a local fallback that digests the contents of + a small array. + + The two environments do not agree, and neither is a translation of the + other: a token taken with dask installed is meaningless to a process without + it, and the reverse. A token is an identifier within one process, not a + portable name. + + Above `_TOKEN_DIGEST_LIMIT` the local fallback has nothing left to identify + the contents with — reading them is exactly what a token call must not do — + so it declines to claim equality at all and returns a value that matches + nothing, including itself. A cache keyed on it misses; the alternative, a + structural description, is a cache that hands one array's result to a + different array of the same shape and dtype. + """ + hook = getattr(array, "__dask_tokenize__", None) + if hook is not None: + try: + return hook() + # A token must never raise; fall through to the structural fallback. + except Exception: # pragma: no cover - a hook that refuses to run + pass + try: + # dask is an optional peer, never a dependency of this package, so it is + # imported here and its absence is ordinary. + from dask.base import tokenize # pyright: ignore[reportMissingImports] + except ImportError: + pass + else: + return tokenize(array) + + shape = tuple(int(s) for s in getattr(array, "shape", ())) + dtype = getattr(array, "dtype", None) + structural = (type(array).__qualname__, shape, str(dtype)) + # A token nothing can equal, for when the contents cannot be identified. It + # is the shape and dtype that would otherwise be mistaken for an identity, + # so they are kept alongside it for a reader looking at a graph. + unidentified = (*structural, "unidentified", uuid.uuid4().hex) + + # Decide whether to digest the contents from the *declared* size. Measuring + # it by converting first would read the whole array — a multi-gigabyte store + # pulled into memory by a token call, which is the opposite of the point. + itemsize = getattr(dtype, "itemsize", None) + if not isinstance(itemsize, int) or itemsize * math.prod(shape) > _TOKEN_DIGEST_LIMIT: + return unidentified + try: + contents = np.ascontiguousarray(array) + # A token must never raise; an unreadable source is simply unidentified. + except Exception: + return unidentified + return (*structural, hashlib.sha256(contents.tobytes()).hexdigest()) + + +# --------------------------------------------------------------------------- # +# The wrapper +# --------------------------------------------------------------------------- # + + +class LazyArray: + """A lazily-indexable view over a system-memory/basic-indexing source. + + Wrapping neither copies nor reads the wrapped array at construction time. + Indexing through `.lazy` composes an `IndexTransform` and returns another + `LazyArray`; `result()` materializes. + + Selections use the **positional NumPy dialect** and reads are broken up + along a **partitioning** discovered from the wrapped array. Every derived + view retains its reader; that reader receives the complete projected + transform once per part. See the module docstring, which also covers how the + dialect differs from `zarr.Array.lazy` and why every non-indexing NumPy + operation materializes the view. + + This wrapper describes **reads**. It defines no `__setitem__`, so + assigning into a view raises `TypeError`. Writing belongs to the + consumer: plan the selection with + [`plan_chunks`][zarr_indexing.chunk_resolution.plan_chunks] and own the + read-modify-write, since chunk atomicity and concurrent-writer policy are + the backend's to decide, not an indexing plan's. + + Parameters + ---------- + array + The array to wrap. It must expose `shape`, `dtype`, and `__getitem__` + with basic (integer/slice) indexing; `__setitem__` is not required, so + a read-only source wraps as well as a writable one. Its partitioning, + if it advertises one, is discovered here; use `with_parts` to choose + a different one. + This conservative constructor selects `basic_reader`; use `from_numpy` + for a NumPy array or `with_reader` to select another backend adapter. + + Examples + -------- + >>> import numpy as np + >>> source = np.arange(12).reshape(3, 4) + >>> view = LazyArray.from_numpy(source).with_parts((2, 2)).lazy[1:, ::2] + >>> view.shape + (2, 2) + >>> view.result() + array([[ 4, 6], + [ 8, 10]]) + """ + + __slots__ = ("_array", "_part_owner", "_parts", "_reader", "_transform", "_window") + + def __init__(self, array: _WrappedArray) -> None: + """Wrap `array` without reading it; parameters are documented on the class. + + The only validation here is the `numpy.matrix` rejection (`TypeError`). + """ + if isinstance(array, np.matrix): + # `np.matrix` keeps every result two-dimensional, so `m[1]` has shape + # `(1, n)` where every other array-like gives `(n,)`. A view's shape + # comes from the transform, which follows NumPy's rule, so the two + # disagree on every rank-reducing selection. Refused at the door + # rather than resolved into a shape the view did not promise. + raise TypeError( + "numpy.matrix cannot be wrapped: it never reduces rank, so a " + "view's shape and its result would disagree. Convert it first, " + "with numpy.asarray(m)." + ) + shape = tuple(int(s) for s in array.shape) + self._array = array + self._window: tuple[slice, ...] | None = None + self._transform = IndexTransform.from_shape(shape) + self._parts = _discover_parts(array, shape) + self._reader = basic_reader + self._part_owner = _PartOwner() + + @classmethod + def from_numpy(cls, array: np.ndarray[Any, Any]) -> LazyArray: + """Wrap a NumPy array with its explicitly selected optimized reader.""" + if not isinstance(cast(object, array), np.ndarray): + raise TypeError( + f"LazyArray.from_numpy requires a numpy.ndarray, got {type(array).__name__}" + ) + return cls(array).with_reader(numpy_reader) + + @classmethod + def _derive( + cls, + array: _WrappedArray, + transform: IndexTransform, + parts: tuple[DimensionGrid, ...] | None, + window: tuple[slice, ...] | None, + reader: Reader, + ) -> LazyArray: + """Build a wrapper sharing `array` but carrying a new transform or partitioning.""" + view = cls.__new__(cls) + view._array = array + # Views re-zero their coordinate system: the positional dialect means a + # view's first element is at position 0 whatever it was sliced from. + view._transform = transform.translate_domain_to((0,) * transform.input_rank) + view._parts = parts + view._window = window + view._reader = reader + view._part_owner = _PartOwner() + return view + + @property + def _base_shape(self) -> tuple[int, ...]: + """The shape of what this wrapper treats as its base array.""" + if self._window is None: + return tuple(int(s) for s in self._array.shape) + return tuple(s.stop - s.start for s in self._window) + + # -- array-like surface ------------------------------------------------- + + @property + def array(self) -> _WrappedArray: + """The wrapped array.""" + return self._array + + @property + def base_shape(self) -> tuple[int, ...]: + """The shape the partitioning is expressed in — not this view's shape. + + `with_parts` and `with_parts_per_axis` describe boxes of the array being + read, not of the view reading it, so a narrowed view still partitions + the extents named here. For a part's own `array`, this is the part's + box, which is why the same call means different sizes there. Without + somewhere to read it, the frame in force could only be inferred from an + error message. + """ + return self._base_shape + + @property + def transform(self) -> IndexTransform: + """The composed transform from this view's coordinates to storage.""" + return self._transform + + @property + def shape(self) -> tuple[int, ...]: + """The shape of this view — the transform's input domain, not the source's.""" + return self._transform.domain.shape + + @property + def ndim(self) -> int: + """Number of dimensions of this view — the transform's input rank.""" + return self._transform.input_rank + + @property + def size(self) -> int: + """Total number of elements in this view (the product of `shape`).""" + return math.prod(self.shape) + + @property + def dtype(self) -> Any: + """The wrapped array's dtype; views never change it.""" + return self._array.dtype + + @property + def reader(self) -> Reader: + """The backend adapter used when this view materializes.""" + return self._reader + + def with_reader(self, reader: Reader) -> LazyArray: + """Return the same metadata view resolved through `reader`.""" + if not callable(getattr(reader, "read_into", None)): + raise TypeError(f"reader.read_into must be callable, got {type(reader).__name__}") + return LazyArray._derive( + self._array, + self._transform, + self._parts, + self._window, + reader, + ) + + # -- shape of the selection --------------------------------------------- + + @property + def is_box(self) -> bool: + """Whether this view selects a rectangular region rather than a point list. + + True exactly when the composed transform's output maps are all + `ConstantMap` or `DimensionMap` — no `ArrayMap`. Such a selection is + affine and monotone along every axis, so it is described completely by + an interval and a stride per dimension: + [`bounding_box`][zarr_indexing.lazy_array.LazyArray.bounding_box] + together with + [`strides`][zarr_indexing.lazy_array.LazyArray.strides]. Basic indexing, + at any depth of composition, stays a box; one `oindex`, `vindex`, or + mask anywhere in the chain makes the selection a query permanently. + + A box is dense — every cell of its bounding box selected — only when + every stride is 1. A strided box covers its hull sparsely: + `lazy[10:50, ::4]` selects 40x20 cells out of a 40x77 hull, so a + consumer that reads the whole hull and discards the rest transfers 3.85x + the data it needs. Check `strides` before treating a box as a single + slab read. + + The distinction lets a consumer decide between a slab read and a + gather; see [the design notes](../design-notes.md) for why it is a + category rather than an optimization. + + Examples + -------- + >>> import numpy as np + >>> array = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> (array.lazy[1:, ::2].is_box, array.lazy.oindex[[2, 0], :].is_box) + (True, False) + """ + return not any(isinstance(m, ArrayMap) for m in self._transform.output) + + def bounding_box(self) -> tuple[tuple[int, int], ...] | None: + """The storage region this view touches, one interval per storage dimension. + + Defined for any selection, box or not, as the hull: the smallest + `[inclusive_min, exclusive_max)` interval per dimension of the array + this view reads from that contains every coordinate the selection + reaches. + + The hull is dense — every cell in it selected — only for a box whose + every stride is 1. A strided box selects a sublattice of its hull (pair + this with [`strides`][zarr_indexing.lazy_array.LazyArray.strides] to + describe it fully), and a query's hull is a superset that can be + arbitrarily loose: `oindex[[0, 999]]` has a 1000-wide hull over two + rows. + + Returns + ------- + tuple of (int, int), or None + One interval per storage dimension, or `None` when the view is + empty (`size == 0`) and so touches no coordinate at all, leaving no + interval to report. + + Notes + ----- + The coordinates directly address the raw `array` this view exposes. + Consequently, partition views report source-global hulls; + [`Partition.box`][zarr_indexing.lazy_array.Partition] separately gives + the whole global partition cell rather than only the selected hull. + + Examples + -------- + >>> import numpy as np + >>> array = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> array.lazy[1:, ::2].bounding_box() + ((1, 3), (0, 3)) + >>> array.lazy.oindex[[2, 0], :].bounding_box() + ((0, 3), (0, 4)) + >>> array.lazy[1:1].bounding_box() is None + True + """ + if self.size == 0: + return None + domain = self._transform.domain + bounds: list[tuple[int, int]] = [] + for m in self._transform.output: + if isinstance(m, ConstantMap): + bounds.append((m.offset, m.offset + 1)) + elif isinstance(m, DimensionMap): + d = m.input_dimension + first = m.offset + m.stride * domain.inclusive_min[d] + last = m.offset + m.stride * (domain.exclusive_max[d] - 1) + bounds.append((min(first, last), max(first, last) + 1)) + else: + coords = m.offset + m.stride * m.index_array + bounds.append((int(coords.min()), int(coords.max()) + 1)) + return tuple(bounds) + + def strides(self) -> tuple[int, ...] | None: + """The step between selected coordinates, one per storage dimension. + + Together with `bounding_box()`, this fully describes a box selection: + `bounding_box()` gives the interval per dimension, `strides()` gives the + step per dimension. A stride of 1 means every cell of the hull along + that dimension is selected; `k` means every `k`-th. Dimensions fixed by + an integer index report 1 — they span a single coordinate. + + Returns + ------- + tuple of int, or None + One positive stride per storage dimension, or `None` when + [`is_box`][zarr_indexing.lazy_array.LazyArray.is_box] is false: a + query's coordinates are a lookup table and have no step. An empty + box still reports its strides even though + [`bounding_box`][zarr_indexing.lazy_array.LazyArray.bounding_box] + returns `None`, because the step is a property of the selection's + shape, not of the (empty) region it touches. + + Notes + ----- + Magnitudes only. A reversing view (`lazy[::-1]`) selects the same set of + coordinates as the equivalent forward view, so it reports the same + bounding box and the same strides. The traversal direction is recorded + in the transform, not in this description of the region touched. A + consumer that needs the order reads the transform, or reverses the block + it gets back. + + Examples + -------- + >>> import numpy as np + >>> array = LazyArray.from_numpy(np.arange(24).reshape(4, 6)) + >>> (array.lazy[1:, ::2].bounding_box(), array.lazy[1:, ::2].strides()) + (((1, 4), (0, 5)), (1, 2)) + >>> array.lazy[2, ::3].strides() + (1, 3) + >>> array.lazy.oindex[[2, 0], :].strides() is None + True + """ + if not self.is_box: + return None + return tuple( + 1 if isinstance(m, ConstantMap) else abs(m.stride) for m in self._transform.output + ) + + # -- partitioning ------------------------------------------------------- + + def with_parts(self, parts: Sequence[int]) -> LazyArray: + """Return the same view, read in uniform boxes of shape `parts`. + + One integer per dimension of `base_shape`, with the trailing box in each + dimension clipped to the extent. The transform, the wrapped array, and + therefore `result()` are all unchanged; only the boxes the read is + broken into differ. Nothing is copied and nothing is read. + + For per-axis sizes see + [`with_parts_per_axis`][zarr_indexing.lazy_array.LazyArray.with_parts_per_axis], + and to read in one pass see + [`unpartitioned`][zarr_indexing.lazy_array.LazyArray.unpartitioned]. + The three were one parameter whose meaning was decided by inspecting the + type of what it was given, which left no way to ask for one of them and + be told when you had spelled it wrong. + + Parameters + ---------- + parts + The box shape, one integer per dimension of `base_shape`. + + Returns + ------- + LazyArray + The same view with a new partitioning. + + Raises + ------ + ValueError + If `parts` has the wrong length or contains a non-positive extent. + Uniform part sizes must remain positive even for a zero-length + axis; use `with_parts_per_axis` for the accepted explicit zero-axis + spellings. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> [part.base_coords for part in view.with_parts((2, 3)).parts()] + [(0, 0), (0, 1), (1, 0), (1, 1)] + """ + entries = self._part_entries(parts, "with_parts") + if any(isinstance(entry, Sequence) for entry in entries): + raise ValueError( + "with_parts takes one integer per dimension; for per-axis box " + "sizes use with_parts_per_axis" + ) + return self._with_grids(dimension_grids_from_chunks(entries, self._base_shape)) + + def with_parts_per_axis(self, sizes: Sequence[Sequence[int]]) -> LazyArray: + """Return the same view, read in boxes of explicitly listed sizes. + + The dask convention: one sequence of box extents per dimension of + `base_shape`, each summing to that dimension's extent. Use it when the + boxes are not uniform — a partitioning discovered from a store, or one + whose last box differs by more than clipping. + + Parameters + ---------- + sizes + One sequence of box extents per dimension of `base_shape`. + + Returns + ------- + LazyArray + The same view with a new partitioning. + + Raises + ------ + ValueError + If `sizes` has the wrong length, contains a negative extent, uses a + zero extent on a nonempty axis, or declares sizes that do not sum + to `base_shape`. On a zero-length axis, `()`, `(0,)`, and repeated + zeros all describe no chunks. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> [part.box for part in view.with_parts_per_axis(((1, 2), (4,))).parts()] + [((0, 1), (0, 4)), ((1, 3), (0, 4))] + """ + entries = self._part_entries(sizes, "with_parts_per_axis") + return self._with_grids(dimension_grids_from_chunks(entries, self._base_shape)) + + @staticmethod + def _part_entries(parts: Sequence[Any], method: str) -> tuple[Any, ...]: + """Materialize a partitioning argument, naming a non-iterable a ValueError. + + Both partitioning methods document ValueError for malformed input; a + bare integer would otherwise surface as a TypeError from iteration. + """ + try: + return tuple(parts) + except TypeError as error: + raise ValueError( + f"{method} takes one entry per dimension of base_shape; got {parts!r}" + ) from error + + def unpartitioned(self) -> LazyArray: + """Return the same view, read in one pass. + + `result()` still allocates its owned output buffer first, then calls the + reader once with the whole projected transform. `parts()` still yields a + single part covering everything. + + Returns + ------- + LazyArray + The same view with no partitioning. + """ + return self._with_grids(None) + + def _with_grids(self, grids: tuple[DimensionGrid, ...] | None) -> LazyArray: + return LazyArray._derive(self._array, self._transform, grids, self._window, self._reader) + + def parts(self) -> Iterator[Partition]: + """Iterate the base partitioning, projected through this view. + + Single-use: this is a generator, so it is consumed by the first walk and + a second `for` over the same object yields nothing. Call `parts()` again + for a fresh walk, or keep a `list` of it if you need to revisit. + + Yields one [`Partition`][zarr_indexing.lazy_array.Partition] per box the + view actually touches. The parts tile the view exactly and disjointly, + and each carries a `LazyArray` that can be resolved on its own: in + another thread, in another order, or not at all. Those views share this + view's reader, and `LazyArray` does not serialize calls, so a stateful + reader must synchronize its own mutable state. + + A wrapper with no partitioning (see `with_parts`) yields a single part + covering the whole array. + + Yields + ------ + Partition + One per touched box, in the resolver's own order. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)).with_parts((2, 2)) + >>> part = next(view.lazy[:, 1:].parts()) + >>> (part.base_coords, part.view.shape, part.is_complete) + ((0, 0), (2, 1), False) + """ + base_shape = self._base_shape + grids = self._parts if self._parts is not None else _whole_array_grids(base_shape) + rank = len(base_shape) + + if self._window is None: + plan_transform = self._transform + else: + plan_transform = self._transform.translate(tuple(-item.start for item in self._window)) + + for projection in plan_chunks(plan_transform, grids): + base_coords = projection.chunk_coords + local = projection.chunk_transform + origin = tuple(grid.chunk_offset(c) for grid, c in zip(grids, base_coords, strict=True)) + extent = tuple(grid.data_size(c) for grid, c in zip(grids, base_coords, strict=True)) + if origin == (0,) * rank and extent == base_shape: + # The part is the whole base: lowering directly against the + # source beats materializing a block that is the source. + window = self._window + elif self._window is None: + window = tuple(slice(o, o + e) for o, e in zip(origin, extent, strict=True)) + else: + window = tuple( + slice(w.start + o, w.start + o + e) + for w, o, e in zip(self._window, origin, extent, strict=True) + ) + # The global box, computed from the origin directly rather than from + # `window`: a part covering the whole base carries no window (so + # nothing is pre-materialized) but still sits somewhere concrete. + if self._window is None: + global_origin = origin + else: + global_origin = tuple( + w.start + o for w, o in zip(self._window, origin, strict=True) + ) + yield Partition( + projection=projection, + box=tuple((o, o + e) for o, e in zip(global_origin, extent, strict=True)), + view=LazyArray._derive( + self._array, + local.translate(global_origin), + None, + window, + self._reader, + ), + out_selection=_partition_out_selection(projection.cell_transform), + _owner=self._part_owner, + ) + + # -- indexing ----------------------------------------------------------- + + @property + def lazy(self) -> _LazyIndexer: + """Lazy indexing: `lazy[...]`, `lazy.oindex[...]`, `lazy.vindex[...]`. + + Each returns a new `LazyArray` view; no data is read. + """ + return _LazyIndexer(self._select) + + def _select(self, selection: Any, mode: SelectionMode) -> LazyArray: + transform = self._transform + if mode != "basic": + # NumPy applies scalar integers as basic indices before the advanced + # ones, dropping their axes. Split them into their own step. + scalar_selection, selection = split_scalar_axes(selection, transform.domain, mode) + if scalar_selection is not None: + transform = transform.select(scalar_selection, "basic") + transform = transform.translate_domain_to((0,) * transform.input_rank) + literal = normalize_positional_selection(selection, transform.domain, mode) + if mode == "basic": + # IndexTransform's basic path includes NumPy's `None`/newaxis. + # `selection_to_transform` intentionally exposes a narrower basic + # selection contract and rejects it. + composed = transform[literal] + else: + composed = transform.select(literal, mode) + return LazyArray._derive(self._array, composed, self._parts, self._window, self._reader) + + def __getitem__(self, selection: Any) -> Any: + """Read a basic selection eagerly, like `numpy.ndarray.__getitem__`. + + Reads here are eager, not lazy, so that a `LazyArray` works as a duck + array for consumers (dask's `from_array`, `numpy.asarray`) that expect + indexing to produce data. Use `.lazy[...]` for the lazy form. + """ + return self._select(selection, "basic").result() + + def result(self, *, parts: Sequence[Partition] | None = None) -> Any: + """Materialize this view. + + Every result starts as a fresh system-memory buffer. Each touched + partition is read through the selected reader directly into its + rectangular destination, or into an owned dense temporary before fancy + placement. Empty views allocate without reading the source. + + Parameters + ---------- + parts + A reusable sequence previously returned by this exact view's + `parts()` method. Supplying it reuses that partition plan instead + of constructing another one. The parts must tile the view exactly. + + Returns + ------- + numpy.ndarray + An array of shape `self.shape`, identical whatever partitioning is + in force, always in fresh system memory. A view with a zero-rank + domain returns a zero-dimensional array, not a scalar. + + Raises + ------ + ValueError + If supplied parts were prepared by another view, or do not tile + this view exactly. The output buffer is uninitialized where nothing + was written, so a bad plan is reported rather than returned. + AssertionError + If this library's own partition walk fails to cover the view — a + bug in zarr-indexing, never a consequence of the caller's input. + """ + prepared_parts = None if parts is None else tuple(parts) + if prepared_parts is not None and any( + # Module-private provenance deliberately crosses the two public + # wrapper types without becoming part of either public surface. + part._owner is not self._part_owner # pyright: ignore[reportPrivateUsage] + for part in prepared_parts + ): + raise ValueError("prepared parts do not belong to this view") + + out_shape = self.shape + if prepared_parts is not None: + _validate_prepared_parts(prepared_parts, out_shape) + out = self._output_buffer(out_shape) + size = math.prod(out_shape) + if size == 0: + return out + + if prepared_parts is None and self._parts is None: + _invoke_reader(self._reader, self._array, ReadContext(self._transform), out) + return out + + written = 0 + selected_parts = self.parts() if prepared_parts is None else prepared_parts + for part in selected_parts: + # Counted before the scatter, so a part addressing the wrong + # number of axes is named rather than reported as a broadcast + # failure against the buffer. + written += _out_selection_cell_count(part.out_selection, out_shape) + direct = all(isinstance(selector, slice) for selector in part.out_selection) + if direct: + destination = out if len(part.out_selection) == 0 else out[part.out_selection] + else: + destination = part.view._output_buffer(part.view.shape) + _invoke_reader( + self._reader, + self._array, + ReadContext(part.view.transform, part.projection), + destination, + ) + if not direct: + out[part.out_selection] = destination + if written != size: + # The buffer is uninitialized where no part wrote, so a partition + # walk that does not tile the view exactly would otherwise hand + # back process memory dressed as data. The parts are disjoint by + # contract, so counting the cells each addresses is enough: + # a gap undercounts and an overlap overcounts. + if prepared_parts is not None: + raise ValueError( + "prepared parts do not tile the view exactly: " + f"they addressed {written} of the view's {size} cells" + ) + raise AssertionError( + f"the partition walk addressed {written} of the view's {size} " + "cells; this is a bug in zarr-indexing's partition walk" + ) + return out + + def _output_buffer(self, out_shape: tuple[int, ...]) -> Any: + """The buffer `result()` scatters parts into. + + Deliberately uninitialized: every cell is written by exactly one part, + and `result()` verifies that before returning. A masked source gets a + masked buffer so that reader writes preserve the mask; other source- + specific array types do not survive materializing. + """ + dtype = np.dtype(self.dtype) + if isinstance(self._array, np.ma.MaskedArray): + return np.ma.masked_all(out_shape, dtype=dtype) + return np.empty(out_shape, dtype=dtype) + + # -- protocols ---------------------------------------------------------- + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: + """Materialize the view as a NumPy array. + + The result never shares memory with the wrapped array, whatever `copy` + asks for: `result()` already allocates, so `copy=True` gets an array the + caller owns and `copy=None` gets the same one rather than a second + allocation. `copy=False` is refused, because materializing means reading + — the values do not exist as a NumPy array until this call makes them. + """ + if copy is False: + raise ValueError( + "a LazyArray cannot be converted to a NumPy array without a " + "copy: a view is a description of a read, and the values only " + "exist once the read is made" + ) + return np.asarray(self.result(), dtype=dtype) + + def __dask_tokenize__(self) -> Any: + """A deterministic token: the wrapped array and the view. + + Two wrappers produce equal tokens when they wrap the same data and + address the same cells. The view contributes a digest of its canonical + ndsel body, so transforms that differ only in representation produce + the same token, and a fancy selection with a large index array does not + embed that array's JSON in the token. See `_wrapped_token` for the + determinism scope of the wrapped array's contribution; dask is imported + lazily and is never a requirement of this package. + + The partitioning and reader are deliberately absent. Both decide how + the data is read — in which boxes, and through which request strategy — + and neither changes the values that come back, so two wrappers differing + only in those describe the same data. A token identifies data, so they + token alike and a consumer that caches on tokens reuses one result for + both. + """ + canonical = json.dumps(self._transform.to_json(), sort_keys=True) + return ( + type(self).__qualname__, + _wrapped_token(self._array), + hashlib.sha256(canonical.encode()).hexdigest(), + ) + + def __len__(self) -> int: + """The length of the first axis, as for a NumPy array; `TypeError` on a 0-d view.""" + if self.ndim == 0: + raise TypeError("len() of unsized object") + return self.shape[0] + + def __iter__(self) -> Iterator[Any]: + """Iterate eagerly over the first axis, like a NumPy array. + + The rank check happens in `__iter__` itself rather than in the + generator, so `iter(view)` on a zero-rank view raises immediately as + NumPy's does, instead of waiting for the first `next`. + """ + if self.ndim == 0: + raise TypeError("iteration over a 0-d array") + return (self[position] for position in range(self.shape[0])) + + # NumPy's own conversions decide what a size-1 (or wrong-sized) view means, + # including which exception it raises, so these delegate rather than + # reimplement. Each materializes the view first. + def __bool__(self) -> bool: + return bool(self.result()) + + def __int__(self) -> int: + return int(self.result()) + + def __float__(self) -> float: + return float(self.result()) + + def __index__(self) -> int: + return operator.index(self.result()) + + def __repr__(self) -> str: + wrapped = type(self._array).__name__ + described = [f"{wrapped} shape={self.shape} dtype={self.dtype}"] + if not _is_identity_transform(self._transform, self._base_shape): + described.append(f"view={self._transform.selection_repr}") + return f"" + + +class _LazyIndexer: + """The `.lazy` accessor: builds views instead of reading data. + + Holds the owning view's bound `_select` rather than the view itself, so the + accessor classes never reach into another object's internals. + """ + + __slots__ = ("_select",) + + def __init__(self, select: SelectFn) -> None: + self._select = select + + def __getitem__(self, selection: Any) -> LazyArray: + """Basic (integer / slice / ellipsis) indexing, lazily.""" + return self._select(selection, "basic") + + @property + def oindex(self) -> _LazyOIndex: + """Orthogonal (outer-product) indexing, lazily.""" + return _LazyOIndex(self._select) + + @property + def vindex(self) -> _LazyVIndex: + """Vectorized (coordinate / mask) indexing, lazily.""" + return _LazyVIndex(self._select) + + +class _LazyOIndex: + """`lazy.oindex[...]` — one selection per axis, combined as an outer product.""" + + __slots__ = ("_select",) + + def __init__(self, select: SelectFn) -> None: + self._select = select + + def __getitem__(self, selection: Any) -> LazyArray: + return self._select(selection, "orthogonal") + + +class _LazyVIndex: + """`lazy.vindex[...]` — correlated coordinate arrays, or a single mask.""" + + __slots__ = ("_select",) + + def __init__(self, select: SelectFn) -> None: + self._select = select + + def __getitem__(self, selection: Any) -> LazyArray: + return self._select(selection, "vectorized") diff --git a/packages/zarr-indexing/src/zarr_indexing/messages.py b/packages/zarr-indexing/src/zarr_indexing/messages.py new file mode 100644 index 0000000000..df0e0c87eb --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/messages.py @@ -0,0 +1,757 @@ +"""The ndsel message layer — pure JSON in, canonical JSON out. + +This module implements the [ndsel](https://github.com/zarr-developers/ndsel) draft wire +format: a JSON-serializable representation of NumPy-style n-dimensional +selections that adapts TensorStore's `IndexTransform` model. It is a **pure +JSON→JSON** layer: it depends on nothing but the standard library, imposes no +engine (numpy/array) constraints, and never rounds, clamps, or drops +information. Engine constraints (finite bounds, in-memory `IndexTransform` +construction) live one layer up, in `json.py`. + +Two entry points: + +- `parse_ndsel(obj)` — structurally validate an ndsel message of any of the + five kinds (`point`/`box`/`slice`/`points`/`transform`), returning it + unchanged. Raises `NdselError` (carrying a spec reason code) on any defect. +- `normalize_ndsel(obj)` — desugar and canonicalize a message to the single + deterministic **canonical transform body** of the spec (section 4.3): a bare + `IndexTransform` JSON body, without the `kind` discriminator. `normalize` is + idempotent when its output is re-tagged with `kind: "transform"`. + +The canonical body is, field-for-field, a TensorStore `IndexTransform` (minus +`kind`), so a normalized `transform` loads directly into TensorStore once +`kind` is stripped. + +Value rules enforced here: every integer is a 64-bit signed value; JSON +booleans are **not** integers (Python's `isinstance(True, int)` is guarded +against explicitly); the `"-inf"`/`"+inf"` sentinels are legal only in bound +positions; an implicit bound is the one-element `[n]`-bracket form, and its +implicit/explicit flag is preserved through normalization. +""" + +from __future__ import annotations + +from typing import Any + +__all__ = [ + "NdselError", + "normalize_ndsel", + "parse_ndsel", +] + +# --------------------------------------------------------------------------- +# Error taxonomy +# --------------------------------------------------------------------------- + +#: The complete set of ndsel reason codes (spec section 6). +REASON_CODES = frozenset( + { + "invalid_json", + "unknown_kind", + "unknown_field", + "multiple_upper_bounds", + "bounds_out_of_order", + "output_map_conflict", + "rank_mismatch", + "step_zero", + # Retired in 1.0-draft.2, when negative `step` became specified. Kept in + # the set so a message carrying the code is still recognized, but no + # condition in this implementation emits it. + "negative_step_unsupported", + } +) + + +class NdselError(ValueError): + """An ndsel message failed validation. + + Carries the spec `reason` code (one of `REASON_CODES`) so callers and the + conformance harness can assert on it directly, plus a human-readable + `detail`. + + Examples + -------- + >>> try: + ... normalize_ndsel({"kind": "bogus"}) + ... except NdselError as error: + ... (error.reason, str(error)) + ('unknown_kind', "unknown_kind: unknown kind 'bogus'") + """ + + def __init__(self, reason: str, detail: str = "") -> None: + """Store `reason` and `detail` and compose the message as `"reason: detail"`. + + `reason` is a spec reason code (one of `REASON_CODES`); `detail` is + optional human-readable context, and when empty the message is the + bare `reason`. + """ + self.reason = reason + self.detail = detail + super().__init__(f"{reason}: {detail}" if detail else reason) + + +# --------------------------------------------------------------------------- +# 64-bit signed integer range (spec section 3.5) +# --------------------------------------------------------------------------- + +_I64_MIN = -(2**63) +_I64_MAX = 2**63 - 1 + +_KNOWN_KINDS = frozenset({"point", "box", "slice", "points", "transform"}) + +# The two upper-bound spellings, keyed by message prefix. Only one of the three +# per group may appear (spec section 4.1 / 5.2). +_BOX_UPPER = ("exclusive_max", "inclusive_max", "shape") +_TRANSFORM_UPPER = ("input_exclusive_max", "input_inclusive_max", "input_shape") + +_OUTPUT_MAP_FIELDS = frozenset( + { + "offset", + "stride", + "input_dimension", + "index_array", + "index_array_bounds", + } +) + +# An upper bound on `input_rank`, because normalization allocates proportionally +# to it — an identity `output`, a bound per dimension, a label per dimension — +# from a document that carries no data behind the number. Matches the rank +# TensorStore accepts, which is well above any real array. +_MAX_RANK = 32 + + +# --------------------------------------------------------------------------- +# Leaf value validators +# --------------------------------------------------------------------------- + + +def _is_int(value: Any) -> bool: + """True iff `value` is a JSON integer — an `int` that is not a `bool`. + + JSON has no boolean-as-integer: `True`/`False` are rejected even though + Python makes `bool` a subclass of `int` (spec section 3.6). + """ + return isinstance(value, int) and not isinstance(value, bool) + + +def _check_int(value: Any, where: str) -> int: + """Validate a plain-integer position: an in-range i64, never a sentinel.""" + if not _is_int(value): + raise NdselError("invalid_json", f"{where} must be an integer, got {value!r}") + if value < _I64_MIN or value > _I64_MAX: + raise NdselError("invalid_json", f"{where} is outside the 64-bit signed range: {value}") + return int(value) + + +def _is_sentinel(value: Any) -> bool: + return value in ("-inf", "+inf") + + +def _check_index_value(value: Any, where: str) -> int | str: + """Validate an `index-value`: an in-range i64 or a `"-inf"`/`"+inf"` sentinel.""" + if _is_sentinel(value): + return str(value) + return _check_int(value, where) + + +def _check_bound(value: Any, where: str) -> int | str | list[int | str]: + """Validate a `bound`: an explicit `index-value`, or a one-element implicit `[index-value]`.""" + if isinstance(value, list): + if len(value) != 1: + raise NdselError( + "invalid_json", + f"{where} implicit bound must be a one-element array, got {value!r}", + ) + return [_check_index_value(value[0], where)] + return _check_index_value(value, where) + + +def _check_int_list(value: Any, where: str) -> list[int]: + if not isinstance(value, list): + raise NdselError("invalid_json", f"{where} must be an array, got {value!r}") + return [_check_int(v, f"{where}[{i}]") for i, v in enumerate(value)] + + +def _check_bound_list(value: Any, where: str) -> list[Any]: + if not isinstance(value, list): + raise NdselError("invalid_json", f"{where} must be an array, got {value!r}") + return [_check_bound(v, f"{where}[{i}]") for i, v in enumerate(value)] + + +def _check_label_list(value: Any, where: str) -> list[str]: + if not isinstance(value, list): + raise NdselError("invalid_json", f"{where} must be an array, got {value!r}") + for i, v in enumerate(value): + if not isinstance(v, str): + raise NdselError("invalid_json", f"{where}[{i}] must be a string, got {v!r}") + return list(value) + + +# --------------------------------------------------------------------------- +# Extended-integer order for bounds (spec section 4.1) +# --------------------------------------------------------------------------- + + +def _bound_value(bound: int | str | list[int | str]) -> int | str: + """The underlying `index-value` of a bound, dropping the implicit bracket.""" + return bound[0] if isinstance(bound, list) else bound + + +def _bound_is_implicit(bound: int | str | list[int | str]) -> bool: + return isinstance(bound, list) + + +def _ext_key(value: int | str) -> tuple[int, int]: + """A sort key giving the extended-integer order `-inf < n < +inf` exactly. + + Uses an integer tier plus the value, so no float rounding of near-`2**63` + integers can misorder the `inclusive_min <= exclusive_max` check. + """ + if value == "-inf": + return (0, 0) + if value == "+inf": + return (2, 0) + assert isinstance(value, int) + return (1, value) + + +def _rewrap(value: int | str, *, implicit: bool) -> int | str | list[int | str]: + return [value] if implicit else value + + +# --------------------------------------------------------------------------- +# Message-level helpers +# --------------------------------------------------------------------------- + + +def _require_object(obj: Any) -> dict[str, Any]: + if not isinstance(obj, dict): + raise NdselError("invalid_json", f"message must be a JSON object, got {type(obj).__name__}") + return obj + + +def _message_kind(obj: dict[str, Any]) -> str: + kind = obj.get("kind") + if not isinstance(kind, str): + raise NdselError("invalid_json", "message must have a string 'kind' field") + if kind not in _KNOWN_KINDS: + raise NdselError("unknown_kind", f"unknown kind {kind!r}") + return kind + + +def _check_membership(obj: dict[str, Any], allowed: frozenset[str], what: str) -> None: + """Strict membership (spec section 3.7): reject any undefined member.""" + for key in obj: + if key not in allowed: + raise NdselError("unknown_field", f"{what} has undefined member {key!r}") + + +def _single_upper_bound(obj: dict[str, Any], fields: tuple[str, str, str]) -> str | None: + present = [f for f in fields if f in obj] + if len(present) > 1: + raise NdselError( + "multiple_upper_bounds", + f"at most one of {fields} may be present; got {present}", + ) + return present[0] if present else None + + +def _resolve_upper_bound( + upper_field: str | None, + upper_raw: list[Any] | None, + inclusive_min: list[Any], + rank: int, + *, + kind_of: str, +) -> list[int | str | list[int | str]]: + """Produce `exclusive_max` from whichever upper-bound spelling was supplied. + + - `exclusive_max`/`input_exclusive_max` → used directly. + - `inclusive_max`/`input_inclusive_max` → each element `+1`. + - `shape`/`input_shape` → `inclusive_min + shape` per element. + - none → an **implicit `+inf`** in every dimension. + + The implicit/explicit bracket travels with the extent-bearing field (the + upper bound, or `shape`), matching the spec's `[n]`-bracket convention. + """ + if upper_field is None: + return [["+inf"] for _ in range(rank)] + + assert upper_raw is not None + if kind_of == "exclusive": + return list(upper_raw) + + result: list[int | str | list[int | str]] = [] + for k in range(rank): + raw = upper_raw[k] + implicit = _bound_is_implicit(raw) + value = _bound_value(raw) + if kind_of == "inclusive": + new = _inclusive_to_exclusive(value, f"{upper_field}[{k}]") + else: # shape + new = _shape_to_exclusive(_bound_value(inclusive_min[k]), value, f"{upper_field}[{k}]") + result.append(_rewrap(new, implicit=implicit)) + return result + + +def _checked_i64(value: int, where: str) -> int: + """An arithmetic result that must still be a 64-bit signed integer. + + Normalization is idempotent (spec section 4.3): whatever it emits must pass + the same validation on the way back in. Desugaring adds — `inclusive_max + 1`, + `inclusive_min + shape` — so a bound at the top of the range would otherwise + be emitted one past it and rejected by the next call on our own output. + """ + if value < _I64_MIN or value > _I64_MAX: + raise NdselError( + "invalid_json", + f"{where} is {value}, which is outside the 64-bit signed range; the " + f"normalized form cannot represent it", + ) + return value + + +def _inclusive_to_exclusive(value: int | str, where: str) -> int | str: + if value == "+inf" or value == "-inf": + return value + assert isinstance(value, int) + return _checked_i64(value + 1, f"{where} converted to an exclusive bound") + + +def _shape_to_exclusive(min_value: int | str, shape_value: int | str, where: str) -> int | str: + if shape_value == "-inf": + raise NdselError( + "invalid_json", + f"{where} is '-inf'; a shape counts cells and cannot be negatively infinite", + ) + if shape_value == "+inf" or min_value == "+inf": + return "+inf" + if min_value == "-inf": + return "-inf" + assert isinstance(min_value, int) + assert isinstance(shape_value, int) + return _checked_i64(min_value + shape_value, f"{where} added to its inclusive_min") + + +def _validate_domain(inclusive_min: list[Any], exclusive_max: list[Any], *, prefix: str) -> None: + """Every dimension must satisfy `inclusive_min <= exclusive_max` (empty is valid).""" + for k, (lo, hi) in enumerate(zip(inclusive_min, exclusive_max, strict=True)): + if _ext_key(_bound_value(lo)) > _ext_key(_bound_value(hi)): + raise NdselError( + "bounds_out_of_order", + f"{prefix}[{k}]: inclusive_min {_bound_value(lo)!r} > " + f"exclusive_max {_bound_value(hi)!r}", + ) + + +def _identity_output(rank: int) -> list[dict[str, Any]]: + return [{"offset": 0, "stride": 1, "input_dimension": k} for k in range(rank)] + + +# --------------------------------------------------------------------------- +# Per-kind desugaring +# --------------------------------------------------------------------------- + + +def _normalize_point(obj: dict[str, Any]) -> dict[str, Any]: + _check_membership(obj, frozenset({"kind", "coords"}), "point") + if "coords" not in obj: + raise NdselError("invalid_json", "point requires 'coords'") + coords = _check_int_list(obj["coords"], "coords") + return { + "input_rank": 0, + "input_inclusive_min": [], + "input_exclusive_max": [], + "input_labels": [], + "output": [{"offset": c} for c in coords], + } + + +def _infer_rank( + obj: dict[str, Any], + named_lengths: list[tuple[str, int]], + *, + declared: int | None, +) -> int: + """Reconcile a declared rank (if any) with every present array's length.""" + rank = declared + for name, length in named_lengths: + if rank is None: + rank = length + elif rank != length: + raise NdselError( + "rank_mismatch", + f"{name} has length {length}, inconsistent with rank {rank}", + ) + return rank if rank is not None else 0 + + +def _normalize_box(obj: dict[str, Any]) -> dict[str, Any]: + allowed = frozenset( + {"kind", "inclusive_min", "exclusive_max", "inclusive_max", "shape", "labels"} + ) + _check_membership(obj, allowed, "box") + + inclusive_min_raw = ( + _check_bound_list(obj["inclusive_min"], "inclusive_min") if "inclusive_min" in obj else None + ) + upper_field = _single_upper_bound(obj, _BOX_UPPER) + upper_raw = _check_bound_list(obj[upper_field], upper_field) if upper_field else None + labels_raw = _check_label_list(obj["labels"], "labels") if "labels" in obj else None + + named_lengths: list[tuple[str, int]] = [] + if inclusive_min_raw is not None: + named_lengths.append(("inclusive_min", len(inclusive_min_raw))) + if upper_raw is not None: + named_lengths.append((upper_field or "", len(upper_raw))) + if labels_raw is not None: + named_lengths.append(("labels", len(labels_raw))) + rank = _infer_rank(obj, named_lengths, declared=None) + + inclusive_min = inclusive_min_raw if inclusive_min_raw is not None else [0] * rank + exclusive_max = _resolve_upper_bound( + upper_field, upper_raw, inclusive_min, rank, kind_of=_upper_kind(upper_field, _BOX_UPPER) + ) + labels = labels_raw if labels_raw is not None else [""] * rank + _validate_domain(inclusive_min, exclusive_max, prefix="box") + + return { + "input_rank": rank, + "input_inclusive_min": inclusive_min, + "input_exclusive_max": exclusive_max, + "input_labels": labels, + "output": _identity_output(rank), + } + + +def _upper_kind(upper_field: str | None, fields: tuple[str, str, str]) -> str: + if upper_field is None or upper_field == fields[0]: + return "exclusive" + if upper_field == fields[1]: + return "inclusive" + return "shape" + + +def _normalize_slice(obj: dict[str, Any]) -> dict[str, Any]: + allowed = frozenset({"kind", "start", "stop", "step", "labels"}) + _check_membership(obj, allowed, "slice") + if "start" not in obj: + raise NdselError("invalid_json", "slice requires 'start'") + if "stop" not in obj: + raise NdselError("invalid_json", "slice requires 'stop'") + start = _check_int_list(obj["start"], "start") + stop = _check_int_list(obj["stop"], "stop") + step = _check_int_list(obj["step"], "step") if "step" in obj else [1] * len(start) + labels_raw = _check_label_list(obj["labels"], "labels") if "labels" in obj else None + + n = len(start) + for name, arr in (("stop", stop), ("step", step)): + if len(arr) != n: + raise NdselError( + "rank_mismatch", f"{name} has length {len(arr)}, expected {n} (from start)" + ) + if labels_raw is not None and len(labels_raw) != n: + raise NdselError( + "rank_mismatch", f"labels has length {len(labels_raw)}, expected {n} (from start)" + ) + + for k, s in enumerate(step): + if s == 0: + raise NdselError("step_zero", f"step[{k}] is zero") + + inclusive_min: list[Any] = [] + exclusive_max: list[Any] = [] + output: list[dict[str, Any]] = [] + for k in range(n): + a, b, s = start[k], stop[k], step[k] + # One rule for both signs (spec 5.3): the traversal runs from `a` + # toward `b`, so the source interval's length is `b - a` going up and + # `a - b` going down. + length = (b - a) if s > 0 else (a - b) + if length < 0: + # A reversed interval is a mistake about the direction of travel, + # not an empty selection. `b == a` is the way to select nothing. + raise NdselError( + "bounds_out_of_order", + f"start[{k}]={a} and stop[{k}]={b} with step {s} run the wrong " + "way; an empty selection is spelled stop == start", + ) + m = -(-length // abs(s)) # ceil(length / |s|) + o = _trunc_div(a, s) # trunc(a / s), toward zero, both signs + offset = a - s * o # lattice phase, |offset| < |s| + inclusive_min.append(o) + exclusive_max.append(o + m) + output.append({"offset": offset, "stride": s, "input_dimension": k}) + + labels = labels_raw if labels_raw is not None else [""] * n + return { + "input_rank": n, + "input_inclusive_min": inclusive_min, + "input_exclusive_max": exclusive_max, + "input_labels": labels, + "output": output, + } + + +def _normalize_points(obj: dict[str, Any]) -> dict[str, Any]: + _check_membership(obj, frozenset({"kind", "coords"}), "points") + if "coords" not in obj: + raise NdselError("invalid_json", "points requires 'coords'") + coords = obj["coords"] + if not isinstance(coords, list): + raise NdselError("invalid_json", f"points coords must be an array, got {coords!r}") + + rows: list[list[int]] = [] + n: int | None = None + for i, row in enumerate(coords): + if not isinstance(row, list): + raise NdselError("invalid_json", f"points coords[{i}] must be an array, got {row!r}") + row_ints = [_check_int(v, f"coords[{i}][{j}]") for j, v in enumerate(row)] + if n is None: + n = len(row_ints) + elif len(row_ints) != n: + raise NdselError( + "rank_mismatch", + f"points coords[{i}] has length {len(row_ints)}, expected {n} (ragged)", + ) + rows.append(row_ints) + + m = len(rows) + n = n if n is not None else 0 + output = [ + { + "offset": 0, + "stride": 1, + "index_array": [rows[i][k] for i in range(m)], + "index_array_bounds": ["-inf", "+inf"], + } + for k in range(n) + ] + return { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [m], + "input_labels": [""], + "output": output, + } + + +def _normalize_output_map(raw: Any, where: str) -> dict[str, Any]: + if not isinstance(raw, dict): + raise NdselError("invalid_json", f"{where} must be a JSON object, got {raw!r}") + _check_membership(raw, _OUTPUT_MAP_FIELDS, where) + + has_index_array = "index_array" in raw + has_input_dim = "input_dimension" in raw + if has_index_array and has_input_dim: + raise NdselError( + "output_map_conflict", + f"{where} carries both 'input_dimension' and 'index_array'", + ) + + offset = _check_int(raw["offset"], f"{where}.offset") if "offset" in raw else 0 + + if has_index_array: + stride = _check_int(raw["stride"], f"{where}.stride") if "stride" in raw else 1 + bounds = ( + _check_index_array_bounds(raw["index_array_bounds"], where) + if "index_array_bounds" in raw + else ["-inf", "+inf"] + ) + # index_array is carried verbatim (spec section 7 defers shape validation). + normalized: dict[str, Any] = { + "offset": offset, + "stride": stride, + "index_array": raw["index_array"], + "index_array_bounds": bounds, + } + return normalized + + if has_input_dim: + input_dim = _check_int(raw["input_dimension"], f"{where}.input_dimension") + if input_dim < 0: + raise NdselError( + "invalid_json", f"{where}.input_dimension must be >= 0, got {input_dim}" + ) + stride = _check_int(raw["stride"], f"{where}.stride") if "stride" in raw else 1 + return {"offset": offset, "stride": stride, "input_dimension": input_dim} + + # Constant map: only offset survives. A stray `stride`/`index_array_bounds` + # is schema-valid (the output-map schema permits those members on any map), + # so it is silently dropped rather than rejected — a constant carries only + # `offset` in canonical form (spec section 4.3). + return {"offset": offset} + + +def _check_index_array_bounds(value: Any, where: str) -> list[int | str]: + if not isinstance(value, list) or len(value) != 2: + raise NdselError( + "invalid_json", + f"{where}.index_array_bounds must be a two-element array, got {value!r}", + ) + lo = _check_index_value(value[0], f"{where}.index_array_bounds[0]") + hi = _check_index_value(value[1], f"{where}.index_array_bounds[1]") + if _ext_key(lo) > _ext_key(hi): + raise NdselError( + "bounds_out_of_order", + f"{where}.index_array_bounds: lower bound {lo!r} > upper bound {hi!r}", + ) + return [lo, hi] + + +def _normalize_transform(obj: dict[str, Any]) -> dict[str, Any]: + allowed = frozenset( + { + "kind", + "input_rank", + "input_inclusive_min", + "input_exclusive_max", + "input_inclusive_max", + "input_shape", + "input_labels", + "output", + } + ) + _check_membership(obj, allowed, "transform") + + declared_rank: int | None = None + if "input_rank" in obj: + declared_rank = _check_int(obj["input_rank"], "input_rank") + if declared_rank < 0: + raise NdselError("invalid_json", f"input_rank must be >= 0, got {declared_rank}") + if declared_rank > _MAX_RANK: + # Normalization fills a bound, a label and an identity output map per + # dimension, so an unbacked rank is a request to allocate from a + # document that carries nothing. + raise NdselError( + "invalid_json", + f"input_rank must be <= {_MAX_RANK}, got {declared_rank}", + ) + + inclusive_min_raw = ( + _check_bound_list(obj["input_inclusive_min"], "input_inclusive_min") + if "input_inclusive_min" in obj + else None + ) + upper_field = _single_upper_bound(obj, _TRANSFORM_UPPER) + upper_raw = _check_bound_list(obj[upper_field], upper_field) if upper_field else None + labels_raw = ( + _check_label_list(obj["input_labels"], "input_labels") if "input_labels" in obj else None + ) + + named_lengths: list[tuple[str, int]] = [] + if inclusive_min_raw is not None: + named_lengths.append(("input_inclusive_min", len(inclusive_min_raw))) + if upper_raw is not None: + named_lengths.append((upper_field or "", len(upper_raw))) + if labels_raw is not None: + named_lengths.append(("input_labels", len(labels_raw))) + rank = _infer_rank(obj, named_lengths, declared=declared_rank) + + inclusive_min = inclusive_min_raw if inclusive_min_raw is not None else [0] * rank + exclusive_max = _resolve_upper_bound( + upper_field, + upper_raw, + inclusive_min, + rank, + kind_of=_upper_kind(upper_field, _TRANSFORM_UPPER), + ) + labels = labels_raw if labels_raw is not None else [""] * rank + _validate_domain(inclusive_min, exclusive_max, prefix="input") + + if "output" in obj: + if not isinstance(obj["output"], list): + raise NdselError("invalid_json", f"output must be an array, got {obj['output']!r}") + output = [_normalize_output_map(m, f"output[{i}]") for i, m in enumerate(obj["output"])] + for i, m in enumerate(output): + # An `input_dimension` names one of *this* transform's input + # dimensions, so the rank is what bounds it. Checked here rather than + # in `_normalize_output_map`, which sees one map and not the rank. + if "input_dimension" in m and m["input_dimension"] >= rank: + raise NdselError( + "rank_mismatch", + f"output[{i}].input_dimension is {m['input_dimension']}, " + f"outside the valid range [0, {rank}) for input_rank {rank}", + ) + else: + output = _identity_output(rank) + + return { + "input_rank": rank, + "input_inclusive_min": inclusive_min, + "input_exclusive_max": exclusive_max, + "input_labels": labels, + "output": output, + } + + +_NORMALIZERS = { + "point": _normalize_point, + "box": _normalize_box, + "slice": _normalize_slice, + "points": _normalize_points, + "transform": _normalize_transform, +} + + +# --------------------------------------------------------------------------- +# trunc division (spec section 5.3 correction, matches _trunc_div in transform.py) +# --------------------------------------------------------------------------- + + +def _trunc_div(a: int, b: int) -> int: + """Integer division rounded toward zero (C semantics).""" + q = a // b + if q < 0 and q * b != a: + q += 1 + return q + + +# --------------------------------------------------------------------------- +# Public entry points +# --------------------------------------------------------------------------- + + +def normalize_ndsel(obj: Any) -> dict[str, Any]: + """Desugar and canonicalize an ndsel message to its canonical transform body. + + Accepts any of the five message kinds and returns the bare canonical + `IndexTransform` body of spec section 4.3 — no `kind` field. Raises + `NdselError` (carrying a reason code) for any invalid input. + + Examples + -------- + >>> body = normalize_ndsel({"kind": "box", "shape": [2, 3]}) + >>> (body["input_rank"], body["input_inclusive_min"], body["input_exclusive_max"]) + (2, [0, 0], [2, 3]) + >>> body["output"][0] + {'offset': 0, 'stride': 1, 'input_dimension': 0} + """ + message = _require_object(obj) + kind = _message_kind(message) + return _NORMALIZERS[kind](message) + + +def parse_ndsel(obj: Any) -> dict[str, Any]: + """Structurally validate an ndsel message, returning it unchanged. + + A lighter gate than `normalize_ndsel`: it confirms the message is a + well-formed ndsel message of a recognized kind (correct field membership, + JSON types, upper-bound exclusivity, domain ordering, step signs) and + raises `NdselError` otherwise, but does not desugar it. Useful for + validating a message you intend to keep in its compact shorthand form. + + Examples + -------- + >>> message = {"kind": "point", "coords": [3, 4]} + >>> parse_ndsel(message) is message + True + >>> normalize_ndsel(message)["output"] + [{'offset': 3}, {'offset': 4}] + """ + message = _require_object(obj) + _message_kind(message) + # Validation and desugaring share one pass; run it and discard the body. + normalize_ndsel(message) + return message diff --git a/packages/zarr-indexing/src/zarr_indexing/output_map.py b/packages/zarr-indexing/src/zarr_indexing/output_map.py new file mode 100644 index 0000000000..3ee7250efa --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/output_map.py @@ -0,0 +1,403 @@ +"""Output index maps — three ordered mappings to integer coordinates. + +An output index map describes how input cells address one dimension of +the output space. Its coordinates form an **ordered, duplicate-preserving sequence** +aligned with the input domain, never a mathematical set. Three representations +cover the cases that arise in practice: + +- `ConstantMap(offset=5)` — every request cell maps to coordinate `5` +- `DimensionMap(input_dimension=0, offset=3, stride=2)` over input `[0, 5)` + — the ordered arithmetic progression `[3, 5, 7, 9, 11]` +- `ArrayMap(index_array=[5, 1, 1])` — the explicit sequence `[5, 1, 1]`, + preserving both order and the repeated coordinate + +Every output map participates in two operations defined on `IndexTransform`, +which provides the input-domain context these maps lack: + +- **intersect** — retain mapped cells whose coordinates lie within a range + (e.g., a chunk), without changing their order or multiplicity. + Restricting `[3, 5, 5, 9]` to `[4, 8)` produces `[5, 5]`. +- **translate** — shift every coordinate by a constant (e.g., make chunk-local). + Translating `[5, 5, 7]` by `-4` produces `[1, 1, 3]`. + +These two operations are the foundation of chunk resolution: for each chunk, +intersect the map with the chunk's range, then translate to chunk-local +coordinates. + +The three types exist because they trade off generality for efficiency: + +- `ConstantMap`: O(1) storage, O(1) intersection +- `DimensionMap`: O(1) storage, O(1) intersection (analytical) +- `ArrayMap`: O(n) storage, O(n) intersection (must scan the array) + +Collapsing everything to `ArrayMap` would be correct but wasteful — a +billion-element slice would materialize a billion coordinates just to group +them by chunk, when `DimensionMap` does it with three integers. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import numpy as np + +from zarr_indexing._affine import checked_affine + +if TYPE_CHECKING: + import numpy.typing as npt + + from zarr_indexing.json import OutputIndexMapJSON + + +def _array_map_dependency_axes(index_array: np.ndarray[Any, Any]) -> tuple[int, ...]: + """Return the input axes on which a normalized index array varies. + + Normalized `ArrayMap` index arrays carry the full input rank of their + enclosing transform: an axis the array varies over has its full size, while + an axis the array is independent of is a singleton (size 1). The dependency + axes are therefore exactly the axes of size 2 or more. An orthogonal + (`oindex`) array depends on a single axis; a vectorized (`vindex`) array + depends on all of the (shared) broadcast axes. + + A size-**0** axis carries no dependency either: the array has no values to + vary, so an empty selection stays the flavor it was made as rather than + reading as correlated with every other axis. + """ + return tuple(axis for axis, size in enumerate(index_array.shape) if size > 1) + + +@dataclass(frozen=True, slots=True) +class ConstantMap: + """A constant output-coordinate mapping. + + Every input cell maps to `offset`. Arises from integer indexing (e.g., + `arr[5]` fixes one dimension to coordinate 5). + + Examples + -------- + Every input cell maps to the same output coordinate — the NumPy analogy + is a broadcast (`np.broadcast_to(5, (3,))`), not an index: + + >>> from zarr_indexing.domain import IndexDomain + >>> from zarr_indexing.transform import IndexTransform + >>> domain = IndexDomain.from_shape((3,)) + >>> t = IndexTransform(domain=domain, output=(ConstantMap(offset=5),)) + >>> t.apply((0,)), t.apply((1,)), t.apply((2,)) + ((5,), (5,), (5,)) + """ + + offset: int = 0 + """The fixed output coordinate every input cell maps to.""" + + def to_json(self) -> OutputIndexMapJSON: + """Convert to the canonical wire form: the bare `constant` map. + + Examples + -------- + >>> ConstantMap(5).to_json() + {'offset': 5} + """ + return {"offset": self.offset} + + +@dataclass(frozen=True, slots=True) +class DimensionMap: + """An ordered affine mapping to output coordinates. + + Maps each input coordinate `i` to `offset + stride * i`, where the input + range comes from the enclosing `IndexTransform`'s domain. Arises from slice + indexing (e.g., `arr[2:10:3]` gives offset=2, stride=3). + + Examples + -------- + The slice `arr[2:11:3]` reads coordinates `2, 5, 8` — the rule + `offset + stride * i` with `offset=2`, `stride=3`: + + >>> m = DimensionMap(input_dimension=0, offset=2, stride=3) + >>> [m.offset + m.stride * i for i in range(3)] + [2, 5, 8] + >>> np.arange(11)[2:11:3].tolist() + [2, 5, 8] + """ + + input_dimension: int + """The input (domain) dimension whose coordinate this map reads.""" + + offset: int = 0 + """The output coordinate that input coordinate `0` maps to.""" + + stride: int = 1 + """The output-coordinate step per unit input step; negative walks backward, zero repeats `offset`.""" + + def to_json(self) -> OutputIndexMapJSON: + """Convert to the canonical wire form: the `single_input_dimension` map. + + Examples + -------- + >>> DimensionMap(input_dimension=1, offset=0, stride=2).to_json() + {'offset': 0, 'stride': 2, 'input_dimension': 1} + """ + return { + "offset": self.offset, + "stride": self.stride, + "input_dimension": self.input_dimension, + } + + +@dataclass(frozen=True, slots=True) +class ArrayMap: + """An explicit ordered, duplicate-preserving coordinate mapping. + + Maps each input position `i` to `offset + stride * index_array[i]`. + Index-array order and repeated entries are semantic and remain present in + the result. Arises from fancy indexing (e.g., `arr[[5, 1, 1]]` or boolean + masks). + + Freshly constructed maps are normalized to the **full input rank** of their + enclosing transform: `index_array` has the enclosing domain's rank, sized + fully on the axes it varies over and singleton (size 1) elsewhere. The + shape is the single source of truth for what the map depends on — its + **dependency axes** are exactly its non-singleton axes (see + `_array_map_dependency_axes`) — and it distinguishes the two + flavors of multi-array fancy indexing: + + - **orthogonal** (`oindex`): each array varies along a single, *distinct* + axis (all others singleton); the result is their outer product. + - **vectorized** (`vindex`): the arrays are correlated and share the same + non-singleton (broadcast) axes; the result is a pointwise scatter. + + A map holding exactly one coordinate carries no shape to read a dependency + from, and none is needed: it is the `ConstantMap` it equals, and the + selection layer builds that instead (see `array_map_or_constant`). A + hand-built all-singleton `ArrayMap` is still a valid value; resolution + classifies it with the correlated maps and reads it pointwise. + + Examples + -------- + The fancy selection `arr[[5, 1, 1]]` reads coordinate 5, then 1, then 1 + — order and the duplicate preserved, exactly as NumPy fancy indexing: + + >>> m = ArrayMap(index_array=np.array([5, 1, 1])) + >>> [m.offset + m.stride * c for c in m.index_array.tolist()] + [5, 1, 1] + >>> np.arange(10)[[5, 1, 1]].tolist() + [5, 1, 1] + """ + + index_array: npt.NDArray[np.integer[Any]] + """Explicit coordinates at the enclosing transform's full input rank; order and + duplicates are semantic. Its non-singleton axes are the map's dependency axes.""" + + offset: int = 0 + """Constant term of the affine adjustment: the output coordinate is `offset + stride * index_array[i]`.""" + + stride: int = 1 + """Multiplier applied to each `index_array` value before `offset` is added.""" + + def __post_init__(self) -> None: + """Own the index array and expose it read-only. + + A map is frozen, but the array inside it was not: reaching through a + view's transform to `index_array[0] = 9` silently changed what the view + returned, in a package whose whole contract is that a view is a + description of a read and resolving it twice answers alike. Owning the + array also prevents the caller from changing the contents behind the + read-only view, which would invalidate this value object's hash. + """ + # Immutable bytes are the ultimate owner so callers cannot re-enable + # the WRITEABLE flag, as they can on a read-only array that owns its + # allocation. `asarray` also accepts the NumPy scalars that reach here + # after indexing an array down to one element. + array = np.asarray(self.index_array) + if not np.issubdtype(array.dtype, np.integer): + raise TypeError(f"index_array must have an integer dtype, got {array.dtype}") + normalized = checked_affine(0, 1, array) + frozen = np.frombuffer(normalized.tobytes(), dtype=np.intp).reshape(normalized.shape) + object.__setattr__(self, "index_array", frozen) + + def __reduce__(self) -> tuple[object, tuple[object, int, int]]: + """Reconstruct through `__init__`, preserving the ownership invariant.""" + return ( + type(self), + (self.index_array, self.offset, self.stride), + ) + + def __eq__(self, other: object) -> bool: + """Value equality, comparing index arrays element-wise. + + The generated `__eq__` compares them with `==`, whose result for two + arrays is an array — so asking whether two maps are equal raised + `ValueError: the truth value of an array ... is ambiguous`. `frozen=True` + reads as a promise that a value can be compared and hashed, and this is + what makes good on it. + """ + if not isinstance(other, ArrayMap): + return NotImplemented + return ( + self.offset == other.offset + and self.stride == other.stride + and self.index_array.shape == other.index_array.shape + and bool(np.array_equal(self.index_array, other.index_array)) + ) + + def __hash__(self) -> int: + """Hashed by the array's contents, so equal maps hash alike. + + The generated `__hash__` hashed the ndarray itself, which is unhashable; + a map could therefore not go in a set, or key a cache. + """ + return hash( + ( + self.offset, + self.stride, + self.index_array.shape, + self.index_array.tobytes(), + ) + ) + + @property + def dependency_axes(self) -> tuple[int, ...]: + """Every input axis this map varies over: its non-singleton axes. + + One axis means orthogonal, several mean correlated, and none means + the map is degenerate — the shape is the single source of truth for + all three. + + Examples + -------- + >>> ArrayMap(index_array=np.array([[4, 0, 2]])).dependency_axes + (1,) + >>> ArrayMap(index_array=np.array([[1, 2], [3, 4]])).dependency_axes + (0, 1) + """ + return _array_map_dependency_axes(self.index_array) + + @property + def dependent_axis(self) -> int | None: + """Return the single input axis an orthogonal `ArrayMap` varies over. + + This is the array's one non-singleton axis, read from the shape — the + single source of truth for what a map depends on. The selection layer + collapses a single-coordinate map to a `ConstantMap` + (`array_map_or_constant`), so a non-empty map built by this package always + has at least one dependency axis. + + Returns + ------- + int or None + The axis the map varies over, or `None` when it varies over no input + axis at all — an empty map, or a hand-built all-singleton one. `None` + is a valid result, not an error; such maps resolve through the + pointwise (general) path. + + Raises + ------ + ValueError + If the map varies over more than one axis, which makes it correlated + rather than orthogonal. + + Examples + -------- + An `oindex` selection on axis 1 of a rank-2 transform stores its + coordinates full-sized on axis 1 and singleton on axis 0, so the + dependency axis is read straight off the shape: + + >>> m = ArrayMap(index_array=np.array([[4, 0, 2]])) + >>> m.index_array.shape + (1, 3) + >>> m.dependent_axis + 1 + """ + dep = self.dependency_axes + if len(dep) == 1: + return dep[0] + if len(dep) == 0: + return None + raise ValueError( + f"orthogonal ArrayMap must vary over exactly one axis; got dependency axes {dep}" + ) + + def to_json(self) -> OutputIndexMapJSON: + """Convert to the canonical wire form, collapsing a degenerate map. + + A map holding exactly one coordinate, or none at all, is emitted as a + `constant` map — see the module note on the wire format in + [`zarr_indexing.json`][zarr_indexing.json]. Both are degenerate: the + first selects one coordinate whatever the input, and the second names + no cell and can only be empty because an input dimension is, so the + emptiness travels in the domain instead. + + Examples + -------- + >>> ArrayMap(np.array([[4], [1], [1]])).to_json()["index_array"] + [[4], [1], [1]] + >>> ArrayMap(np.array([7])).to_json() # degenerate: one coordinate + {'offset': 7} + """ + if self.index_array.size == 1: + value = int(self.index_array.reshape(-1)[0]) + return {"offset": self.offset + self.stride * value} + if self.index_array.size == 0: + return {"offset": 0} + return { + "offset": self.offset, + "stride": self.stride, + "index_array": self.index_array.tolist(), + "index_array_bounds": ["-inf", "+inf"], + } + + +def output_index_map_from_json(data: OutputIndexMapJSON) -> OutputIndexMap: + """Construct the output map a canonical wire form names. + + The wire form is a tagged union — `index_array`, then `input_dimension`, + else constant — so loading it dispatches to the right kind here rather + than on any one of them. + + Examples + -------- + >>> output_index_map_from_json({"offset": 5}) + ConstantMap(offset=5) + >>> output_index_map_from_json({"offset": 0, "stride": 2, "input_dimension": 1}) + DimensionMap(input_dimension=1, offset=0, stride=2) + """ + from zarr_indexing._wire import lower_index_array + + if "index_array" in data: + return ArrayMap( + index_array=lower_index_array(data["index_array"], "index_array"), + offset=data.get("offset", 0), + stride=data.get("stride", 1), + ) + if "input_dimension" in data: + return DimensionMap( + input_dimension=data["input_dimension"], + offset=data.get("offset", 0), + stride=data.get("stride", 1), + ) + return ConstantMap(offset=data.get("offset", 0)) + + +def array_map_or_constant( + index_array: npt.NDArray[np.integer[Any]], + offset: int = 0, + stride: int = 1, +) -> ArrayMap | ConstantMap: + """An `ArrayMap`, collapsed to the `ConstantMap` it equals when it can be. + + An index array holding exactly one coordinate maps every input cell to the + same place; representing it as a lookup table would leave a map whose shape + names no dependency axis, the one form the shape-derived classifier cannot + read. The selection and composition layers build their array maps through + this helper so that a non-empty `ArrayMap` always varies over at least one + axis. An empty array stays an `ArrayMap`: it maps no cell at all, and the + emptiness lives in the domain that accompanies it. + """ + arr = np.asarray(index_array) + if arr.size == 1: + return ConstantMap(offset=checked_affine(offset, stride, int(arr.reshape(-1)[0]))) + return ArrayMap(index_array=arr, offset=offset, stride=stride) + + +OutputIndexMap = ConstantMap | DimensionMap | ArrayMap diff --git a/packages/zarr-indexing/src/zarr_indexing/py.typed b/packages/zarr-indexing/src/zarr_indexing/py.typed new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-indexing/src/zarr_indexing/reader.py b/packages/zarr-indexing/src/zarr_indexing/reader.py new file mode 100644 index 0000000000..8d47d51d21 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/reader.py @@ -0,0 +1,585 @@ +"""Backend reader protocol and built-in system-memory implementations.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Final, Protocol + +if TYPE_CHECKING: + from collections.abc import Callable + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing.chunk_resolution import ChunkProjection # noqa: TC001 (runtime annotation) +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap, OutputIndexMap +from zarr_indexing.transform import ( + IndexTransform, +) + +__all__ = [ + "BasicReader", + "NumPyReader", + "ReadContext", + "Reader", + "UnitStepReader", + "basic_reader", + "numpy_reader", + "unit_step_reader", +] + + +@dataclass(frozen=True, slots=True) +class ReadContext: + """A source-global transform and optional projection for a partitioned read. + + Examples + -------- + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> context = ReadContext(transform) + >>> context.transform.domain.shape + (2,) + >>> context.projection is None + True + """ + + transform: IndexTransform + """Maps zero-origin output-buffer coordinates to global coordinates in the source.""" + + projection: ChunkProjection | None = None + """The partition plan when this read is one part of a partitioned view, else `None`.""" + + +class Reader(Protocol): + """Backend adapter that fills supplied system-memory result buffers. + + A reader may be shared by every view and part derived from one + [`LazyArray`][zarr_indexing.lazy_array.LazyArray]. Part reads may run + concurrently, so a stateful implementation must synchronize its own + mutable state. `LazyArray` deliberately adds no serialization. + + Examples + -------- + The protocol is not `runtime_checkable`; an object satisfies it by + exposing a conforming `read_into`, as `basic_reader` does: + + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> source = np.arange(6) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> basic_reader.read_into(source, ReadContext(transform), out) + >>> out.tolist() + [1, 3] + """ + + def read_into( + self, + source: Any, + context: ReadContext, + out: np.ndarray[Any, Any], + /, + ) -> None: + """Fill `out` with the exact source values selected by `context`. + + `context.transform` maps zero-origin coordinates in the output buffer + to global coordinates in `source`, and its domain shape equals + `out.shape`. `context.projection`, when present, is the corresponding + partition plan: its `chunk_transform` is chunk-local, its + `cell_transform` describes result placement, and its `chunk_domain` + describes the grid cell. Fill every cell in place, preserving the + transform's exact values, order, and dtype, then return `None`. Do not + replace or retain `out`; it may be a strided writable view rather than + an owning array. + + Backend exceptions propagate unchanged. Because callers may resolve + parts concurrently through the same reader object, stateful readers + are responsible for synchronizing their own state. + """ + ... + + +class BasicReader: + """Reader for system-memory sources exposing basic integer/slice indexing. + + Each transform is decomposed into the smallest enclosing positive-slice + slab and a residual transform. The slab is read once with basic indexing, + so fancy or negative-step selections may over-read, and the residual is + then lowered through NumPy system-memory operations into the supplied + buffer. + + Slice results must permit conversion to NumPy system memory. Device arrays + that reject implicit conversion require a custom reader responsible for + transferring values into the supplied system-memory output buffer. + + Examples + -------- + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> source = np.arange(6) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> BasicReader().read_into(source, ReadContext(transform), out) + >>> out.tolist() == source[1:5:2].tolist() + True + """ + + __slots__ = () + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + """Read one transform through a positive-slice slab and residual lowering.""" + transform = context.transform + key, residual = _decompose_basic(transform) + block = np.asanyarray(source[key]) + out[...] = _lower(block, residual) + + +class NumPyReader: + """Reader optimized for NumPy system-memory arrays. + + This is the reader selected by + [`LazyArray.from_numpy`][zarr_indexing.lazy_array.LazyArray.from_numpy]. It + applies the complete transform with NumPy operations and is applicable to + `numpy.ndarray` sources, including `numpy.ma.MaskedArray`. + + Examples + -------- + >>> transform = IndexTransform.from_shape((3, 4))[::2, 1:3] + >>> source = np.arange(12).reshape(3, 4) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> NumPyReader().read_into(source, ReadContext(transform), out) + >>> out.tolist() + [[1, 2], [9, 10]] + """ + + __slots__ = () + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + """Read one transform through a narrowed slab into `out`.""" + transform = context.transform + key, residual = _decompose_basic(transform) + block = np.asanyarray(source[key]) + out[...] = _lower(block, residual) + + +class UnitStepReader: + """Reader for sources whose basic indexing accepts only step-1 slices. + + Each transform is decomposed into the smallest enclosing ascending + unit-step slab and a residual transform, so the source only ever receives + `slice(start, stop, 1)` on every axis — the one form an API without + general strided reads (an FFI binding, an HTTP range endpoint) supports. + `BasicReader` instead pushes strided and reversed slices down, which + reads less but asks more of the source. + + The residual lowering applies strides, reversals, and gathers to the + in-memory block, so a strided selection over-reads its cover by the + stride factor. Partitioning the wrapping + [`LazyArray`][zarr_indexing.lazy_array.LazyArray] (`with_parts`) bounds + each cover by a part. + + Slice results must permit conversion to NumPy system memory, exactly as + for `BasicReader`. + + Examples + -------- + The source below is only ever asked for step-1 slices — here the cover + `slice(1, 4, 1)` — and the stride is replayed against the block: + + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> source = np.arange(6) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> UnitStepReader().read_into(source, ReadContext(transform), out) + >>> out.tolist() + [1, 3] + """ + + __slots__ = () + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + """Read one transform through an ascending unit-step slab into `out`.""" + transform = context.transform + key, residual = _decompose_unit_step(transform) + block = np.asanyarray(source[key]) + out[...] = _lower(block, residual) + + +basic_reader: Final = BasicReader() +numpy_reader: Final = NumPyReader() +unit_step_reader: Final = UnitStepReader() + + +def _take(array: Any, indices: np.ndarray[Any, np.dtype[np.intp]], axis: int) -> Any: + return np.take(array, indices, axis=axis) + + +def _reshape(array: Any, shape: tuple[int, ...]) -> Any: + return np.reshape(array, shape) + + +def _transpose(array: Any, permutation: tuple[int, ...]) -> Any: + return np.transpose(array, permutation) + + +def _expand_dims(array: Any, axis: int) -> Any: + return np.expand_dims(array, axis) + + +def _dimension_map_coords( + m: DimensionMap, transform: IndexTransform +) -> np.ndarray[Any, np.dtype[np.intp]]: + """The storage coordinates a DimensionMap enumerates, in view order.""" + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = transform.domain.exclusive_max[d] + extent = hi - lo + if extent == 0: + return np.empty((0,), dtype=np.intp) + first = checked_affine(m.offset, m.stride, lo) + return checked_affine(first, m.stride, np.arange(extent, dtype=np.intp)) + + +def _array_map_coords(m: ArrayMap) -> np.ndarray[Any, np.dtype[np.intp]]: + """The storage coordinates an ArrayMap enumerates, flattened.""" + return checked_affine(m.offset, m.stride, m.index_array).reshape(-1) + + +def _correlated_map_coords( + m: ArrayMap, broadcast_axes: list[int], broadcast_shape: tuple[int, ...], input_rank: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """One storage coordinate per point of the correlated block, flattened. + + A correlated `ArrayMap`'s index array carries the transform's full input + rank, with a singleton on every axis it does not vary over — including + broadcast axes it shares with the *other* correlated maps but is itself + constant along. Flattening it directly would then yield fewer coordinates + than there are points, so it is reduced to the broadcast block and + broadcast up to it explicitly. + """ + coords = checked_affine(m.offset, m.stride, m.index_array) + if math.prod(broadcast_shape) == 0: + # A zero-extent broadcast axis makes the correlated block empty — for + # example an ArrayMap composed over an empty domain, which the package + # promises resolves like any other. The per-axis reshape below cannot + # express that block (a 0-size array does not reshape to the non-zero + # singleton axes), and there is no coordinate to produce anyway. + return np.empty(0, dtype=np.intp) + if coords.ndim == input_rank: + # Drop the axes bound by a slice, which the map is singleton along. + # Removing size-1 axes by reshape preserves element order wherever they + # sit, so no transpose is needed. + coords = coords.reshape(tuple(coords.shape[axis] for axis in broadcast_axes)) + return np.ascontiguousarray(np.broadcast_to(coords, broadcast_shape)).reshape(-1) + + +def _restore_domain_axis_order( + result: Any, axis_input_dims: list[int], domain_shape: tuple[int, ...] +) -> Any: + """Permute `result`'s axes into input-domain order, restoring dropped axes. + + `axis_input_dims[k]` is the input (domain) dimension that axis `k` of + `result` corresponds to. Axes are permuted so that they appear in increasing + domain-dimension order, and any domain dimension no output map depends on is + reinserted at **its own extent**. + + An unreferenced dimension is not always a singleton. A `vindex` coordinate + array with a broadcast axis it does not vary over leaves that axis in the + domain; a later basic index that consumes the axis the array *does* vary + over collapses the map to a `ConstantMap` and leaves the broadcast axis + behind, with whatever extent the basic index gave it — including 0. Every + position along such an axis holds the same values, so it is restored by + repeating the block, and an extent of 0 restores an empty result rather than + fabricating a row. + + This is also where NumPy's advanced-index placement rules are absorbed: + whatever order the gather produced, the lowered result always comes back in + the view's own axis order. + """ + if len(set(axis_input_dims)) != len(axis_input_dims): + raise NotImplementedError( + "resolving a transform whose output maps share an input dimension " + "(a diagonal view) is not supported" + ) + order = sorted(range(len(axis_input_dims)), key=lambda k: axis_input_dims[k]) + if order != list(range(len(order))): + result = _transpose(result, tuple(order)) + covered = set(axis_input_dims) + for dim, extent in enumerate(domain_shape): + if dim in covered: + continue + result = _expand_dims(result, dim) + if extent != 1: + result = _take(result, np.zeros(extent, dtype=np.intp), axis=dim) + return result + + +def _lower(array: Any, transform: IndexTransform) -> Any: + """Lower a transform to one pass of array operations over `array`. + + Every read, partitioned or not, goes through this function. The result is + always in the transform's own domain axis order and of exactly its domain + shape. + """ + if math.prod(transform.domain.shape) == 0: + # An empty domain selects nothing, and its maps may legitimately be + # empty along the vanished axes (an ArrayMap composed over an empty + # domain, which the package promises resolves like any other). The + # resolvers below cannot evaluate such maps — and have no reason to. + return np.empty(transform.domain.shape, dtype=np.asanyarray(array).dtype) + if transform.index_array_structure == "general": + result = _lower_general(array, transform) + else: + result = _lower_orthogonal(array, transform) + if isinstance(result, np.generic): + # Basic indexing every axis of a NumPy array yields a scalar; `result()` + # documents a zero-dimensional array. + return np.asarray(result) + return result + + +def _lower_orthogonal(array: Any, transform: IndexTransform) -> Any: + """Basic slicing plus one `take` per fancy-indexed axis (an outer product). + + Orthogonal `ArrayMap`s vary over distinct input axes, so gathering them one + axis at a time is exact — a `take` along one storage axis leaves every other + axis's coordinates untouched. + """ + outputs = transform.output + gathered: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + for out_dim, m in enumerate(outputs): + if isinstance(m, ArrayMap): + gathered[out_dim] = _array_map_coords(m) + elif isinstance(m, DimensionMap) and m.stride <= 0: + # Reversing and repeating maps have no positive-step slice; gather them. + gathered[out_dim] = _dimension_map_coords(m, transform) + + result = array + for out_dim, coords in gathered.items(): + result = _take(result, coords, axis=out_dim) + + selection: list[Any] = [] + axis_input_dims: list[int] = [] + for out_dim, m in enumerate(outputs): + if isinstance(m, ConstantMap): + selection.append(m.offset) + continue + if out_dim in gathered: + selection.append(slice(None)) + else: + assert isinstance(m, DimensionMap) + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = transform.domain.exclusive_max[d] + selection.append(slice(m.offset + m.stride * lo, m.offset + m.stride * hi, m.stride)) + if isinstance(m, ArrayMap): + axis = m.dependent_axis + if axis is None: + raise NotImplementedError( + "resolving an orthogonal ArrayMap that varies over no input " + "dimension is not supported; such a map should have been " + "collapsed to a ConstantMap" + ) + axis_input_dims.append(axis) + else: + axis_input_dims.append(m.input_dimension) + result = result[tuple(selection)] + return _restore_domain_axis_order(result, axis_input_dims, transform.domain.shape) + + +def _lower_general(array: Any, transform: IndexTransform) -> Any: + """Flatten the index-array axes, gather the points once, reshape back. + + The general path for every index-array structure the orthogonal resolver + cannot take: correlated (`vindex`) maps, maps sharing an input axis (a + diagonal gather), and mixtures of correlated and orthogonal maps. All + index arrays are treated as lookup tables over the joint block of + non-slice axes: the corresponding storage axes are moved to the front and + flattened, the per-point coordinates are converted to offsets into that + flat axis with row-major strides, and a single `take` collects them. + """ + outputs = transform.output + correlated_dims = [d for d, m in enumerate(outputs) if isinstance(m, ArrayMap)] + + slice_input_dims = {m.input_dimension for m in outputs if isinstance(m, DimensionMap)} + broadcast_axes = [d for d in range(transform.input_rank) if d not in slice_input_dims] + broadcast_shape = tuple(transform.domain.shape[d] for d in broadcast_axes) + + for d in correlated_dims: + arr_map = outputs[d] + assert isinstance(arr_map, ArrayMap) + # The axes the array varies over (its non-singleton axes; see + # transform._array_map_dependency_axes) must all live in the block. + dependency = (axis for axis, size in enumerate(arr_map.index_array.shape) if size > 1) + if any(a not in broadcast_axes for a in dependency): + # Reachable only by hand-building a transform: no selection binds + # the same input axis to both a slice map and an index array. + raise NotImplementedError( + "resolving a transform whose index array varies over an input " + "dimension also bound by a slice map is not supported" + ) + + # Gather any reversing or repeating slice axis first, then take the basic-slice + # cut. The correlated axes keep their full extent: their coordinates are absolute. + gathered: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = { + d: _dimension_map_coords(m, transform) + for d, m in enumerate(outputs) + if isinstance(m, DimensionMap) and m.stride <= 0 + } + result = array + for out_dim, coords in gathered.items(): + result = _take(result, coords, axis=out_dim) + + selection: list[Any] = [] + residual_axis_dims: list[int] = [] + correlated_positions: list[int] = [] + residual_positions: list[int] = [] + axis = 0 + for out_dim, m in enumerate(outputs): + if isinstance(m, ConstantMap): + selection.append(m.offset) + continue + if out_dim in correlated_dims: + selection.append(slice(None)) + correlated_positions.append(axis) + elif out_dim in gathered: + selection.append(slice(None)) + residual_positions.append(axis) + assert isinstance(m, DimensionMap) + residual_axis_dims.append(m.input_dimension) + else: + assert isinstance(m, DimensionMap) + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = transform.domain.exclusive_max[d] + selection.append(slice(m.offset + m.stride * lo, m.offset + m.stride * hi, m.stride)) + residual_positions.append(axis) + residual_axis_dims.append(d) + axis += 1 + result = result[tuple(selection)] + + # Correlated axes to the front, in output order, so the flattening strides + # below match the order the coordinates are combined in. + perm = tuple(correlated_positions) + tuple(residual_positions) + if perm != tuple(range(len(perm))): + result = _transpose(result, perm) + + n_corr = len(correlated_dims) + corr_sizes = tuple(int(s) for s in result.shape[:n_corr]) + tail_shape = tuple(int(s) for s in result.shape[n_corr:]) + result = _reshape(result, (math.prod(corr_sizes), *tail_shape)) + + flat_index = np.zeros(math.prod(broadcast_shape), dtype=np.intp) + stride = 1 + for position in range(n_corr - 1, -1, -1): + m = outputs[correlated_dims[position]] + assert isinstance(m, ArrayMap) + flat_index = flat_index + ( + _correlated_map_coords(m, broadcast_axes, broadcast_shape, transform.input_rank) + * stride + ) + stride *= corr_sizes[position] + + result = _take(result, flat_index, axis=0) + result = _reshape(result, broadcast_shape + tail_shape) + return _restore_domain_axis_order( + result, list(broadcast_axes) + residual_axis_dims, transform.domain.shape + ) + + +def _push_slice_for_dimension_map( + m: DimensionMap, transform: IndexTransform +) -> tuple[slice, DimensionMap]: + """The positive-step slice covering a `DimensionMap`, and its block-local map. + + A negative step is read forwards and reversed by the residual: a source is + only ever asked for a slice that walks upwards, which is the one form every + array-like agrees on. + """ + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = max(transform.domain.exclusive_max[d], lo) + if hi == lo: + return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) + first = checked_affine(m.offset, m.stride, lo) + last = checked_affine(m.offset, m.stride, hi - 1) + if m.stride > 0: + return ( + slice(first, last + 1, m.stride), + DimensionMap(input_dimension=d, offset=-lo, stride=1), + ) + if m.stride == 0: + return ( + slice(first, first + 1, 1), + DimensionMap(input_dimension=d, offset=0, stride=0), + ) + # Descending: the block holds the same coordinates in ascending order, so + # the residual walks it backwards from the last block position. + return ( + slice(last, first + 1, -m.stride), + DimensionMap(input_dimension=d, offset=hi - 1, stride=-1), + ) + + +def _push_unit_slice_for_dimension_map( + m: DimensionMap, transform: IndexTransform +) -> tuple[slice, DimensionMap]: + """The unit-step slice covering a `DimensionMap`, and its block-local map. + + Strides and reversals stay in the residual: the source is only ever asked + for a contiguous ascending slice, and the original stride is replayed + against the in-memory block. The cover therefore over-reads a strided + selection by its stride factor, which is the price of a source that + accepts nothing but `slice(start, stop, 1)`. + """ + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = max(transform.domain.exclusive_max[d], lo) + if hi == lo: + return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) + first = checked_affine(m.offset, m.stride, lo) + if m.stride == 0: + return ( + slice(first, first + 1, 1), + DimensionMap(input_dimension=d, offset=0, stride=0), + ) + last = checked_affine(m.offset, m.stride, hi - 1) + origin = min(first, last) + return ( + slice(origin, max(first, last) + 1, 1), + DimensionMap(input_dimension=d, offset=m.offset - origin, stride=m.stride), + ) + + +def _decompose_basic(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: + return _decompose(transform, _push_slice_for_dimension_map) + + +def _decompose_unit_step(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: + return _decompose(transform, _push_unit_slice_for_dimension_map) + + +def _decompose( + transform: IndexTransform, + push_dimension_map: Callable[[DimensionMap, IndexTransform], tuple[slice, DimensionMap]], +) -> tuple[tuple[slice, ...], IndexTransform]: + key: list[slice] = [] + residual: list[OutputIndexMap] = [] + for output_map in transform.output: + if isinstance(output_map, ConstantMap): + coordinate = checked_affine(output_map.offset, 0, 0) + key.append(slice(coordinate, coordinate + 1, 1)) + residual.append(ConstantMap(offset=0)) + elif isinstance(output_map, DimensionMap): + pushed, local = push_dimension_map(output_map, transform) + key.append(pushed) + residual.append(local) + else: + coordinates = checked_affine( + output_map.offset, output_map.stride, output_map.index_array + ) + if coordinates.size == 0: + key.append(slice(0, 0, 1)) + local_index = coordinates + else: + origin = int(coordinates.min()) + key.append(slice(origin, int(coordinates.max()) + 1, 1)) + local_index = checked_affine(-origin, 1, coordinates) + residual.append(ArrayMap(index_array=local_index)) + return tuple(key), IndexTransform(domain=transform.domain, output=tuple(residual)) diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py b/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py new file mode 100644 index 0000000000..e98d051900 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py @@ -0,0 +1,57 @@ +"""Test support for projects whose arrays are read through `LazyArray`. + +A Hypothesis state machine that composes indexing steps onto a `LazyArray` +wrapping your array and checks every step against NumPy +([`stateful`][zarr_indexing.testing.stateful]), and the selection strategies it +draws from, exported on their own for a project that has its own harness +([`strategies`][zarr_indexing.testing.strategies]). + +```python +from zarr_indexing.testing import ChainedIndexingStateMachine, state_machine_test + +class MyArrayIndexing(ChainedIndexingStateMachine): + def make_source(self, data): + array = my_format.create(shape=data.shape, dtype=data.dtype) + array[:] = data + return array + +TestMyArrayIndexing = state_machine_test(MyArrayIndexing) +``` + +This subpackage needs `hypothesis`, which the rest of `zarr_indexing` does not: +install it with the `testing` extra (`pip install zarr-indexing[testing]`). +""" + +from zarr_indexing.testing.stateful import ( + DEFAULT_DATA, + DEFAULT_PARTITIONINGS, + DEFAULT_SETTINGS, + ChainedIndexingStateMachine, + apply_selection, + outer_selection, + repartition, + state_machine_test, +) +from zarr_indexing.testing.strategies import ( + basic_selections, + masks, + orthogonal_selections, + slice_selections, + vectorized_selections, +) + +__all__ = [ + "DEFAULT_DATA", + "DEFAULT_PARTITIONINGS", + "DEFAULT_SETTINGS", + "ChainedIndexingStateMachine", + "apply_selection", + "basic_selections", + "masks", + "orthogonal_selections", + "outer_selection", + "repartition", + "slice_selections", + "state_machine_test", + "vectorized_selections", +] diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py new file mode 100644 index 0000000000..4458d7922a --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py @@ -0,0 +1,380 @@ +"""A stateful property test for indexing an array through `LazyArray`. + +`ChainedIndexingStateMachine` composes indexing steps onto a `LazyArray` +wrapping *your* array — `lazy[...]`, `lazy.oindex[...]`, `lazy.vindex[...]`, +each step applied to the view the last one produced — while applying the same +steps to a NumPy array holding the same values. After every step the view must +still agree with that model three ways: its shape, its `result()`, and the +assembly of its `parts()`. + +Point it at an array by subclassing and overriding `make_source`: + +```python +from zarr_indexing.testing import ChainedIndexingStateMachine, state_machine_test + +class MyArrayIndexing(ChainedIndexingStateMachine): + def make_source(self, data): + array = my_format.create(shape=data.shape, dtype=data.dtype) + array[:] = data + return array + +TestMyArrayIndexing = state_machine_test(MyArrayIndexing) +``` + +`data`, `partitionings`, and `readers` are class attributes; override any of +them to widen or narrow what is drawn. The base class needs no `make_source` at +all — left alone it wraps the NumPy array itself, which is a useful smoke test +of this package but says nothing about yours. + +What it is checking +------------------- +The parts invariant is the one with teeth. +[`Partition`][zarr_indexing.lazy_array.Partition] documents +`out[part.out_selection] = part.view.result()` as the assembly procedure, so +this checks that literally: a part's values must arrive at exactly the shape its +`out_selection` addresses — not merely a shape that broadcasts into it — land +there, and cover the view once. Checking through `result()` alone would prove +only that `result()` is self-consistent. + +The `choose_reader` rule draws a reader and applies it to the view, so the +execution strategy becomes part of the chain. Every reader listed by a subclass +must preserve the NumPy model for its source. The universal `basic_reader` is +always exercised, even when a subclass lists only specialized readers; with no +declared readers it is the sole strategy drawn. + +Requires the `testing` extra (`pip install zarr-indexing[testing]`). +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, ClassVar + +import numpy as np +from hypothesis import HealthCheck, settings +from hypothesis import strategies as st +from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, precondition, rule + +from zarr_indexing.lazy_array import LazyArray +from zarr_indexing.reader import Reader, basic_reader +from zarr_indexing.testing.strategies import ( + basic_selections, + orthogonal_selections, + slice_selections, + vectorized_selections, +) + +if TYPE_CHECKING: + from zarr_indexing.boundary import SelectionMode + +__all__ = [ + "DEFAULT_DATA", + "DEFAULT_PARTITIONINGS", + "DEFAULT_SETTINGS", + "ChainedIndexingStateMachine", + "apply_selection", + "outer_selection", + "repartition", + "state_machine_test", +] + +DEFAULT_DATA = np.arange(7 * 5 * 4, dtype=np.int64).reshape(7, 5, 4) +"""The values the source holds by default: distinct, so a misplaced cell shows.""" + +DEFAULT_PARTITIONINGS: tuple[Any, ...] = ( + None, + (2, 2, 2), + (7, 5, 4), + (3, 2, 3), + ((3, 3, 1), (2, 2, 1), (3, 1)), + (4, 3, 3), +) +"""Partitionings to read under: a single whole-array part, uniform boxes of +several shapes (some of which do not divide the extent), and explicit per-axis +sizes. Boxes that straddle whatever the source declares are deliberate — they +cost extra I/O but must not change an answer.""" + +DEFAULT_SETTINGS = settings( + max_examples=250, + stateful_step_count=10, + deadline=None, + suppress_health_check=[ + HealthCheck.data_too_large, + HealthCheck.filter_too_much, + HealthCheck.too_slow, + ], +) +"""Enough examples to find a defect reachable only through a narrow chain, at a +few seconds per run when there is nothing to find. Every step is followed by +checks that each materialize the whole view, so the budget buys examples rather +than long chains — a chain runs out of axes to index within a few steps anyway. + +`filter_too_much` is suppressed because a chain that reaches a rank-0 view +leaves only `repartition` enabled, so a run that opens there is discarded.""" + + +# --------------------------------------------------------------------------- # +# The NumPy model +# --------------------------------------------------------------------------- # + + +def outer_selection(array: Any, selection: Sequence[Any]) -> Any: + """Apply an orthogonal selection to a NumPy array: the outer product of its axes. + + NumPy has no operator for this, so the model is built from `numpy.ix_`. + Scalar integers are basic indices — NumPy applies them first and drops the + axis — so they are peeled off before the outer product is formed. + """ + + def is_scalar(sel: Any) -> bool: + return isinstance(sel, (int, np.integer)) and not isinstance(sel, bool) + + scalars = tuple(sel if is_scalar(sel) else slice(None) for sel in selection) + reduced = array[scalars] + axes = [ + np.arange(size)[sel] + for size, sel in zip(reduced.shape, [s for s in selection if not is_scalar(s)], strict=True) + ] + if len(axes) == 0: + return reduced + return reduced[np.ix_(*axes)] + + +def apply_selection(array: Any, selection: tuple[Any, ...], mode: SelectionMode) -> Any: + """Apply a selection to a NumPy array in the given mode — the model a view is checked against. + + NumPy's own semantics *are* basic and vectorized indexing, so only the + orthogonal mode needs building (see `outer_selection`). + """ + if mode == "orthogonal": + return outer_selection(array, selection) + return array[selection] + + +def state_machine_test( + machine: type[RuleBasedStateMachine], *, config: settings = DEFAULT_SETTINGS +) -> Any: + """The pytest-collectable `TestCase` for a machine, with settings applied. + + Hypothesis builds a fresh `TestCase` per state-machine class, so settings + set on a base class do not reach a subclass's; this applies them where they + land. Assign the result to a module-level name beginning with `Test`. + """ + case = machine.TestCase + case.settings = config + return case + + +def repartition(view: LazyArray, parts: Any) -> LazyArray: + """Apply one of `partitionings` to a view. + + The three partitioning spellings are three named methods, so a list holding + a mix of them needs a dispatch somewhere. Choosing among them is what a test + harness drawing from that list is doing, so it lives here rather than being + pushed back into the public API as a type-inspecting parameter. + """ + if parts is None: + return view.unpartitioned() + if any(isinstance(entry, Sequence) for entry in parts): + return view.with_parts_per_axis(parts) + return view.with_parts(parts) + + +# --------------------------------------------------------------------------- # +# The machine +# --------------------------------------------------------------------------- # + +_SOURCE = "_zarr_indexing_cached_source" + + +class ChainedIndexingStateMachine(RuleBasedStateMachine): + """Indexing steps composed onto one `LazyArray`, against NumPy as the model. + + Subclass and override `make_source` to point it at your own array. See the + module docstring for the shape of that subclass and for what the invariants + check. + + Attributes + ---------- + data + The values the source holds, and the model every step is checked + against. Any shape and dtype NumPy supports; every axis must be + non-empty. + partitionings + Drawn once per run, before any indexing: `with_parts` is a pure setter + that carries through composition untouched and is read only when a view + resolves, so choosing it up front reaches the same states choosing it + mid-chain does, and spends the whole step budget on indexing. + readers + Execution strategies `choose_reader` may draw. Every listed reader must + preserve the model for the source. `basic_reader` is always included; + `None` means the reader already carried by the constructed view. + """ + + data: ClassVar[Any] = DEFAULT_DATA + partitionings: ClassVar[Sequence[Any]] = DEFAULT_PARTITIONINGS + readers: ClassVar[Sequence[Reader] | None] = None + + def make_source(self, data: Any) -> Any: + """Build the array under test, holding `data`. + + Called once per machine class and cached, not once per example: an + example is cheap and a source may not be. The machine only ever reads, + so the same object serves every run — but it must therefore not be + mutated by anything else while the test runs. + + The default returns `data` itself, so an unsubclassed machine exercises + this package against NumPy. + """ + return data + + def __init__(self) -> None: + super().__init__() + cls = type(self) + self.model: Any = np.asarray(cls.data) + source = cls.__dict__.get(_SOURCE) + if source is None: + source = self.make_source(self.model) + setattr(cls, _SOURCE, source) + self.view = LazyArray(source) + self.reader_choices = _reader_set(self.view, cls.readers) + self.chain: list[tuple[str, Any]] = [] + + def _indexable(self) -> bool: + """Whether there is anything left to index. + + A rank-0 or empty view takes no further step — NumPy would reject one + too — so the chain ends there, and the invariants keep checking. + """ + return self.model.ndim > 0 and self.model.size > 0 + + def _step(self, mode: SelectionMode, selection: tuple[Any, ...]) -> None: + self.chain.append((mode, selection)) + self.model = apply_selection(self.model, selection, mode) + if mode == "basic": + self.view = self.view.lazy[selection] + elif mode == "orthogonal": + self.view = self.view.lazy.oindex[selection] + else: + self.view = self.view.lazy.vindex[selection] + + # -- rules -------------------------------------------------------------- + + @initialize(data=st.data()) + def choose_partitioning(self, data: st.DataObject) -> None: + """Fix how the read is broken up, before any indexing.""" + parts = data.draw(st.sampled_from(list(type(self).partitionings))) + self.view = repartition(self.view, parts) + self.chain.append(("parts", parts)) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def basic(self, data: st.DataObject) -> None: + self._step("basic", data.draw(basic_selections(self.model.shape))) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def orthogonal(self, data: st.DataObject) -> None: + self._step("orthogonal", data.draw(orthogonal_selections(self.model.shape))) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def vectorized(self, data: st.DataObject) -> None: + self._step("vectorized", data.draw(vectorized_selections(self.model.shape))) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def slices_only(self, data: st.DataObject) -> None: + """An `oindex` step carrying only slices is not a fancy selection. + + It narrows the view's own axes and composes like basic indexing. Drawn + as its own rule so that narrowing an existing index array by slices — + a distinct code path from narrowing it with coordinates — stays + exercised at full weight. + """ + self._step("orthogonal", data.draw(slice_selections(self.model.shape))) + + @rule(data=st.data()) + def choose_reader(self, data: st.DataObject) -> None: + """Read the rest of the chain through another conforming strategy.""" + reader = data.draw(st.sampled_from(list(self.reader_choices))) + self.view = self.view.with_reader(reader) + self.chain.append(("reader", type(reader).__qualname__)) + + @precondition(lambda self: not self._indexable()) + @rule(data=st.data()) + def repartition(self, data: st.DataObject) -> None: + """Re-box a chain that has run out of axes to index. + + Something must stay enabled once the view is rank-0 or empty, or + Hypothesis has no move to make and abandons the run. Re-boxing is the + useful thing to do there: it changes nothing the invariants may see, and + a rank-0 view read through every partitioning is exactly the state a + collapsed correlated selection reaches. + """ + parts = data.draw(st.sampled_from(list(type(self).partitionings))) + self.view = repartition(self.view, parts) + self.chain.append(("parts", parts)) + + # -- invariants --------------------------------------------------------- + + @invariant() + def the_view_has_the_models_shape(self) -> None: + assert self.view.shape == self.model.shape, self.chain + + @invariant() + def result_matches_the_model(self) -> None: + np.testing.assert_array_equal( + np.asarray(self.view.result()), self.model, err_msg=str(self.chain) + ) + + @invariant() + def parts_tile_the_view(self) -> None: + """The documented assembly, run literally. + + Every part's values arrive at exactly the shape its `out_selection` + addresses — not merely a shape that broadcasts into it — and together + the parts cover the view once. + """ + assembled = np.zeros(self.view.shape, dtype=self.view.dtype) + hits = np.zeros(self.view.shape, dtype=np.int64) + for part in self.view.parts(): + value = np.asarray(part.view.result()) + assert value.shape == assembled[part.out_selection].shape, ( + f"part {part.base_coords} carries {value.shape} for an out_selection " + f"addressing {assembled[part.out_selection].shape}: {self.chain}" + ) + # `is_complete` is what a consumer reads to decide it may take a + # whole-box read and skip assembling anything, so a wrongly-`True` + # one is the silent-corruption case. Asserted one way only: the flag + # is documented as conservative, free to say `False` about a part it + # does cover (a strided walk over a one-cell box, a fancy axis that + # happens to enumerate everything), and only the claim to cover + # everything has to be earned. Both quantities are already in hand + # here, and nothing else in the suite compares them. + if part.is_complete: + box_cells = math.prod(stop - start for start, stop in part.box) + assert value.size == box_cells, ( + f"part {part.base_coords} reports is_complete but carries " + f"{value.size} of its box's {box_cells} cells: {self.chain}" + ) + assembled[part.out_selection] = value + np.add.at(hits, part.out_selection, 1) + + np.testing.assert_array_equal(assembled, self.model, err_msg=str(self.chain)) + np.testing.assert_array_equal( + hits, np.ones(self.view.shape, dtype=np.int64), err_msg=str(self.chain) + ) + + +def _reader_set(view: LazyArray, declared: Sequence[Reader] | None) -> tuple[Reader, ...]: + """The readers `choose_reader` draws from, `basic_reader` always among them.""" + readers = list(declared) if declared is not None else [view.reader] + if all(reader is not basic_reader for reader in readers): + readers.insert(0, basic_reader) + unique: list[Reader] = [] + for reader in readers: + if all(reader is not existing for existing in unique): + unique.append(reader) + return tuple(unique) diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py b/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py new file mode 100644 index 0000000000..63a3d351a9 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py @@ -0,0 +1,207 @@ +"""Hypothesis strategies for the selections `LazyArray` accepts. + +Each strategy takes the shape of the array being indexed and generates one +selection for it — an index tuple with one entry per axis, in the spelling its +mode expects. They are the generators behind +[`ChainedIndexingStateMachine`][zarr_indexing.testing.stateful.ChainedIndexingStateMachine] +and are exported on their own for a project that has its own test harness and +wants only the hard part. + +```python +from hypothesis import given, strategies as st +from zarr_indexing.testing.strategies import basic_selections + +@given(selection=basic_selections((7, 5, 4))) +def test_my_array_slices_like_numpy(selection): + assert_array_equal(my_array[selection], reference[selection]) +``` + +Every axis of `shape` must be non-empty: a selection over an axis of extent 0 +has no coordinates to draw. Filter or narrow the shape before calling. + +Requires the `testing` extra (`pip install zarr-indexing[testing]`). +""" + +from __future__ import annotations + +import operator +from typing import TYPE_CHECKING, Any + +import numpy as np +from hypothesis import strategies as st + +if TYPE_CHECKING: + from collections.abc import Callable + +__all__ = [ + "basic_selections", + "empty_masks", + "masks", + "orthogonal_selections", + "slice_selections", + "vectorized_selections", +] + + +def _entries(shape: tuple[int, ...], entry: Callable[[int], st.SearchStrategy[Any]]) -> Any: + """One `entry` strategy per axis, as an index tuple.""" + return st.tuples(*[entry(size) for size in shape]) + + +def _basic_entry(size: int) -> st.SearchStrategy[Any]: + steps = st.integers(1, 3) + return st.one_of( + # A scalar integer drops its axis, in every mode, exactly as NumPy does. + st.integers(-size, size - 1), + st.builds(slice, st.integers(0, size), st.integers(0, size), steps), + # Downward. The start is drawn from below `-size` as well, where the walk + # begins off the front and selects nothing — a case that reads as an + # ordinary negative index but is empty — and a stop that falls off the + # front is spelled `None`. + st.builds( + slice, + st.integers(-2 * size - 1, size - 1), + st.none() | st.integers(0, size), + steps.map(operator.neg), + ), + st.just(slice(None)), + ) + + +def _orthogonal_entry(size: int) -> st.SearchStrategy[Any]: + """One axis of an `oindex` selection. + + The slices carry a step and are free to stop early. Drawing them as + `slice(start, size)` alone meant no strided or reversed slice ever reached + `oindex`, and no orthogonal selection ever stopped short of the axis end. + + An empty coordinate list is drawn too. It selects nothing, which is legal + and is exactly the shape that lost its axis on the way through JSON — but + with `min_size=1` no fancy selection was ever empty. + """ + coordinate = st.integers(-size, size - 1) + return st.one_of( + coordinate, + st.lists(coordinate, min_size=1, max_size=4), + st.just([]), + masks((size,)), + empty_masks((size,)), + st.builds( + slice, + st.integers(0, size - 1), + st.integers(0, size) | st.none(), + st.integers(1, 3) | st.integers(-3, -1), + ), + ) + + +def _slice_entry(size: int) -> st.SearchStrategy[slice]: + return st.one_of( + st.builds(slice, st.integers(0, size - 1), st.just(size), st.integers(1, 2)), + st.just(slice(None, None, -1)), + st.just(slice(None)), + ) + + +@st.composite +def masks(draw: st.DrawFn, shape: tuple[int, ...]) -> np.ndarray[Any, np.dtype[np.bool_]]: + """Boolean masks over `shape`, each selecting at least one cell. + + An all-False mask is legal but is a separate concern — it empties the view, + and a chain of selections is more interesting when every step leaves + something to index — so one cell is always forced True. + """ + size = int(np.prod(shape)) + flags = np.array(draw(st.lists(st.booleans(), min_size=size, max_size=size))) + flags[draw(st.integers(0, size - 1))] = True + return flags.reshape(shape) + + +def empty_masks(shape: tuple[int, ...]) -> st.SearchStrategy[np.ndarray[Any, np.dtype[np.bool_]]]: + """The all-False mask over `shape` — a fancy selection that empties the view. + + Split out from `masks`, which forces a cell True so a chain has something + left to index at the next step. Drawn on its own because an empty fancy + selection is a shape the code paths treat separately, and nothing generated + one. + """ + return st.just(np.zeros(shape, dtype=np.bool_)) + + +def basic_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ...]]: + """Basic selections: one scalar integer or slice per axis. + + Slices run in both directions, including the two empty spellings — a + forward slice whose stop precedes its start, and a backward one whose start + is off the front of the axis. + """ + return _entries(shape, _basic_entry) + + +def orthogonal_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ...]]: + """Orthogonal (`oindex`) selections: an outer product of per-axis choices. + + Each axis draws a scalar, a coordinate list (unsorted, with duplicates), a + boolean mask, or a slice. + """ + return _entries(shape, _orthogonal_entry) + + +def slice_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ...]]: + """Selections of slices alone, for the `oindex` spelling that carries no coordinates. + + Such a step is not a fancy selection — it narrows the view's own axes and + composes like basic indexing — so it is legal after a fancy step, where + genuine coordinates are not. The starts reach past the origin, which is what + distinguishes a step that walks an existing index array's dependency axes + from one that walks its broadcast singletons. + """ + return _entries(shape, _slice_entry) + + +@st.composite +def vectorized_selections(draw: st.DrawFn, shape: tuple[int, ...]) -> tuple[Any, ...]: + """Vectorized (`vindex`) selections over a leading or trailing block of axes. + + `vindex` is coordinate-only — it rejects a slice outright — so a partial + selection names its axes by position: a leading block, or a trailing one + reached through an ellipsis. Either a single boolean mask spanning the whole + covered block, or one entry per axis, each a coordinate array or a scalar + (a scalar being a basic index NumPy applies before the coordinates). + """ + ndim = len(shape) + trailing = draw(st.booleans()) + count = draw(st.integers(1, ndim)) + axes = range(ndim - count, ndim) if trailing else range(count) + sizes = [shape[axis] for axis in axes] + + entries: list[Any] + if draw(st.booleans()): + entries = [draw(masks(tuple(sizes)))] + else: + # The coordinate arrays share one shape, which is what makes the + # selection correlated. That shape is not always one-dimensional: a + # vectorized read of a (2, 3) block of points is an ordinary thing to + # ask for and produces a result of that rank. Drawing only 1-D arrays + # meant no rank-raising vindex was ever generated — and a length of 0 + # covers the empty case the same way `_orthogonal_entry` does. + coordinate_shape = draw( + st.one_of( + st.integers(0, 4).map(lambda length: (length,)), + st.tuples(st.integers(1, 2), st.integers(1, 3)), + ) + ) + entries = [ + draw( + st.one_of( + st.integers(-size, size - 1), + st.lists( + st.integers(-size, size - 1), + min_size=int(np.prod(coordinate_shape)), + max_size=int(np.prod(coordinate_shape)), + ).map(lambda values: np.array(values, dtype=np.intp).reshape(coordinate_shape)), + ) + ) + for size in sizes + ] + return (Ellipsis, *entries) if trailing else tuple(entries) diff --git a/packages/zarr-indexing/src/zarr_indexing/transform.py b/packages/zarr-indexing/src/zarr_indexing/transform.py new file mode 100644 index 0000000000..a8a5963a26 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/transform.py @@ -0,0 +1,1941 @@ +"""Index transforms — composable, lazy coordinate mappings. + +An `IndexTransform` pairs an **input domain** (the coordinates a user sees) +with a tuple of **output maps** (the output coordinates those inputs map to). +One output map per output dimension. See `output_map.py` for the three +output map types. + +Key operations: + +- **Indexing** (`transform[2:8]`, `.oindex[idx]`, `.vindex[idx]`) — + produces a new transform with a narrower input domain and adjusted output + maps. No I/O occurs. This is how lazy slicing works. + +- **intersect(output_domain)** — restrict to output coordinates within a + region. This is chunk resolution: "which of my coordinates fall in this + chunk?" + +- **translate(shift)** — shift all output coordinates. This makes coordinates + chunk-local: "express my coordinates relative to the chunk origin." + +- **`transform.compose(inner)`** — chain two transforms into one. + +The transform is the atomic unit that connects user-facing indexing to +chunk-level I/O. A wrapper holds one — `LazyArray` starts from the identity — +and `.lazy[...]` composes a new transform lazily rather than reading. Reading +resolves the transform against the chunk grid via intersect + translate. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal, cast + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing._selector import as_scalar_index, require_index +from zarr_indexing.boundary import validate_advanced_selection +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError, VindexInvalidSelectionError +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + OutputIndexMap, + array_map_or_constant, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + + import numpy.typing as npt + + from zarr_indexing.json import IndexTransformJSON + + +@dataclass(frozen=True, slots=True) +class _PointOutOfBounds(Exception): + """Internal signal from the shared point kernel: one coordinate left the domain. + + Never escapes this module. `apply` and `apply_many` format it as the + public `BoundsCheckError`, each in its own vocabulary — the kernel knows + batches, but a single-point caller must never hear about them. + """ + + dimension: int + value: int + lower: int + upper: int + batch_position: tuple[int, ...] + + +@dataclass(frozen=True, slots=True) +class IndexTransform: + """A composable mapping from input coordinates to output coordinates. + + An `IndexTransform` has: + + - `domain`: an `IndexDomain` describing the valid input coordinates + (the result's coordinate range, possibly with non-zero origin). + - `output`: a tuple of output maps (one per output dimension), each + describing which output coordinates the inputs touch. + + In array-indexing terms: `domain` describes the coordinates of the result + array an indexing operation produces, and `output` is the rule relating + each result coordinate to a coordinate in the source. Note the direction — + the transform's input side is the result, its output side addresses the + source; the coordinate mapping runs opposite to the data flow. + + Indexing an existing transform composes a new one without I/O. + + Examples + -------- + The operation "every other element of a 100-element array, starting at + index 0" — `array[::2]` — is a 50-cell domain whose cell `i` reads + output coordinate `2 * i`: + + >>> domain = IndexDomain.from_shape((50,)) + >>> output = (DimensionMap(input_dimension=0, offset=0, stride=2),) + >>> transform = IndexTransform(domain=domain, output=output) + >>> transform.apply((0,)), transform.apply((1,)), transform.apply((49,)) + ((0,), (2,), (98,)) + + The selection compiler derives the identical transform from the source's + shape and the slice: + + >>> transform == IndexTransform.from_shape((100,))[::2] + True + """ + + domain: IndexDomain + """The input domain: the request coordinates this transform accepts.""" + + output: tuple[OutputIndexMap, ...] + """One output map per output dimension, each producing that dimension's coordinate.""" + + def __post_init__(self) -> None: + for i, m in enumerate(self.output): + if isinstance(m, DimensionMap): + if m.input_dimension < 0 or m.input_dimension >= self.domain.ndim: + raise ValueError( + f"output[{i}].input_dimension = {m.input_dimension} " + f"is out of range for input rank {self.domain.ndim}" + ) + elif isinstance(m, ArrayMap): + # An index array carries the transform's full input rank: the axis + # a map varies over is full-sized, every other axis a singleton. + # The rank is what makes the dependency axes readable from the + # shape, so a mismatch is a bug rather than a spelling. External + # JSON may use a lower-rank array that broadcasts against the + # domain; `from_json` widens those on the way in, + # so the invariant holds for every transform that exists. + if m.index_array.ndim != self.domain.ndim: + raise ValueError( + f"output[{i}].index_array has {m.index_array.ndim} dims " + f"but input domain has {self.domain.ndim} dims" + ) + # Every axis is either the domain's extent or a singleton it + # broadcasts over. Any other size addresses input coordinates the + # array has no entry for, which reads as a smaller selection + # rather than as the error it is. + bad = [ + (axis, size, extent) + for axis, (size, extent) in enumerate( + zip(m.index_array.shape, self.domain.shape, strict=True) + ) + if size not in (1, extent) + ] + if len(bad) > 0: + axis, size, extent = bad[0] + raise ValueError( + f"output[{i}].index_array has {size} entries on axis {axis}, " + f"which is neither 1 nor the domain's extent of {extent} " + f"(index_array shape {m.index_array.shape}, " + f"domain shape {self.domain.shape})" + ) + + def __eq__(self, other: object) -> bool: + """Value equality. `ArrayMap` compares its index array element-wise, so + a transform holding one can be compared at all — the generated `__eq__` + raised `ValueError: the truth value of an array ... is ambiguous`.""" + if not isinstance(other, IndexTransform): + return NotImplemented + return self.domain == other.domain and self.output == other.output + + def __hash__(self) -> int: + """Hashed by value, so a transform can key a cache or enter a set.""" + return hash((self.domain, self.output)) + + @property + def input_rank(self) -> int: + """Number of input dimensions — the rank of `domain`.""" + return self.domain.ndim + + @property + def output_rank(self) -> int: + """Number of output dimensions — one per output map.""" + return len(self.output) + + @classmethod + def identity(cls, domain: IndexDomain) -> IndexTransform: + """The identity transform over `domain`: every result cell reads the source at its own address.""" + output = tuple(DimensionMap(input_dimension=i) for i in range(domain.ndim)) + return cls(domain=domain, output=output) + + @classmethod + def from_shape(cls, shape: tuple[int, ...]) -> IndexTransform: + """The identity transform over a zero-origin domain of the given `shape`.""" + return cls.identity(IndexDomain.from_shape(shape)) + + def apply(self, point: Sequence[int]) -> tuple[int, ...]: + """Map one coordinate of `domain` to the source coordinate that fills it. + + In array-indexing terms: `point` names a cell of the result array, and + the returned tuple — each `output` map evaluated at `point` — names the + source-array cell its value is read from: the coordinate arrow, + running result to source. + + Parameters + ---------- + point : Sequence[int] + One literal coordinate for each input dimension. + + Returns + ------- + tuple[int, ...] + One coordinate for each output map. + + Raises + ------ + ValueError + If ``point`` does not have exactly one coordinate per input + dimension. + TypeError + If the coordinates do not have an integer dtype. + BoundsCheckError + If a coordinate lies outside the input domain. + OverflowError + If a mapped output coordinate cannot be represented by + ``np.intp``. + + Examples + -------- + The `[::2]` transform reads result cell `i` from source coordinate + `2 * i`, so cell 3 of the result holds `source[6]`: + + >>> transform = IndexTransform.from_shape((100,))[::2] + >>> transform.apply((3,)) + (6,) + """ + coordinates = np.asarray(point) + expected_shape = (self.input_rank,) + if coordinates.shape != expected_shape: + raise ValueError(f"point must have shape {expected_shape}, got {coordinates.shape}") + # An empty Python sequence has no elements from which NumPy can infer + # an integer dtype, but it is the unique point in a rank-zero domain. + if self.input_rank == 0 and isinstance(point, (list, tuple)): + coordinates = coordinates.astype(np.intp) + try: + result = self._apply_points(coordinates) + except _PointOutOfBounds as error: + raise BoundsCheckError( + f"coordinate {error.value} on input dimension {error.dimension} " + f"is outside the domain [{error.lower}, {error.upper})" + ) from None + return tuple(int(value) for value in result) + + def apply_many(self, points: npt.ArrayLike) -> npt.NDArray[np.intp]: + """Map a batch of `domain` coordinates to the source coordinates that fill them. + + The vectorized form of `apply`: each row of `points` names a result + cell, and the corresponding output row names the source-array cell + its value is read from. + + Parameters + ---------- + points : numpy.typing.ArrayLike + Integer coordinates with shape ``batch_shape + (input_rank,)``. + + Returns + ------- + numpy.typing.NDArray[numpy.intp] + An owned array with shape ``batch_shape + (output_rank,)``. + + Raises + ------ + ValueError + If ``points`` has no trailing coordinate axis or that axis does + not contain exactly one coordinate per input dimension. + TypeError + If the coordinates do not have an integer dtype. + BoundsCheckError + If a coordinate lies outside the input domain. + OverflowError + If a mapped output coordinate cannot be represented by + ``np.intp``. + + Examples + -------- + Three result cells of the `[::2]` transform, located in one call: + + >>> transform = IndexTransform.from_shape((100,))[::2] + >>> transform.apply_many(np.array([[0], [1], [49]])).tolist() + [[0], [2], [98]] + """ + coordinates = np.asarray(points) + if coordinates.ndim == 0 or coordinates.shape[-1] != self.input_rank: + raise ValueError( + "points must have a trailing coordinate axis of size " + f"{self.input_rank}, got shape {coordinates.shape}" + ) + try: + return self._apply_points(coordinates) + except _PointOutOfBounds as error: + raise BoundsCheckError( + f"point at batch position {error.batch_position} has input dimension " + f"{error.dimension} coordinate {error.value} outside " + f"[{error.lower}, {error.upper})" + ) from None + + def _apply_points(self, points: np.ndarray[Any, Any]) -> npt.NDArray[np.intp]: + """Vectorized implementation shared by ``apply`` and ``apply_many``. + + Out-of-domain coordinates raise the internal `_PointOutOfBounds` + signal; each public entry point formats it in its own vocabulary — + `apply` never mentions a batch, `apply_many` names the batch position.""" + if not np.issubdtype(points.dtype, np.integer): + raise TypeError(f"points must have an integer dtype, got {points.dtype}") + + invalid = np.zeros(points.shape, dtype=np.bool_) + for dimension, (lower, upper) in enumerate( + zip(self.domain.inclusive_min, self.domain.exclusive_max, strict=True) + ): + invalid[..., dimension] = (points[..., dimension] < lower) | ( + points[..., dimension] >= upper + ) + invalid_positions = np.argwhere(invalid) + if invalid_positions.size > 0: + first = invalid_positions[0] + dimension = int(first[-1]) + batch_position = tuple(int(position) for position in first[:-1]) + point_index = tuple(int(position) for position in first) + value = int(points[point_index]) + lower = self.domain.inclusive_min[dimension] + upper = self.domain.exclusive_max[dimension] + raise _PointOutOfBounds(dimension, value, lower, upper, batch_position) + + batch_shape = points.shape[:-1] + result = np.empty(batch_shape + (self.output_rank,), dtype=np.intp) + for output_dimension, output_map in enumerate(self.output): + if isinstance(output_map, ConstantMap): + if result[..., output_dimension].size == 0: + continue + result[..., output_dimension] = checked_affine(output_map.offset, 0, 0) + elif isinstance(output_map, DimensionMap): + result[..., output_dimension] = checked_affine( + output_map.offset, + output_map.stride, + points[..., output_map.input_dimension], + ) + else: + index = tuple( + np.zeros(batch_shape, dtype=np.intp) + if output_map.index_array.shape[axis] == 1 + else _positions_from_origin(points[..., axis], self.domain.inclusive_min[axis]) + for axis in range(self.input_rank) + ) + result[..., output_dimension] = checked_affine( + output_map.offset, + output_map.stride, + np.asarray(output_map.index_array[index]), + ) + return result + + def inverted(self) -> IndexTransform: + """Return the restricted, exactly representable inverse transform. + + Inversion is defined for square transforms containing only constants + and unique unit-stride dimension maps. Any input dimension not named by + a dimension map must have singleton extent, so its coordinate can be + recovered as a constant. + + Returns + ------- + IndexTransform + A new transform mapping output coordinates back to input + coordinates. + + Raises + ------ + ValueError + If this transform does not have a representable inverse, including + when input labels cannot be transferred to unlabeled output + dimensions. + """ + if self.domain.labels is not None: + raise ValueError( + "cannot invert transform: input labels cannot be represented " + "because output dimensions do not carry labels" + ) + if self.input_rank != self.output_rank: + raise ValueError( + "cannot invert transform: input rank must equal output rank, got " + f"{self.input_rank} and {self.output_rank}" + ) + + referenced: set[int] = set() + for output_dimension, output_map in enumerate(self.output): + if isinstance(output_map, ArrayMap): + raise ValueError( # noqa: TRY004 - valid map, invalid inverse + f"cannot invert transform: output[{output_dimension}] is an ArrayMap" + ) + if isinstance(output_map, DimensionMap): + if output_map.stride not in (-1, 1): + raise ValueError( + "cannot invert transform: DimensionMap stride must be +1 or -1, " + f"got {output_map.stride} for output[{output_dimension}]" + ) + if output_map.input_dimension in referenced: + raise ValueError( + "cannot invert transform: input dimension " + f"{output_map.input_dimension} is referenced more than once" + ) + referenced.add(output_map.input_dimension) + + for input_dimension, extent in enumerate(self.domain.shape): + if input_dimension not in referenced and extent != 1: + raise ValueError( + "cannot invert transform: unreferenced input dimension " + f"{input_dimension} has extent {extent}, not 1" + ) + + inverse_min: list[int] = [] + inverse_max: list[int] = [] + inverse_output: dict[int, OutputIndexMap] = {} + for output_dimension, output_map in enumerate(self.output): + if isinstance(output_map, ConstantMap): + inverse_min.append(output_map.offset) + inverse_max.append(output_map.offset + 1) + continue + + assert isinstance(output_map, DimensionMap) + input_dimension = output_map.input_dimension + lower = self.domain.inclusive_min[input_dimension] + upper = self.domain.exclusive_max[input_dimension] + if output_map.stride == 1: + inverse_min.append(output_map.offset + lower) + inverse_max.append(output_map.offset + upper) + inverse_output[input_dimension] = DimensionMap( + output_dimension, + offset=-output_map.offset, + ) + else: + inverse_min.append(output_map.offset - upper + 1) + inverse_max.append(output_map.offset - lower + 1) + inverse_output[input_dimension] = DimensionMap( + output_dimension, + offset=output_map.offset, + stride=-1, + ) + + for input_dimension, lower in enumerate(self.domain.inclusive_min): + if input_dimension not in referenced: + inverse_output[input_dimension] = ConstantMap(lower) + + return IndexTransform( + domain=IndexDomain(tuple(inverse_min), tuple(inverse_max)), + output=tuple(inverse_output[dimension] for dimension in range(self.input_rank)), + ) + + @property + def selection_repr(self) -> str: + """Compact domain string, e.g. `'{ [2, 8), [0, 10) }'`. + + Follows TensorStore's IndexDomain notation: each dimension shown + as `[inclusive_min, exclusive_max)` with stride annotation if not 1. + Constant (integer-indexed) dimensions show as a single value. + Array-indexed dimensions show the set of selected coordinates. + """ + parts: list[str] = [] + for m in self.output: + if isinstance(m, ConstantMap): + parts.append(str(m.offset)) + elif isinstance(m, DimensionMap): + d = m.input_dimension + lo = self.domain.inclusive_min[d] + hi = self.domain.exclusive_max[d] + start = m.offset + m.stride * lo + stop = m.offset + m.stride * hi + if m.stride == 1: + parts.append(f"[{start}, {stop})") + else: + parts.append(f"[{start}, {stop}) step {m.stride}") + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + storage = m.offset + m.stride * m.index_array + n = int(storage.size) # .size, not len(): index_array may be 0-d + if n <= 5: + vals = ", ".join(str(int(v)) for v in storage.ravel()) + parts.append("{" + vals + "}") + else: + parts.append("{" + f"array({n})" + "}") + return "{ " + ", ".join(parts) + " }" + + def __repr__(self) -> str: + maps: list[str] = [] + for i, m in enumerate(self.output): + if isinstance(m, ConstantMap): + maps.append(f"out[{i}] = {m.offset}") + elif isinstance(m, DimensionMap): + maps.append(f"out[{i}] = {m.offset} + {m.stride} * in[{m.input_dimension}]") + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + maps.append(f"out[{i}] = {m.offset} + {m.stride} * arr{m.index_array.shape}[in]") + maps_str = ", ".join(maps) + return f"IndexTransform(domain={self.domain}, {maps_str})" + + def intersect( + self, output_domain: IndexDomain + ) -> ( + tuple[ + IndexTransform, + dict[int, np.ndarray[Any, np.dtype[np.intp]]] + | np.ndarray[Any, np.dtype[np.intp]] + | None, + ] + | None + ): + """Keep only the cells whose source coordinates fall inside `output_domain`. + + Chunk resolution is the canonical caller: intersecting a request with + one chunk's box keeps the cells that chunk can serve. + + Returns `(restricted_transform, out_indices)` or None if empty. + + `out_indices` carries the surviving output positions: `None` when all + positions survive (ConstantMap/DimensionMap only), a single integer array + for one ArrayMap (or correlated/vectorized ArrayMaps), or a dict keyed by + output dimension for >= 2 orthogonal ArrayMaps (an outer product). + """ + return _intersect(self, output_domain) + + def translate(self, shift: tuple[int, ...]) -> IndexTransform: + """Shift the source coordinates every cell reads by `shift`, per dimension. + + The domain is untouched: the result keeps its cells, and each one + reads from a shifted source address — for example, making a chunk's + global addresses chunk-local by translating by the chunk's negated + origin. + """ + if len(shift) != self.output_rank: + raise ValueError(f"shift must have length {self.output_rank}, got {len(shift)}") + new_output: list[OutputIndexMap] = [] + for m, s in zip(self.output, shift, strict=True): + if isinstance(m, ConstantMap): + new_output.append(ConstantMap(offset=m.offset + s)) + elif isinstance(m, DimensionMap): + new_output.append( + DimensionMap( + input_dimension=m.input_dimension, + offset=m.offset + s, + stride=m.stride, + ) + ) + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + new_output.append( + ArrayMap( + index_array=m.index_array, + offset=m.offset + s, + stride=m.stride, + ) + ) + return IndexTransform(domain=self.domain, output=tuple(new_output)) + + def __getitem__(self, selection: Any) -> IndexTransform: + """Compose a basic selection (int, slice, ellipsis, newaxis) into a new transform. + + No I/O occurs. Integers and slice bounds are literal domain coordinates + (TensorStore convention): negative values are not counted from the end, + and out-of-domain values raise `BoundsCheckError`. Integer indices drop + their input dimension; `None` inserts a size-1 dimension. + """ + return _apply_basic_indexing(self, selection) + + def translate_domain_by(self, shift: tuple[int, ...]) -> IndexTransform: + """Shift the *input* domain by `shift`, preserving which cells are addressed. + + TensorStore's `translate_by`: the domain moves, and every output map is + re-offset so that new coordinate `c` addresses the cell that `c - shift` + addressed before. ArrayMaps are indexed positionally over the domain, so + their index arrays are unchanged. + """ + if len(shift) != self.input_rank: + raise ValueError(f"shift must have length {self.input_rank}, got {len(shift)}") + new_domain = self.domain.translate(shift) + new_output: list[OutputIndexMap] = [] + for m in self.output: + if isinstance(m, DimensionMap): + s = shift[m.input_dimension] + new_output.append( + DimensionMap( + input_dimension=m.input_dimension, + offset=m.offset - m.stride * s, + stride=m.stride, + ) + ) + else: + # ConstantMap: no input dependence. ArrayMap: positional over + # the domain, invariant under domain translation. + new_output.append(m) + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + def translate_domain_to(self, origins: tuple[int, ...]) -> IndexTransform: + """Move the input domain so its per-dimension origins equal `origins`. + + TensorStore's `translate_to`; `translate_domain_to((0,) * rank)` + re-zeros a view's coordinate system without changing which cells it + addresses. + """ + if len(origins) != self.input_rank: + raise ValueError(f"origins must have length {self.input_rank}, got {len(origins)}") + shift = tuple(o - m for o, m in zip(origins, self.domain.inclusive_min, strict=True)) + return self.translate_domain_by(shift) + + @property + def oindex(self) -> _OIndexHelper: + """Accessor for the orthogonal (outer-product) indexing dialect. + + `transform.oindex[sel]` applies each index array independently per + dimension and returns a new transform. + """ + return _OIndexHelper(self) + + @property + def vindex(self) -> _VIndexHelper: + """Accessor for the vectorized (coordinate/mask) indexing dialect. + + `transform.vindex[sel]` broadcasts all index arrays together, NumPy + fancy-indexing style, and returns a new transform. + """ + return _VIndexHelper(self) + + @property + def index_array_structure(self) -> Literal["none", "orthogonal", "general"]: + """Classify how a transform's index arrays relate to its input axes. + + Returns + ------- + `"none"` when no output map is an `ArrayMap`; `"orthogonal"` when every + `ArrayMap` varies over exactly one input axis, each its own (an outer + product, one independent gather per axis); `"general"` otherwise — + correlated (`vindex`) maps sharing their non-singleton axes, maps produced + by composing fancy steps, maps sharing an input axis (a diagonal gather), + and empty or hand-built all-singleton maps whose shape names no axis. The + orthogonal resolvers narrow one axis at a time and are only sound for + `"orthogonal"`; everything else takes the pointwise path that collapses + the joint block. Everything is read off the index arrays' shapes. + + Examples + -------- + >>> t = IndexTransform.from_shape((4, 5)) + >>> t.index_array_structure + 'none' + + `oindex` arrays each vary over their own axis (an outer product): + + >>> t.oindex[[0, 2], [1, 3]].index_array_structure + 'orthogonal' + + `vindex` arrays are correlated — they share the broadcast axis: + + >>> t.vindex[np.array([0, 2]), np.array([1, 3])].index_array_structure + 'general' + """ + seen: set[int] = set() + has_array = False + for m in self.output: + if not isinstance(m, ArrayMap): + continue + has_array = True + dep = m.dependency_axes + if len(dep) != 1 or dep[0] in seen: + return "general" + seen.add(dep[0]) + return "orthogonal" if has_array else "none" + + def select( + self, + selection: Any, + mode: Literal["basic", "orthogonal", "vectorized"] = "basic", + ) -> IndexTransform: + """Convert a user selection into a composed IndexTransform. + + Negative indices are treated as literal coordinates (TensorStore convention). + The caller (Array layer) is responsible for converting numpy-style negative + indices before calling this function. + + Examples + -------- + The `mode` picks the dialect; the result is the composed self the + corresponding accessor builds: + + >>> t = IndexTransform.from_shape((10,)) + >>> t.select(slice(2, 8)) == t[2:8] + True + >>> s = t.select(([9, 0, 0],), mode="orthogonal") + >>> s.apply((0,)), s.apply((1,)), s.apply((2,)) + ((9,), (0,), (0,)) + """ + if mode == "basic": + _validate_basic_selection(selection) + return self[selection] + elif mode == "orthogonal": + _validate_array_selection(selection, self.domain.shape, mode) + return self.oindex[selection] + elif mode == "vectorized": + _validate_array_selection(selection, self.domain.shape, mode) + return self.vindex[selection] + else: + raise ValueError(f"Unknown mode: {mode!r}") + + def compose(self, inner: IndexTransform) -> IndexTransform: + """Chain `inner` onto this transform, yielding one direct transform. + + This transform maps its own input coordinates to `inner`'s input + coordinates, and `inner` maps those onward; the result maps this + transform's input coordinates straight to `inner`'s output + coordinates. Composition is what keeps a view of a view a single + description rather than a stack of layers, and it is exact: index + arrays are evaluated at the new coordinates rather than accumulated. + + The precondition is that this transform's output rank equals `inner`'s + input rank; a mismatch, or coordinates leaving `inner`'s domain, raises. + + Examples + -------- + Chained indexing — `source[2:5]`, then `[::-1]` on the result — + collapses to one transform (a reversed axis keeps literal coordinates, + so the composed domain is `[-4, -1)`): + + >>> inner = IndexTransform.from_shape((10,))[2:5] + >>> outer = IndexTransform.identity(inner.domain)[::-1] + >>> chained = outer.compose(inner) + >>> chained == inner[::-1] + True + >>> [chained.apply((i,)) for i in (-4, -3, -2)] + [(4,), (3,), (2,)] + """ + from zarr_indexing._composition import compose + + return compose(self, inner) + + # -- serialization ------------------------------------------------------ + + def to_json(self) -> IndexTransformJSON: + """Convert to the canonical ndsel transform body (spec section 4.3). + + The result is fully explicit: `input_rank`, fully written bounds and + labels, and an `output` carrying `offset`/`stride` on every affine and + array map. It is field-for-field a TensorStore `IndexTransform` minus + the `kind` discriminator, so it loads directly into + `tensorstore.IndexTransform(json=...)`. + + Examples + -------- + >>> body = IndexTransform.from_shape((6,))[1:5:2].to_json() + >>> (body["input_inclusive_min"], body["input_exclusive_max"]) + ([0], [2]) + >>> body["output"] + [{'offset': 1, 'stride': 2, 'input_dimension': 0}] + """ + from zarr_indexing._wire import emit_labels + + return { + "input_rank": self.domain.ndim, + "input_inclusive_min": list(self.domain.inclusive_min), + "input_exclusive_max": list(self.domain.exclusive_max), + "input_labels": emit_labels(self.domain.labels, self.domain.ndim), + "output": [m.to_json() for m in self.output], + } + + @classmethod + def from_json(cls, data: IndexTransformJSON) -> IndexTransform: + """Construct from a canonical (or canonicalizable) ndsel transform body. + + The body is first run through the message layer (`normalize_ndsel`) so + that omitted fields — identity `output`, default bounds and labels — + are filled and validated, then lowered to the engine representation. + Lower-rank `index_array`s are widened to the full input rank on the way + in. + + Examples + -------- + >>> body = IndexTransform.from_shape((6,))[1:5:2].to_json() + >>> transform = IndexTransform.from_json(body) + >>> transform.domain.shape + (2,) + >>> transform.to_json() == body # the round trip is exact + True + """ + from zarr_indexing._wire import ( + full_rank_index_array, + lower_bound, + lower_index_array, + lower_labels, + ) + from zarr_indexing.messages import NdselError, normalize_ndsel + + if not isinstance(data, dict): # pyright: ignore[reportUnnecessaryIsInstance] + raise NdselError( + "invalid_json", f"a transform body must be a JSON object, got {data!r}" + ) + kind = data.get("kind", "transform") + if kind != "transform": + # Spelled before normalization so a body carrying its own `kind` + # cannot reinterpret the document as some other message and return + # a selection this constructor never promised. + raise NdselError("invalid_json", f"a transform body cannot carry kind {kind!r}") + body = normalize_ndsel({**data, "kind": "transform"}) + + domain = IndexDomain( + inclusive_min=tuple( + lower_bound(b, f"input_inclusive_min[{i}]") + for i, b in enumerate(body["input_inclusive_min"]) + ), + exclusive_max=tuple( + lower_bound(b, f"input_exclusive_max[{i}]") + for i, b in enumerate(body["input_exclusive_max"]) + ), + labels=lower_labels(body["input_labels"]), + ) + + output: list[OutputIndexMap] = [] + for i, om in enumerate(body["output"]): + if "index_array" in om: + where = f"output[{i}]" + arr = lower_index_array(om["index_array"], f"{where}.index_array") + # ndsel leaves index-array rank unvalidated, so an external + # producer may send an array of lower rank that broadcasts + # against the domain. Widen it here, on the way in, so every + # transform that exists holds the full-rank invariant the + # engine reads dependency axes from. + output.append( + ArrayMap( + index_array=full_rank_index_array(arr, domain, where), + offset=om.get("offset", 0), + stride=om.get("stride", 1), + ) + ) + elif "input_dimension" in om: + output.append( + DimensionMap( + input_dimension=om["input_dimension"], + offset=om.get("offset", 0), + stride=om.get("stride", 1), + ) + ) + else: + output.append(ConstantMap(offset=om.get("offset", 0))) + + try: + return cls(domain=domain, output=tuple(output)) + except ValueError as exc: + # The engine's invariants are the last gate a document passes, and + # they speak in the engine's vocabulary. A document that fails them + # is invalid input, so it leaves here as one — with the engine's + # account of what was wrong kept, since it names the offending + # output map and axis. + raise NdselError("rank_mismatch", str(exc)) from exc + + +def _positions_from_origin(coordinates: np.ndarray[Any, Any], origin: int) -> npt.NDArray[np.intp]: + """Convert literal coordinates to positional indices without wrapping.""" + return checked_affine(-int(origin), 1, coordinates) + + +def _intersect( + transform: IndexTransform, output_domain: IndexDomain +) -> ( + tuple[ + IndexTransform, + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None, + ] + | None +): + """Intersect a transform with an output domain (e.g., a chunk's bounds). + + For each output dimension, restrict to output coordinates within + `[output_domain.inclusive_min[d], output_domain.exclusive_max[d])`. + + Two flavors of fancy indexing require different treatment, distinguished by + the ArrayMaps' dependency axes (see `ArrayMap.dependency_axes`): + + - **orthogonal** (`oindex`): each ArrayMap varies over a single, distinct + input axis, forming an outer product. Every output dimension is intersected + independently and the input domain narrowed per axis. + - **correlated** (`vindex`): the ArrayMaps share their (broadcast) dependency + axes and scatter through a single flat index. A point survives only if ALL + its output coordinates fall within the output domain; residual slice + dimensions are intersected independently, as in the orthogonal case. + + The routing is `index_array_structure`: only a pure per-axis outer product + takes the orthogonal path. + + Returns `None` if the intersection is empty. + """ + if output_domain.ndim != transform.output_rank: + raise ValueError( + f"output_domain rank ({output_domain.ndim}) != " + f"transform output rank ({transform.output_rank})" + ) + + if any(size == 0 for size in transform.domain.shape): + # An empty input domain addresses no coordinates at all, so it meets no + # output domain. Deciding it here keeps the per-flavor intersections from + # having to reconcile an empty domain with an index array that is *not* + # empty: a genuine extent-1 axis is stored as a broadcast singleton, so + # emptying its domain leaves the array at size 1. + return None + + if transform.index_array_structure == "general": + return _intersect_general(transform, output_domain) + return _intersect_orthogonal(transform, output_domain) + + +def _intersect_dimension_map( + m: DimensionMap, input_lo: int, input_hi: int, lo: int, hi: int +) -> tuple[int, int] | None: + """Narrow a DimensionMap's input range to output coordinates in `[lo, hi)`. + + `input_lo`/`input_hi` are the current (possibly already narrowed) input + range for the map's axis. Returns the new `(input_lo, input_hi)` or `None` + if no input produces an in-bounds output coordinate. + """ + if input_lo >= input_hi: + return None + if m.stride > 0: + new_input_lo = max(input_lo, _ceil_div(lo - m.offset, m.stride)) + new_input_hi = min(input_hi, _ceil_div(hi - m.offset, m.stride)) + elif m.stride < 0: + new_input_lo = max(input_lo, _ceil_div(hi - 1 - m.offset, m.stride)) + new_input_hi = min(input_hi, _ceil_div(lo - 1 - m.offset, m.stride)) + else: + if lo <= m.offset < hi: + new_input_lo, new_input_hi = input_lo, input_hi + else: + return None + if new_input_lo >= new_input_hi: + return None + return new_input_lo, new_input_hi + + +def _ceil_div(numerator: int, denominator: int) -> int: + """Return ``ceil(numerator / denominator)`` using exact integer arithmetic.""" + return -((-numerator) // denominator) + + +def _intersect_orthogonal( + transform: IndexTransform, output_domain: IndexDomain +) -> ( + tuple[ + IndexTransform, + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None, + ] + | None +): + """Intersect a transform with no correlated ArrayMaps. + + Every output dimension is intersected independently. Multiple ArrayMaps bound + to distinct input dimensions form an outer product, so each array's surviving + *output* positions are tracked separately. + """ + new_min = list(transform.domain.inclusive_min) + new_max = list(transform.domain.exclusive_max) + new_output: list[OutputIndexMap] = [] + out_positions: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + + for out_dim, m in enumerate(transform.output): + lo = output_domain.inclusive_min[out_dim] + hi = output_domain.exclusive_max[out_dim] + + if isinstance(m, ConstantMap): + if lo <= m.offset < hi: + new_output.append(m) + else: + return None + + elif isinstance(m, DimensionMap): + d = m.input_dimension + narrowed = _intersect_dimension_map(m, new_min[d], new_max[d], lo, hi) + if narrowed is None: + return None + new_min[d], new_max[d] = narrowed + new_output.append(m) + + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + # Orthogonal: the array varies over a single axis. Filter along that + # axis and keep the array at full input rank so the singleton axes + # it broadcasts over are preserved. + axis = m.dependent_axis + if axis is None: + raise ValueError( + f"output[{out_dim}] is an ArrayMap that varies over no input " + "dimension; a map with no dependency axis should have been " + "collapsed to a ConstantMap" + ) + d = axis + storage = checked_affine(m.offset, m.stride, m.index_array) + mask = (storage >= lo) & (storage < hi) + # The array is singleton on every axis but `d`, so its mask reduces + # to a 1-D vector along `d`. + survivors = np.nonzero(mask.reshape(-1))[0].astype(np.intp) + if survivors.size == 0: + return None + filtered = np.take(m.index_array, survivors, axis=d) + new_output.append( + ArrayMap( + index_array=np.asarray(filtered, dtype=np.intp), + offset=m.offset, + stride=m.stride, + ) + ) + new_max[d] = new_min[d] + int(survivors.size) + out_positions[out_dim] = survivors + + new_domain = IndexDomain( + inclusive_min=tuple(new_min), + exclusive_max=tuple(new_max), + ) + result = IndexTransform(domain=new_domain, output=tuple(new_output)) + + # Hand back the surviving output positions in the shape the bridge expects: + # None (no arrays), a single vector (one array), or a per-output-dim dict + # (>= 2 orthogonal arrays → outer product). + out_indices: ( + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None + ) + if len(out_positions) == 0: + out_indices = None + elif len(out_positions) == 1: + out_indices = next(iter(out_positions.values())) + else: + out_indices = out_positions + return (result, out_indices) + + +def _intersect_general( + transform: IndexTransform, + output_domain: IndexDomain, +) -> tuple[IndexTransform, np.ndarray[Any, np.dtype[np.intp]]] | None: + """Intersect a transform with any index-array structure, pointwise. + + Every `ArrayMap` — correlated, orthogonal, or several sharing an axis — is + treated as a lookup table over the joint block of non-slice axes: a block + point survives only if ALL its output coordinates fall within the output + domain. Residual DimensionMap dimensions are intersected independently (as in + the orthogonal case) and preserved, so a partial vindex — e.g. two coordinate + arrays over a 3-D array, leaving one slice dimension — resolves correctly. + Treating an orthogonal map this way forfeits its per-axis independence (the + block enumerates the outer product), which is why the pure-orthogonal case + keeps its own resolver. + + The surviving broadcast axes collapse to a single axis; the returned + `out_indices` is the flat scatter index into the (row-major flattened) + output buffer, of shape `(surviving_points,) + (residual slice sizes)`. + + A rank-0 broadcast block — every coordinate array a scalar, as after + `vindex[...]` narrowed to a single point — has no axis to collapse and stays + rank 0: the block either survives whole or the intersection is empty. The + result keeps only the residual slice axes and `out_indices` loses its leading + points axis, so the sub-transform's rank still matches the view's. + """ + correlated_dims = [i for i, m in enumerate(transform.output) if isinstance(m, ArrayMap)] + + # The broadcast axes are exactly the input axes no `DimensionMap` binds: a + # correlated transform's input domain is its residual slice axes plus the + # collapsed broadcast block. Deriving them by complement rather than from the + # index array's non-singleton axes keeps this correct when a broadcast axis + # is itself size 1, and when NumPy's placement rule puts the broadcast block + # somewhere other than the front (see `_broadcast_insertion_point`). + bound_axes = {m.input_dimension for m in transform.output if isinstance(m, DimensionMap)} + broadcast_axes = tuple(a for a in range(transform.input_rank) if a not in bound_axes) + broadcast_shape = tuple(transform.domain.shape[a] for a in broadcast_axes) + + for out_dim in correlated_dims: + arr_map = cast("ArrayMap", transform.output[out_dim]) + if any(a not in broadcast_axes for a in arr_map.dependency_axes): + # Reachable only by hand-building a transform: no selection binds + # the same input axis to both a slice map and an index array. + raise NotImplementedError( + "intersecting a transform whose index array varies over an " + "input dimension also bound by a slice map is not supported" + ) + + # Joint bounds mask over the broadcast block. + combined: np.ndarray[Any, np.dtype[np.bool_]] | None = None + for out_dim in correlated_dims: + cm = cast("ArrayMap", transform.output[out_dim]) + storage = checked_affine(cm.offset, cm.stride, cm.index_array) + lo = output_domain.inclusive_min[out_dim] + hi = output_domain.exclusive_max[out_dim] + mask = (storage >= lo) & (storage < hi) + combined = mask if combined is None else (combined & mask) + assert combined is not None + # Index arrays are singleton on every non-broadcast axis, so the mask + # collapses (C-order) to the broadcast block. A map may also be singleton + # along a block axis it does not vary over (an orthogonal member, or a + # leftover broadcast axis), so the collapsed mask is broadcast up to the + # full block rather than reshaped. + combined_block = combined.reshape(tuple(combined.shape[a] for a in broadcast_axes)) + combined_bcast = np.broadcast_to(combined_block, broadcast_shape) + surviving = np.nonzero(combined_bcast.reshape(-1))[0].astype(np.intp) + if surviving.size == 0: + return None + + # Intersect residual (slice / constant) dimensions independently. Slice dims + # are ordered by input dimension so their flat-buffer strides are row-major. + slice_dims: list[tuple[int, int, int, int, DimensionMap]] = [] # (in_dim, lo, hi, full, m) + for out_dim, m in enumerate(transform.output): + if out_dim in correlated_dims: + continue + lo = output_domain.inclusive_min[out_dim] + hi = output_domain.exclusive_max[out_dim] + if isinstance(m, ConstantMap): + if not (lo <= m.offset < hi): + return None + elif isinstance(m, DimensionMap): + d = m.input_dimension + input_lo = transform.domain.inclusive_min[d] + input_hi = transform.domain.exclusive_max[d] + narrowed = _intersect_dimension_map(m, input_lo, input_hi, lo, hi) + if narrowed is None: + return None + slice_dims.append((d, narrowed[0], narrowed[1], input_hi - input_lo, m)) + slice_dims.sort(key=lambda item: item[0]) + + n_points = int(surviving.size) + n_slice = len(slice_dims) + corr_values: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + for out_dim in correlated_dims: + arr = cast("ArrayMap", transform.output[out_dim]).index_array + block = arr.reshape(tuple(arr.shape[a] for a in broadcast_axes)) + corr_values[out_dim] = np.asarray( + np.ascontiguousarray(np.broadcast_to(block, broadcast_shape)).reshape(-1)[surviving], + dtype=np.intp, + ) + + # A rank-0 broadcast block contributes no axis: the leading `(n_points,)` of + # the domain, of every index array, and of `out_indices` is present only when + # there was a block to collapse. + points_shape = (n_points,) if len(broadcast_shape) > 0 else () + + # New domain: the collapsed broadcast axis if there is one, then one axis per + # residual slice. + new_min = [0] * len(points_shape) + new_max = list(points_shape) + new_input_dim_of = {} + for new_axis, (d, nlo, nhi, _full, _m) in enumerate(slice_dims, start=len(points_shape)): + new_min.append(nlo) + new_max.append(nhi) + new_input_dim_of[d] = new_axis + new_domain = IndexDomain(inclusive_min=tuple(new_min), exclusive_max=tuple(new_max)) + + corr_shape = points_shape + (1,) * n_slice + new_output: list[OutputIndexMap] = [] + for out_dim, m in enumerate(transform.output): + if out_dim in correlated_dims: + corr = cast("ArrayMap", m) + new_output.append( + ArrayMap( + index_array=corr_values[out_dim].reshape(corr_shape).astype(np.intp), + offset=corr.offset, + stride=corr.stride, + ) + ) + elif isinstance(m, ConstantMap): + new_output.append(m) + else: + assert isinstance(m, DimensionMap) + new_output.append( + DimensionMap( + input_dimension=new_input_dim_of[m.input_dimension], + offset=m.offset, + stride=m.stride, + ) + ) + result = IndexTransform(domain=new_domain, output=tuple(new_output)) + + # Flat scatter index into the caller's row-major output buffer, whose shape + # is the *input* domain's shape. The buffer is addressed positionally, so + # this assumes a zero-origin domain — the resolvers normalize with + # `translate_domain_to` before resolving. + # + # Each surviving point is a flat index into the broadcast block; unravel it + # to per-axis coordinates so the buffer stride of each broadcast axis is + # applied at its real position, wherever NumPy's placement rule put it. + domain_shape = transform.domain.shape + buffer_strides = [1] * len(domain_shape) + for axis in range(len(domain_shape) - 2, -1, -1): + buffer_strides[axis] = buffer_strides[axis + 1] * domain_shape[axis + 1] + + point_offsets = np.zeros(n_points, dtype=np.intp) + if len(broadcast_shape) > 0: + for axis, coords_along_axis in zip( + broadcast_axes, np.unravel_index(surviving, broadcast_shape), strict=True + ): + point_offsets = point_offsets + coords_along_axis.astype(np.intp) * buffer_strides[axis] + + n_lead = len(points_shape) + out_indices: np.ndarray[Any, np.dtype[np.intp]] = point_offsets.reshape( + points_shape + (1,) * n_slice + ) + for j in range(n_slice): + d, nlo, nhi, _full, _m = slice_dims[j] + coords = np.arange(nlo, nhi, dtype=np.intp) * buffer_strides[d] + shape = [1] * (n_lead + n_slice) + shape[n_lead + j] = coords.size + out_indices = out_indices + coords.reshape(shape) + return (result, out_indices.astype(np.intp)) + + +def _normalize_basic_selection(selection: Any, ndim: int) -> tuple[int | slice | None, ...]: + """Normalize a selection to a tuple of int, slice, or None (newaxis), + expanding ellipsis and padding with slice(None) as needed. + """ + if not isinstance(selection, tuple): + selection = (selection,) + + # Count non-newaxis, non-ellipsis entries to determine how many real dims are addressed + n_newaxis = sum(1 for s in selection if s is None) + has_ellipsis = any(s is Ellipsis for s in selection) + n_real = len(selection) - n_newaxis - (1 if has_ellipsis else 0) + + if n_real > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, but {n_real} were indexed" + ) + + result: list[int | slice | None] = [] + ellipsis_seen = False + for sel in selection: + if sel is Ellipsis: + if ellipsis_seen: + raise IndexError("an index can only have a single ellipsis ('...')") + ellipsis_seen = True + num_missing = ndim - n_real + result.extend([slice(None)] * num_missing) + elif (scalar := as_scalar_index(sel)) is not None: + result.append(scalar) + elif isinstance(sel, slice) or sel is None: + result.append(sel) + else: + raise IndexError(f"unsupported selection type for basic indexing: {type(sel)!r}") + + # Pad remaining dimensions with slice(None) + while sum(1 for s in result if s is not None) < ndim: + result.append(slice(None)) + + return tuple(result) + + +def _positional_slice(pos: int, size: int, step: int) -> slice: + """A NumPy slice selecting `size` elements from `pos`, walking by `step`. + + The stop is `pos + size*step`, except in two cases. An empty selection is + written out explicitly, because the arithmetic form can be a negative stop + that NumPy would read as counting from the end. And a downward walk + reaching the start of the array must stop at `None`, for the same reason: + `slice(6, -1, -1)` selects nothing where `slice(6, None, -1)` selects the + first seven elements in reverse. + """ + if size <= 0: + return slice(0, 0, 1) + stop = pos + size * step + if step < 0 and stop < 0: + return slice(pos, None, step) + return slice(pos, stop, step) + + +def _reindex_array( + m: ArrayMap, + normalized: tuple[int | slice | None, ...], + domain: IndexDomain, +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Apply basic indexing operations to an ArrayMap's index_array. + + The array's axes correspond to the transform's input dimensions (0-indexed + over the domain shape). Each axis is either a **dependency axis** — the array + varies with that input dimension — or a **singleton** axis it + broadcasts over. Integer indexing, slicing, or newaxis is applied to the + array only along its dependency axes; a selection on a singleton axis does not + touch the array's values (it just narrows or drops that broadcast axis). + """ + dependent = set(m.dependency_axes) + arr = m.index_array + + # Build a numpy indexing tuple: one entry per old input dimension + idx: list[Any] = [] + old_dim = 0 + newaxis_positions: list[int] = [] + result_axis = 0 + + for sel in normalized: + if sel is None: + newaxis_positions.append(result_axis) + result_axis += 1 + elif isinstance(sel, int): + if old_dim < arr.ndim: + if old_dim in dependent: + # Convert absolute domain coordinate to 0-based array index + idx.append(sel - domain.inclusive_min[old_dim]) + else: + # Broadcast axis: keep the single element and drop the axis. + idx.append(0) + old_dim += 1 + else: + # sel: slice (normalized: tuple[int | slice | None, ...]) + if old_dim < arr.ndim: + if old_dim in dependent: + lo = domain.inclusive_min[old_dim] + hi = domain.exclusive_max[old_dim] + # Bounds are literal domain coordinates; the stored array is + # indexed positionally, so shift by the domain origin. + start, step, _origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + pos = start - lo + idx.append(_positional_slice(pos, size, step)) + else: + # Broadcast axis: preserve the singleton (it still broadcasts + # over the narrowed domain), regardless of the slice bounds. + idx.append(slice(None)) + old_dim += 1 + result_axis += 1 + + result = arr[tuple(idx)] if idx else arr + + for pos in newaxis_positions: + result = np.expand_dims(result, axis=pos) + + return np.asarray(result, dtype=np.intp) + + +def _compose_selection( + transform: IndexTransform, + selection: Any, + mode: Literal["orthogonal", "vectorized"], +) -> IndexTransform: + """Apply an advanced selection to an array-carrying transform by composition. + + The selection is applied to an identity transform over the current domain — + the same code path a fresh transform takes, so the dialect (placement, + bounds, domains) is identical by construction — and the result is chained + onto `transform` with `compose`, which evaluates the existing index arrays + at the new coordinates. This is how a second fancy step lands on *any* axis + of an already-fancy view: axes an existing array varies over, axes it merely + broadcasts along, or a mixture. + """ + # Deferred import: `composition` imports this module at import time. + + identity = IndexTransform.identity(transform.domain) + if mode == "orthogonal": + outer = _apply_oindex(identity, selection) + else: + outer = _apply_vindex(identity, selection) + return outer.compose(transform) + + +def _apply_basic_indexing(transform: IndexTransform, selection: Any) -> IndexTransform: + """Apply basic indexing (int, slice, ellipsis, newaxis) to an IndexTransform.""" + normalized = _normalize_basic_selection(selection, transform.domain.ndim) + + new_inclusive_min: list[int] = [] + new_exclusive_max: list[int] = [] + old_dim = 0 + new_dim_idx = 0 + old_to_new_dim: dict[int, int] = {} + dropped_dims: set[int] = set() + + # Per old-dim: the slice parameters (for computing new output maps) + dim_slice_params: dict[int, tuple[int, int, int]] = {} # old_dim -> (start, stop, step) + dim_int_val: dict[int, int] = {} # old_dim -> integer index value + + for sel in normalized: + if sel is None: + # newaxis: add a size-1 dimension + new_inclusive_min.append(0) + new_exclusive_max.append(1) + new_dim_idx += 1 + elif isinstance(sel, int): + # Integer index: drop this input dimension. + # Negative indices are literal coordinates (TensorStore convention), + # NOT "from the end" like NumPy. The Array layer handles conversion. + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + idx = sel + if idx < lo or idx >= hi: + hint = _LITERAL_HINT if sel < 0 else "" + raise BoundsCheckError( + f"index {sel} is out of bounds for dimension {old_dim} " + f"(valid indices [{lo}, {hi})){hint}" + ) + dropped_dims.add(old_dim) + dim_int_val[old_dim] = idx + old_dim += 1 + else: + # sel: slice (normalized: tuple[int | slice | None, ...]) + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + + # TensorStore semantics: bounds are literal coordinates; a step-1 + # slice keeps them as the new domain, a strided slice's domain is + # [trunc(start/step), trunc(start/step) + size). + start, step, origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + new_inclusive_min.append(origin) + new_exclusive_max.append(origin + size) + dim_slice_params[old_dim] = (start, step, origin) + old_to_new_dim[old_dim] = new_dim_idx + new_dim_idx += 1 + old_dim += 1 + + new_domain = IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + # Now update output maps + new_output: list[OutputIndexMap] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + new_output.append(m) + elif isinstance(m, DimensionMap): + d = m.input_dimension + if d in dropped_dims: + # Integer index: this output becomes constant + new_offset = m.offset + m.stride * dim_int_val[d] + new_output.append(ConstantMap(offset=new_offset)) + elif d in old_to_new_dim: + # Slice: new coordinate `origin + k` maps to old coordinate + # `start + k*step`, i.e. old = start - step*origin + step*new. + start, step, origin = dim_slice_params[d] + new_offset = m.offset + m.stride * (start - step * origin) + new_stride = m.stride * step + new_input_dim = old_to_new_dim[d] + new_output.append( + DimensionMap( + input_dimension=new_input_dim, offset=new_offset, stride=new_stride + ) + ) + else: + raise RuntimeError(f"unexpected: dimension {d} not handled") + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap). + # A result narrowed to a single coordinate collapses to the + # ConstantMap it equals — whether an integer consumed the dependency + # axis or a slice narrowed it to one entry — so a non-empty ArrayMap + # always varies over at least one axis. Nothing here renumbers: the + # array's axes are the new domain's axes by construction. + new_arr = _reindex_array(m, normalized, transform.domain) + new_output.append(array_map_or_constant(new_arr, offset=m.offset, stride=m.stride)) + + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + +def _reshape_to_axis( + values: np.ndarray[Any, np.dtype[np.intp]], axis: int, ndim: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Reshape a 1-D selection to full rank `ndim` varying only along `axis`. + + The result has `values` laid out along `axis` and singleton (size-1) axes + everywhere else, so its dependency axis is derivable from its shape. + """ + flat = np.asarray(values, dtype=np.intp).ravel() + shape = [1] * ndim + shape[axis] = flat.shape[0] + return flat.reshape(shape) + + +class _OIndexHelper: + """Helper that provides orthogonal (outer) indexing via `transform.oindex[...]`.""" + + def __init__(self, transform: IndexTransform) -> None: + self._transform = transform + + def __getitem__(self, selection: Any) -> IndexTransform: + return _apply_oindex(self._transform, selection) + + +def _normalize_oindex_selection( + selection: Any, ndim: int +) -> tuple[np.ndarray[Any, np.dtype[np.intp]] | slice, ...]: + """Normalize an oindex selection: arrays, slices, booleans, integers.""" + if not isinstance(selection, tuple): + selection = (selection,) + + # Expand ellipsis + has_ellipsis = any(s is Ellipsis for s in selection) + n_ellipsis = 1 if has_ellipsis else 0 + n_real = len(selection) - n_ellipsis + + result: list[np.ndarray[Any, np.dtype[np.intp]] | slice] = [] + for sel in selection: + if sel is Ellipsis: + num_missing = ndim - n_real + result.extend([slice(None)] * num_missing) + elif isinstance(sel, np.ndarray) and sel.dtype == np.bool_: + # Boolean array -> integer indices + (indices,) = np.nonzero(sel) + result.append(indices.astype(np.intp)) + elif isinstance(sel, np.ndarray): + result.append(sel.astype(np.intp)) + elif isinstance(sel, slice): + result.append(sel) + elif (scalar := as_scalar_index(sel)) is not None: + # Convert integer scalars to 1-element arrays for orthogonal indexing + result.append(np.array([scalar], dtype=np.intp)) + elif isinstance(sel, (list, tuple)): + array = np.asarray(sel) + if array.dtype == np.bool_: + (indices,) = np.nonzero(array) + result.append(indices.astype(np.intp)) + else: + result.append(np.asarray(sel, dtype=np.intp)) + else: + result.append(sel) + + # Pad with slice(None) + while len(result) < ndim: + result.append(slice(None)) + + return tuple(result) + + +def _apply_oindex(transform: IndexTransform, selection: Any) -> IndexTransform: + """Apply orthogonal indexing to an IndexTransform. + + Each index array is applied independently per dimension (outer product). + + A transform that already carries index arrays takes the composition path + (`_compose_selection`) instead of being rewritten in place, so the new + selection may land on any axis — including axes an existing array merely + broadcasts along. + """ + validate_advanced_selection(selection, transform.domain, "orthogonal") + if any(isinstance(m, ArrayMap) for m in transform.output): + return _compose_selection(transform, selection, "orthogonal") + normalized = _normalize_oindex_selection(selection, transform.domain.ndim) + + new_inclusive_min: list[int] = [] + new_exclusive_max: list[int] = [] + new_dim_idx = 0 + old_to_new_dim: dict[int, int] = {} + + # Info per old dim + dim_array: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + dim_slice_params: dict[int, tuple[int, int, int]] = {} + + for old_dim, sel in enumerate(normalized): + if isinstance(sel, np.ndarray): + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + # Index-array values are literal domain coordinates; the fancy dim + # they create gets a fresh zero-origin [0, n) domain (TensorStore). + _check_array_in_bounds(sel, lo, hi) + dim_array[old_dim] = sel + new_inclusive_min.append(0) + new_exclusive_max.append(len(sel)) + old_to_new_dim[old_dim] = new_dim_idx + new_dim_idx += 1 + else: + # sel: slice (_normalize_oindex_selection returns + # tuple[np.ndarray | slice, ...]) + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + start, step, origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + new_inclusive_min.append(origin) + new_exclusive_max.append(origin + size) + dim_slice_params[old_dim] = (start, step, origin) + old_to_new_dim[old_dim] = new_dim_idx + new_dim_idx += 1 + + new_domain = IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + new_output: list[OutputIndexMap] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + new_output.append(m) + elif isinstance(m, DimensionMap): + d = m.input_dimension + if d in dim_array: + new_axis = old_to_new_dim[d] + # Normalize to full input rank: the selection varies along its + # own new axis and is singleton on every other axis, so the + # dependency axis is readable from the shape. A single-entry + # selection holds one coordinate and collapses to the + # ConstantMap it equals; its length-1 axis stays in the domain. + full_arr = _reshape_to_axis(dim_array[d], new_axis, new_dim_idx) + new_output.append(array_map_or_constant(full_arr, offset=m.offset, stride=m.stride)) + elif d in dim_slice_params: + start, step, origin = dim_slice_params[d] + new_offset = m.offset + m.stride * (start - step * origin) + new_stride = m.stride * step + new_input_dim = old_to_new_dim[d] + new_output.append( + DimensionMap( + input_dimension=new_input_dim, offset=new_offset, stride=new_stride + ) + ) + else: + raise RuntimeError(f"unexpected: dimension {d} not handled") + else: + # m: ArrayMap — unreachable: array-carrying transforms took the + # composition path at the top of this function. + raise AssertionError( # noqa: TRY004 - unreachable, not a dispatch + "unreachable: ArrayMap transforms are composed" + ) + + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + +class _VIndexHelper: + """Helper that provides vectorized (fancy) indexing via `transform.vindex[...]`.""" + + def __init__(self, transform: IndexTransform) -> None: + self._transform = transform + + def __getitem__(self, selection: Any) -> IndexTransform: + return _apply_vindex(self._transform, selection) + + +def _broadcast_insertion_point(array_dims: Sequence[int], slice_dims: Sequence[int]) -> int: + """Where the broadcast dimensions land, as a count of leading slice dimensions. + + NumPy's advanced-indexing placement rule: when the advanced indices are all + next to each other in the index tuple, the broadcast dimensions are inserted + at the spot they occupied; when a slice separates them, they lead. So + `a[:, i, j]` has shape `(len(a), *broadcast)` while `a[i, :, j]` has shape + `(*broadcast, a.shape[1])`. + + Returns the number of slice dimensions that precede the broadcast block; `0` + means the broadcast dimensions lead. + """ + if len(array_dims) == 0: + return 0 + first, last = array_dims[0], array_dims[-1] + separated = any(first < d < last for d in slice_dims) + if separated: + return 0 + return sum(1 for d in slice_dims if d < first) + + +def _as_boolean_index_array(selection: Any) -> np.ndarray[Any, np.dtype[np.bool_]] | None: + """Return an array-like boolean index as an ndarray, else None.""" + if not isinstance(selection, (np.ndarray, list, tuple)): + return None + array = np.asarray(selection) + if array.dtype != np.bool_: + return None + return array + + +def _selection_axis_count(selection: Any) -> int: + """Return how many input axes one vectorized selection entry consumes.""" + boolean_array = _as_boolean_index_array(selection) + return boolean_array.ndim if boolean_array is not None else 1 + + +def _apply_vindex(transform: IndexTransform, selection: Any) -> IndexTransform: + """Apply vectorized indexing to an IndexTransform. + + All array indices are broadcast together. Broadcast dimensions are prepended, + followed by non-array (slice) dimensions. + + A transform that already carries index arrays takes the composition path + (`_compose_selection`) instead of being rewritten in place; see + `_apply_oindex`. + """ + validate_advanced_selection(selection, transform.domain, "vectorized") + if any(isinstance(m, ArrayMap) for m in transform.output): + return _compose_selection(transform, selection, "vectorized") + if not isinstance(selection, tuple): + selection = (selection,) + + # Expand ellipsis and count consumed dimensions. Boolean masks consume one + # input axis per mask dimension, whether spelled as an ndarray or a list. + n_consumed = sum(_selection_axis_count(s) for s in selection if s is not Ellipsis) + ndim = transform.domain.ndim + + expanded: list[Any] = [] + for sel in selection: + if sel is Ellipsis: + num_missing = ndim - n_consumed + expanded.extend([slice(None)] * num_missing) + else: + expanded.append(sel) + # Count dimensions already consumed by expanded entries + n_expanded_dims = sum(_selection_axis_count(sel) for sel in expanded) + while n_expanded_dims < ndim: + expanded.append(slice(None)) + n_expanded_dims += 1 + + # Convert booleans, lists, ints to integer arrays + processed: list[np.ndarray[Any, np.dtype[np.intp]] | slice] = [] + for sel in expanded: + boolean_array = _as_boolean_index_array(sel) + if boolean_array is not None: + indices_tuple = np.nonzero(boolean_array) + processed.extend(indices.astype(np.intp) for indices in indices_tuple) + elif isinstance(sel, np.ndarray): + processed.append(sel.astype(np.intp)) + elif isinstance(sel, (list, tuple)): + processed.append(np.asarray(sel, dtype=np.intp)) + elif (scalar := as_scalar_index(sel)) is not None: + processed.append(np.array([scalar], dtype=np.intp)) + else: + processed.append(sel) + + # Separate array dims and slice dims + array_dims: list[int] = [] + slice_dims: list[int] = [] + arrays: list[np.ndarray[Any, np.dtype[np.intp]]] = [] + + for i, sel in enumerate(processed): + if isinstance(sel, np.ndarray): + lo = transform.domain.inclusive_min[i] + hi = transform.domain.exclusive_max[i] + _check_array_in_bounds(sel, lo, hi) + array_dims.append(i) + arrays.append(sel) + else: + slice_dims.append(i) + + # Broadcast all arrays together + broadcast_arrays: list[np.ndarray[Any, np.dtype[np.intp]]] + if len(arrays) > 0: + broadcast_arrays = list(np.broadcast_arrays(*arrays)) + broadcast_shape = broadcast_arrays[0].shape + else: + broadcast_arrays = [] + broadcast_shape = () + + # Slice dimensions (preserved-domain literal semantics, like basic indexing) + slice_dim_params: dict[int, tuple[int, int, int]] = {} + slice_bounds: list[tuple[int, int]] = [] + for old_dim in slice_dims: + sel = processed[old_dim] + assert isinstance(sel, slice) + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + start, step, origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + slice_bounds.append((origin, origin + size)) + slice_dim_params[old_dim] = (start, step, origin) + + n_before = _broadcast_insertion_point(array_dims, slice_dims) + + # Build the new domain with NumPy's placement rule: the broadcast + # (correlated) dimensions sit where the advanced indices sat when those are + # adjacent, and lead when a slice separates them. + new_inclusive_min = [lo for lo, _ in slice_bounds[:n_before]] + new_exclusive_max = [hi for _, hi in slice_bounds[:n_before]] + new_inclusive_min.extend([0] * len(broadcast_shape)) + new_exclusive_max.extend(broadcast_shape) + new_inclusive_min.extend(lo for lo, _ in slice_bounds[n_before:]) + new_exclusive_max.extend(hi for _, hi in slice_bounds[n_before:]) + + new_domain = IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + # Build output maps + array_dim_to_broadcast: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + for i, d in enumerate(array_dims): + array_dim_to_broadcast[d] = broadcast_arrays[i] + + # New dim index for slice dims starts after broadcast dims + n_broadcast_dims = len(broadcast_shape) + + new_output: list[OutputIndexMap] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + new_output.append(m) + elif isinstance(m, DimensionMap): + d = m.input_dimension + if d in array_dim_to_broadcast: + # Normalize to full input rank: the broadcast (correlated) axes + # come first, followed by a singleton axis per slice dimension. + # Every vectorized array shares the same broadcast axes, so the + # dependency axes derived from the shape coincide — the signature + # of a pointwise scatter rather than an outer product. + broadcast_arr = array_dim_to_broadcast[d] + full_arr = broadcast_arr.reshape( + (1,) * n_before + broadcast_shape + (1,) * (len(slice_dims) - n_before) + ) + new_output.append(array_map_or_constant(full_arr, offset=m.offset, stride=m.stride)) + else: + # Slice dim: new coord `origin + k` maps to old `start + k*step` + start, step, origin = slice_dim_params[d] + new_offset = m.offset + m.stride * (start - step * origin) + new_stride = m.stride * step + position = slice_dims.index(d) + new_input_dim = position if position < n_before else position + n_broadcast_dims + new_output.append( + DimensionMap( + input_dimension=new_input_dim, offset=new_offset, stride=new_stride + ) + ) + else: + # m: ArrayMap — unreachable: array-carrying transforms took the + # composition path at the top of this function. + raise AssertionError( # noqa: TRY004 - unreachable, not a dispatch + "unreachable: ArrayMap transforms are composed" + ) + + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + +_LITERAL_HINT = ( + "; within this transform layer, indices are literal domain coordinates (the " + "public Array boundary wraps NumPy-style negatives before they reach here)" +) + + +def _trunc_div(a: int, b: int) -> int: + """Integer division rounded toward zero (C semantics), as TensorStore uses + for strided-slice domain origins — distinct from Python's floor division + for negative operands (`trunc(-9/2) == -4` where `-9 // 2 == -5`).""" + q = a // b + if q < 0 and q * b != a: + q += 1 + return q + + +def _resolve_slice_ts(sel: slice, dim: int, lo: int, hi: int) -> tuple[int, int, int, int]: + """Resolve a slice against domain `[lo, hi)` with TensorStore semantics. + + Slice bounds are **literal domain coordinates** — never from-the-end, never + clamped. One rule covers both signs of the step (each part verified against + tensorstore 0.1.84, and matching ndsel 1.0-draft.2 section 5.3): + + - defaults follow the direction of travel: `start = lo`, `stop = hi` going + up; `start = hi - 1`, `stop = lo - 1` going down; + - the traversal runs from `start` toward `stop`, which is excluded, so the + source interval is `[start, stop)` going up and `[stop + 1, start + 1)` + going down; + - a non-empty interval must be contained in the domain (no clamping — a + NumPy-style out-of-range or negative bound is an error, not a shorter or + wrapped result); + - an empty interval is valid anywhere, for either sign; + - an interval running the wrong way (`stop` on the far side of `start` from + the direction of travel) is an error, not an empty result; + - the result's domain origin is `trunc(start/step)` — toward zero, for both + signs — and coordinate `origin + k` maps to input `start + k*step`. + + A negative step normally produces a negative origin: reversing a + zero-origin axis of length 20 gives the domain `[-19, 1)`. The coordinate + frame stays anchored to the source; a caller that needs non-negative + coordinates re-bases explicitly with `translate_domain_to`. + + Returns `(start, step, origin, size)` in domain coordinates. + """ + start_bound = None if sel.start is None else require_index(sel.start) + stop_bound = None if sel.stop is None else require_index(sel.stop) + step = 1 if sel.step is None else require_index(sel.step) + if step == 0: + raise IndexError("slice step must not be zero") + if step > 0: + start = lo if start_bound is None else start_bound + stop = hi if stop_bound is None else stop_bound + interval_lo, interval_hi = start, stop + else: + start = hi - 1 if start_bound is None else start_bound + stop = lo - 1 if stop_bound is None else stop_bound + interval_lo, interval_hi = stop + 1, start + 1 + length = interval_hi - interval_lo + if length < 0: + raise IndexError( + f"slice from {start} to {stop} with step {step} does not specify a " + f"valid interval for dimension {dim}: the derived interval " + f"[{interval_lo}, {interval_hi}) runs the wrong way. An empty " + "selection is spelled stop == start." + ) + if length > 0 and (interval_lo < lo or interval_hi > hi): + hint = _LITERAL_HINT if (start < 0 or stop < 0) and lo >= 0 else "" + raise BoundsCheckError( + f"slice interval [{interval_lo}, {interval_hi}) is not contained " + f"within domain [{lo}, {hi}) for dimension {dim}{hint}" + ) + size = -(-length // abs(step)) # ceil(length / |step|) + origin = _trunc_div(start, step) + return start, step, origin, size + + +def _check_array_in_bounds(arr: np.ndarray[Any, np.dtype[np.intp]], lo: int, hi: int) -> None: + """Reject index-array values outside the domain `[lo, hi)`. + + Index-array values are literal domain coordinates (TensorStore semantics): + a value below `inclusive_min` is out of bounds rather than counting from + the end. Out-of-range values raise instead of silently wrapping. + """ + if arr.size == 0: + return + lo_val, hi_val = int(arr.min()), int(arr.max()) + if lo_val < lo: + hint = _LITERAL_HINT if lo_val < 0 and lo >= 0 else "" + raise BoundsCheckError( + f"index {lo_val} is out of bounds (valid indices [{lo}, {hi})){hint}" + ) + if hi_val >= hi: + raise BoundsCheckError(f"index {hi_val} is out of bounds (valid indices [{lo}, {hi}))") + + +def _validate_array_selection(selection: Any, shape: tuple[int, ...], mode: str) -> None: + """Validate array-based selections (orthogonal, vectorized). + + Rejects types that are not valid for coordinate/vectorized indexing. + Does not check bounds — the transform operations handle that. + """ + items = selection if isinstance(selection, tuple) else (selection,) + for sel in items: + if isinstance(sel, slice): + # vindex is coordinate-only (matches eager zarr): every axis needs an + # integer/boolean array, never a slice. Orthogonal (oindex) allows slices. + if mode == "vectorized": + raise VindexInvalidSelectionError( + "unsupported selection type for vectorized indexing; only " + "coordinate selection (tuple of integer arrays) and mask selection " + f"(single Boolean array) are supported; got {selection!r}" + ) + continue + if sel is Ellipsis or as_scalar_index(sel) is not None: + continue + if isinstance(sel, (list, np.ndarray)): + if mode == "orthogonal": + array = np.asarray(sel) + # An orthogonal selection is per-axis, so an integer array names + # coordinates along one axis and can only be one-dimensional. + # Left to the engine, this surfaced much later as a rank + # complaint about an `index_array` the caller never wrote. + if array.dtype.kind in "iu" and array.ndim > 1: + raise IndexError( + f"integer arrays in an orthogonal selection must be " + f"1-dimensional only; got one with {array.ndim} dimensions" + ) + continue + raise IndexError(f"unsupported selection type for {mode} indexing: {type(sel)!r}") + + +def _validate_basic_selection(selection: Any) -> None: + """Validate that a selection only contains basic indexing types (int, slice, Ellipsis). + + Rejects None (newaxis), arrays, lists, floats, strings, etc. + """ + items = selection if isinstance(selection, tuple) else (selection,) + for s in items: + if s is Ellipsis or isinstance(s, slice) or as_scalar_index(s) is not None: + continue + raise IndexError(f"unsupported selection type for basic indexing: {type(s)!r}") diff --git a/packages/zarr-indexing/tests/conformance/PROVENANCE.md b/packages/zarr-indexing/tests/conformance/PROVENANCE.md new file mode 100644 index 0000000000..749a2810e7 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/PROVENANCE.md @@ -0,0 +1,39 @@ +# Provenance of the ndsel conformance corpus + +The JSON fixtures in this directory (`point.json`, `box.json`, `slice.json`, +`points.json`, `transform.json`, `errors.json`) and `README.md` are **vendored, +unmodified**, from the ndsel reference repository. + +- **Source:** +- **Branch:** `main` (merge of d-v-b/ndsel#3, empty `index_array` serialization) +- **Commit:** `49b9e1db1ca93c55f320b025a666367de87a9014` (previously vendored: + `92d6a32df0cd1ac47d548f14f42909a95997cf19`, before that `c59bc556c`, itself + byte-identical to `c132b4c1caa3205830ce35a42502363171f650a7`) +- **Path in source:** `conformance/` + +**Do not edit these files.** They are vendored as-is so that +`zarr_indexing`' ndsel message layer can be checked against the same +language-agnostic corpus every other ndsel implementation runs. To update the +corpus, re-vendor from a newer ndsel commit and update the commit SHA above. + +ndsel PR #1 (merged) corrected the `slice` desugaring origin from +`floor(a/s)` to `trunc(a/s)` (rounding toward zero), which matches +`zarr_indexing`' existing `_trunc_div` semantics. + +ndsel PR #2 (merged) specified negative `step`, which changed two fixtures: + +- `slice.json` gained the negative-step cases (full reverse, `|s| > 1` + non-divisible, negative-coordinate intervals, empty-at-any-coordinate). +- `errors.json` retired `error/negative-step` — the reason code + `negative_step_unsupported` is retired with it — and replaced it with three + `bounds_out_of_order` fixtures pinning that a reversed interval is an error + for either sign of the step, rather than being clamped to empty. + +Re-vendoring those two files and teaching `zarr_indexing.messages` the new +desugaring are one change: the corpus is the definition of correct here, so it +lands in the same commit as the code that satisfies it. + +ndsel PR #3 (merged) specified empty `index_array` serialization, adding two +fixtures to `transform.json`: `normalize` carries an empty `index_array` +verbatim (it is not rewritten to a constant map), while a producer SHOULD +collapse it to a constant output map — which `zarr_indexing.json` already does. diff --git a/packages/zarr-indexing/tests/conformance/README.md b/packages/zarr-indexing/tests/conformance/README.md new file mode 100644 index 0000000000..ecb0c57ca2 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/README.md @@ -0,0 +1,16 @@ +# ndsel conformance corpus + +Language-agnostic fixtures. Each file is a JSON array of cases. + +A **success** case: + { "name": "...", "input": , "normalized": } + +An **error** case: + { "name": "...", "input": , "error": "" } + +An implementation is conformant iff, for every success case, +`normalize(input)` equals `normalized` by structural JSON equality, and for +every error case, `normalize(input)` is rejected with the given reason code. + +The `normalized` value is a canonical `transform` body (the `kind` field is +omitted; implementations compare the transform structure). diff --git a/packages/zarr-indexing/tests/conformance/box.json b/packages/zarr-indexing/tests/conformance/box.json new file mode 100644 index 0000000000..e847872f86 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/box.json @@ -0,0 +1,50 @@ +[ + { + "name": "box/2d-min-max", + "input": { "kind": "box", "inclusive_min": [0, 0], "exclusive_max": [3, 4] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 4], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "box/shape-only-origin-zero", + "input": { "kind": "box", "shape": [5] }, + "normalized": { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [5], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 1, "input_dimension": 0 } ] + } + }, + { + "name": "box/inclusive-max", + "input": { "kind": "box", "inclusive_min": [2], "inclusive_max": [9] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [2], "input_exclusive_max": [10], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 1, "input_dimension": 0 } ] + } + }, + { + "name": "box/implicit-and-infinite-bounds", + "input": { "kind": "box", "inclusive_min": [["-inf"], 0], "exclusive_max": [["+inf"], 4], "labels": ["t", ""] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [["-inf"], 0], + "input_exclusive_max": [["+inf"], 4], + "input_labels": ["t", ""], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/errors.json b/packages/zarr-indexing/tests/conformance/errors.json new file mode 100644 index 0000000000..072acd0af5 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/errors.json @@ -0,0 +1,25 @@ +[ + { "name": "error/step-zero", "input": { "kind": "slice", "start": [0], "stop": [4], "step": [0] }, "error": "step_zero" }, + { "name": "error/slice-reversed-interval-unit-step", "input": { "kind": "slice", "start": [9], "stop": [0] }, "error": "bounds_out_of_order" }, + { "name": "error/slice-reversed-interval-positive-step", "input": { "kind": "slice", "start": [9], "stop": [0], "step": [2] }, "error": "bounds_out_of_order" }, + { "name": "error/slice-reversed-interval-negative-step", "input": { "kind": "slice", "start": [5], "stop": [6], "step": [-1] }, "error": "bounds_out_of_order" }, + { "name": "error/multiple-upper-bounds", "input": { "kind": "box", "shape": [3], "exclusive_max": [3] }, "error": "multiple_upper_bounds" }, + { "name": "error/rank-mismatch", "input": { "kind": "slice", "start": [0, 0], "stop": [4] }, "error": "rank_mismatch" }, + { "name": "error/unknown-kind", "input": { "kind": "bogus" }, "error": "unknown_kind" }, + { "name": "error/transform-multiple-upper-bounds", "input": { "kind": "transform", "input_shape": [3], "input_exclusive_max": [3] }, "error": "multiple_upper_bounds" }, + { "name": "error/transform-rank-mismatch", "input": { "kind": "transform", "input_rank": 2, "input_inclusive_min": [0] }, "error": "rank_mismatch" }, + { "name": "error/missing-kind", "input": { "coords": [1, 2] }, "error": "invalid_json" }, + { "name": "error/point-missing-coords", "input": { "kind": "point" }, "error": "invalid_json" }, + { "name": "error/point-bool-coord", "input": { "kind": "point", "coords": [true] }, "error": "invalid_json" }, + { "name": "error/slice-missing-stop", "input": { "kind": "slice", "start": [0] }, "error": "invalid_json" }, + { "name": "error/box-non-list-bound", "input": { "kind": "box", "inclusive_min": 5 }, "error": "invalid_json" }, + { "name": "error/points-bool-coord", "input": { "kind": "points", "coords": [[true]] }, "error": "invalid_json" }, + { "name": "error/integer-out-of-i64-range", "input": { "kind": "point", "coords": [99999999999999999999] }, "error": "invalid_json" }, + { "name": "error/box-inverted-bounds", "input": { "kind": "box", "inclusive_min": [5], "exclusive_max": [3] }, "error": "bounds_out_of_order" }, + { "name": "error/box-negative-shape", "input": { "kind": "box", "shape": [-3] }, "error": "bounds_out_of_order" }, + { "name": "error/transform-inverted-bounds", "input": { "kind": "transform", "input_inclusive_min": [0], "input_exclusive_max": [-1] }, "error": "bounds_out_of_order" }, + { "name": "error/output-map-conflict", "input": { "kind": "transform", "output": [{ "input_dimension": 0, "index_array": [1, 2] }] }, "error": "output_map_conflict" }, + { "name": "error/box-unknown-field", "input": { "kind": "box", "shapee": [3] }, "error": "unknown_field" }, + { "name": "error/point-unknown-field", "input": { "kind": "point", "coords": [1], "extra": true }, "error": "unknown_field" }, + { "name": "error/output-map-unknown-field", "input": { "kind": "transform", "output": [{ "offset": 0, "bogus": 1 }] }, "error": "unknown_field" } +] diff --git a/packages/zarr-indexing/tests/conformance/point.json b/packages/zarr-indexing/tests/conformance/point.json new file mode 100644 index 0000000000..99a5ea16d8 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/point.json @@ -0,0 +1,30 @@ +[ + { + "name": "point/2d", + "input": { "kind": "point", "coords": [4, 7] }, + "normalized": { + "input_rank": 0, + "input_inclusive_min": [], + "input_exclusive_max": [], + "input_labels": [], + "output": [ { "offset": 4 }, { "offset": 7 } ] + } + }, + { + "name": "point/scalar-0d", + "input": { "kind": "point", "coords": [] }, + "normalized": { + "input_rank": 0, "input_inclusive_min": [], "input_exclusive_max": [], + "input_labels": [], "output": [] + } + }, + { + "name": "point/large-i64", + "input": { "kind": "point", "coords": [1152921504606846976] }, + "normalized": { + "input_rank": 0, "input_inclusive_min": [], "input_exclusive_max": [], + "input_labels": [], + "output": [ { "offset": 1152921504606846976 } ] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/points.json b/packages/zarr-indexing/tests/conformance/points.json new file mode 100644 index 0000000000..1ad92e12b1 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/points.json @@ -0,0 +1,34 @@ +[ + { + "name": "points/three-2d", + "input": { "kind": "points", "coords": [[1, 10], [2, 20], [3, 30]] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [1, 2, 3], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "index_array": [10, 20, 30], "index_array_bounds": ["-inf", "+inf"] } + ] + } + }, + { + "name": "points/1d", + "input": { "kind": "points", "coords": [[5], [9], [2]] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [5, 9, 2], "index_array_bounds": ["-inf", "+inf"] } + ] + } + }, + { + "name": "points/empty", + "input": { "kind": "points", "coords": [] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [0], + "input_labels": [""], + "output": [] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/slice.json b/packages/zarr-indexing/tests/conformance/slice.json new file mode 100644 index 0000000000..959ebc6247 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/slice.json @@ -0,0 +1,156 @@ +[ + { + "name": "slice/unit-step-preserves-frame", + "input": { "kind": "slice", "start": [5], "stop": [10] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [5], "input_exclusive_max": [10], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/divisible-stride", + "input": { "kind": "slice", "start": [4], "stop": [10], "step": [2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [2], "input_exclusive_max": [5], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/nondivisible-stride-phase-offset", + "input": { "kind": "slice", "start": [5], "stop": [10], "step": [2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [2], "input_exclusive_max": [5], + "input_labels": [""], + "output": [ { "offset": 1, "stride": 2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/2d-mixed-step", + "input": { "kind": "slice", "start": [0, 5], "stop": [10, 10], "step": [2, 1] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [0, 5], + "input_exclusive_max": [5, 10], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 2, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "slice/negative-start-trunc-origin", + "input": { "kind": "slice", "start": [-9], "stop": [5], "step": [2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-4], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -1, "stride": 2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-start-trunc-origin-step3", + "input": { "kind": "slice", "start": [-8], "stop": [6], "step": [3] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-2], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -2, "stride": 3, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-full-reverse", + "input": { "kind": "slice", "start": [19], "stop": [-1], "step": [-1] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-19], "input_exclusive_max": [1], + "input_labels": [""], + "output": [ { "offset": 0, "stride": -1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-divisible-span", + "input": { "kind": "slice", "start": [15], "stop": [5], "step": [-2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-7], "input_exclusive_max": [-2], + "input_labels": [""], + "output": [ { "offset": 1, "stride": -2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-nondivisible-span", + "input": { "kind": "slice", "start": [15], "stop": [5], "step": [-4] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-3], "input_exclusive_max": [0], + "input_labels": [""], + "output": [ { "offset": 3, "stride": -4, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-down-to-zero", + "input": { "kind": "slice", "start": [9], "stop": [0], "step": [-2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-4], "input_exclusive_max": [1], + "input_labels": [""], + "output": [ { "offset": 1, "stride": -2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-negative-interval", + "input": { "kind": "slice", "start": [-1], "stop": [-6], "step": [-2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -1, "stride": -2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-negative-interval-step3", + "input": { "kind": "slice", "start": [-2], "stop": [-9], "step": [-3] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -2, "stride": -3, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-single-point", + "input": { "kind": "slice", "start": [5], "stop": [4], "step": [-3] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-1], "input_exclusive_max": [0], + "input_labels": [""], + "output": [ { "offset": 2, "stride": -3, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-empty", + "input": { "kind": "slice", "start": [5], "stop": [5], "step": [-1] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-5], "input_exclusive_max": [-5], + "input_labels": [""], + "output": [ { "offset": 0, "stride": -1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-keeps-labels", + "input": { "kind": "slice", "start": [19], "stop": [-1], "step": [-1], "labels": ["x"] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-19], "input_exclusive_max": [1], + "input_labels": ["x"], + "output": [ { "offset": 0, "stride": -1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/2d-mixed-sign-step", + "input": { "kind": "slice", "start": [19, 0], "stop": [-1, 10], "step": [-1, 2] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [-19, 0], + "input_exclusive_max": [1, 5], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": -1, "input_dimension": 0 }, + { "offset": 0, "stride": 2, "input_dimension": 1 } + ] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/transform.json b/packages/zarr-indexing/tests/conformance/transform.json new file mode 100644 index 0000000000..3d12fe3352 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/transform.json @@ -0,0 +1,94 @@ +[ + { + "name": "transform/omitted-output-identity", + "input": { "kind": "transform", "input_inclusive_min": [0, 0], "input_exclusive_max": [3, 4] }, + "normalized": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [3, 4], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "transform/implicit-bounds-and-labels", + "input": { + "kind": "transform", + "input_inclusive_min": [["-inf"], 7], + "input_exclusive_max": [["+inf"], 11], + "input_labels": ["x", "y"] + }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [["-inf"], 7], + "input_exclusive_max": [["+inf"], 11], + "input_labels": ["x", "y"], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "transform/explicit-output-all-three-map-kinds", + "input": { + "kind": "transform", + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "output": [ + { "offset": 7 }, + { "input_dimension": 0, "stride": 2 }, + { "index_array": [1, 2, 3] } + ] + }, + "normalized": { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + { "offset": 7 }, + { "offset": 0, "stride": 2, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "index_array": [1, 2, 3], "index_array_bounds": ["-inf", "+inf"] } + ] + } + }, + { + "name": "transform/empty-index-array-carried-verbatim", + "input": { + "kind": "transform", + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 3], + "output": [{ "index_array": [] }, { "input_dimension": 1 }] + }, + "normalized": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [0, 3], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "transform/empty-index-array-is-idempotent", + "input": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [0, 3], + "input_labels": ["", ""], + "kind": "transform", + "output": [ + { "offset": 0, "stride": 1, "index_array": [], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + }, + "normalized": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [0, 3], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + } +] diff --git a/packages/zarr-indexing/tests/test_chunk_resolution.py b/packages/zarr-indexing/tests/test_chunk_resolution.py new file mode 100644 index 0000000000..fbd779f463 --- /dev/null +++ b/packages/zarr-indexing/tests/test_chunk_resolution.py @@ -0,0 +1,598 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest +from hypothesis import assume, given +from hypothesis import strategies as st + +import zarr_indexing +from zarr_indexing import ( + ChunkGrid, + ChunkPlan, + ChunkProjection, + FixedDimension, + VaryingDimension, + chunk_resolution, + plan_chunks, +) +from zarr_indexing.domain import IndexDomain +from zarr_indexing.grid import dimension_grids_from_chunks +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import IndexTransform + + +def _storage_of(transform: IndexTransform, point: tuple[int, ...]) -> tuple[int, ...]: + """Evaluate the three map forms at one point, independently of planning.""" + result: list[int] = [] + for output_map in transform.output: + if isinstance(output_map, ConstantMap): + result.append(output_map.offset) + elif isinstance(output_map, DimensionMap): + result.append(output_map.offset + output_map.stride * point[output_map.input_dimension]) + else: + index = tuple( + 0 + if output_map.index_array.shape[axis] == 1 + else point[axis] - transform.domain.inclusive_min[axis] + for axis in range(output_map.index_array.ndim) + ) + result.append( + output_map.offset + output_map.stride * int(output_map.index_array[index]) + ) + return tuple(result) + + +def _points(domain: IndexDomain) -> list[tuple[int, ...]]: + """Enumerate a small finite domain in its own coordinates.""" + return [ + tuple( + coordinate + origin + for coordinate, origin in zip(position, domain.inclusive_min, strict=True) + ) + for position in np.ndindex(*domain.shape) + ] + + +def _count_intersect_calls(monkeypatch: pytest.MonkeyPatch) -> dict[str, int]: + """Count real intersections to protect touched-only candidate enumeration.""" + calls = {"n": 0} + original = IndexTransform.intersect + + def counting(self: IndexTransform, output_domain: IndexDomain) -> object: + calls["n"] += 1 + return original(self, output_domain) + + monkeypatch.setattr(IndexTransform, "intersect", counting) + return calls + + +def test_basic_plan_is_reiterable_and_projects_both_spaces() -> None: + """A plan can be revisited without losing either side of each projection.""" + transform = IndexTransform.from_shape((6,))[1:6] + grids = dimension_grids_from_chunks((3,), (6,)) + + plan = plan_chunks(transform, grids) + first = list(plan) + second = list(plan.projections()) + + assert isinstance(plan, ChunkPlan) + assert all(isinstance(projection, ChunkProjection) for projection in first) + assert [projection.chunk_coords for projection in first] == [(0,), (1,)] + assert [projection.chunk_domain for projection in first] == [ + IndexDomain((0,), (3,)), + IndexDomain((3,), (6,)), + ] + assert [projection.coverage for projection in first] == ["partial", "full"] + assert first == second + assert all( + projection.chunk_transform.domain == projection.cell_transform.domain + for projection in first + ) + assert all(projection.chunk_transform.domain.origin == (0,) for projection in first) + + +def test_projection_requires_one_shared_synthetic_domain() -> None: + """Paired transforms with different cell domains are rejected as incoherent.""" + with pytest.raises(ValueError, match="must share an input domain"): + ChunkProjection( + chunk_coords=(0,), + chunk_domain=IndexDomain.from_shape((3,)), + chunk_transform=IndexTransform.identity(IndexDomain.from_shape((2,))), + cell_transform=IndexTransform.identity(IndexDomain.from_shape((1,))), + coverage="partial", + ) + + +def test_projection_plan_is_the_only_public_chunk_resolution_surface() -> None: + """The greenfield API does not retain tuple or NumPy-selector bridges.""" + assert {"ChunkCoverage", "ChunkPlan", "ChunkProjection", "plan_chunks"} <= set( + zarr_indexing.__all__ + ) + assert "iter_chunk_transforms" not in zarr_indexing.__all__ + assert "sub_transform_to_selections" not in zarr_indexing.__all__ + + +def test_plan_rejects_grid_rank_different_from_transform_output_rank() -> None: + """A missing storage grid dimension is rejected before iteration.""" + transform = IndexTransform.from_shape((2, 3)) + + with pytest.raises(ValueError, match="1 grids for output rank 2"): + plan_chunks(transform, dimension_grids_from_chunks((2,), (2,))) + + +@pytest.mark.parametrize( + ("transform", "expected"), + [ + (IndexTransform.from_shape((5,)), ["full", "full"]), + (IndexTransform.from_shape((5,))[::-1], ["full", "full"]), + (IndexTransform.from_shape((5,))[::2], ["partial", "partial"]), + (IndexTransform.from_shape((5,))[2], ["partial"]), + ( + IndexTransform.from_shape((5,)).oindex[np.array([0, 1, 2, 3, 4])], + ["unknown", "unknown"], + ), + ], + ids=["clipped-edge", "reverse", "strided", "scalar", "fancy-is-conservative"], +) +def test_coverage_classification(transform: IndexTransform, expected: list[str]) -> None: + """Coverage is exact for affine requests and conservative for gathers.""" + grids = dimension_grids_from_chunks((3,), (5,)) + + assert [projection.coverage for projection in plan_chunks(transform, grids)] == expected + + +def test_repeated_input_dependency_is_not_full_coverage() -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(DimensionMap(input_dimension=0), DimensionMap(input_dimension=0)), + ) + grids = dimension_grids_from_chunks((2, 2), (2, 2)) + + assert [projection.coverage for projection in plan_chunks(transform, grids)] == ["partial"] + + +def test_unused_input_axis_is_not_full_coverage() -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2, 2)), + output=(DimensionMap(input_dimension=0),), + ) + grids = dimension_grids_from_chunks((2,), (2,)) + + assert [projection.coverage for projection in plan_chunks(transform, grids)] == ["partial"] + + +@pytest.mark.parametrize( + ("transform", "grids"), + [ + ( + IndexTransform.from_shape((2, 3)), + dimension_grids_from_chunks((2, 3), (2, 3)), + ), + ( + IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=(DimensionMap(input_dimension=1), DimensionMap(input_dimension=0)), + ), + dimension_grids_from_chunks((3, 2), (3, 2)), + ), + ( + IndexTransform.from_shape((2, 3))[::-1, ::-1], + dimension_grids_from_chunks((2, 3), (2, 3)), + ), + ( + IndexTransform( + domain=IndexDomain((4, 7), (6, 10)), + output=( + DimensionMap(input_dimension=0, offset=-4), + DimensionMap(input_dimension=1, offset=-7), + ), + ), + dimension_grids_from_chunks((2, 3), (2, 3)), + ), + ], + ids=["identity", "axis-permutation", "reversal", "translated-unit-affine"], +) +def test_bijective_unit_affine_transforms_retain_full_coverage( + transform: IndexTransform, grids: tuple[Any, ...] +) -> None: + assert [projection.coverage for projection in plan_chunks(transform, grids)] == ["full"] + + +def test_rank_zero_transform_has_full_coverage() -> None: + transform = IndexTransform.identity(IndexDomain((), ())) + + assert [projection.coverage for projection in plan_chunks(transform, ())] == ["full"] + + +@pytest.mark.parametrize( + ("transform", "grids", "expected_coords"), + [ + ( + IndexTransform.from_shape((30,)), + dimension_grids_from_chunks((10,), (30,)), + [(0,), (1,), (2,)], + ), + ( + IndexTransform.from_shape((20, 30)), + dimension_grids_from_chunks((10, 10), (20, 30)), + [(i, j) for i in range(2) for j in range(3)], + ), + ( + IndexTransform.from_shape((100, 100))[25, :], + dimension_grids_from_chunks((10, 10), (100, 100)), + [(2, j) for j in range(10)], + ), + ( + IndexTransform.from_shape((100,))[8:15], + dimension_grids_from_chunks((10,), (100,)), + [(0,), (1,)], + ), + ], + ids=["one-dimensional", "two-dimensional", "constant-map", "slice"], +) +def test_affine_plans_touch_the_expected_chunks( + transform: IndexTransform, + grids: tuple[Any, ...], + expected_coords: list[tuple[int, ...]], +) -> None: + """Identity, constant, and sliced transforms enumerate literal grid cells.""" + assert [projection.chunk_coords for projection in plan_chunks(transform, grids)] == ( + expected_coords + ) + + +@pytest.mark.parametrize( + ("transform", "grids"), + [ + ( + IndexTransform.from_shape((6,)).oindex[np.array([4, 0, 4, 2])], + dimension_grids_from_chunks((3,), (6,)), + ), + ( + IndexTransform.from_shape((4, 5)).oindex[np.array([3, 0]), np.array([4, 1, 1])], + dimension_grids_from_chunks(((1, 3), (2, 3)), (4, 5)), + ), + ( + IndexTransform.from_shape((2, 4, 5)).vindex[ + ..., np.array([3, 0, 3]), np.array([4, 1, 1]) + ], + dimension_grids_from_chunks((1, 2, 3), (2, 4, 5)), + ), + ], + ids=["repeated-oindex", "irregular-oindex", "vindex-with-residual"], +) +def test_projection_invariants_for_fancy_selections( + transform: IndexTransform, grids: tuple[Any, ...] +) -> None: + """Both transforms agree pointwise and cell ranges tile request space once.""" + plan = plan_chunks(transform, grids) + request_points: list[tuple[int, ...]] = [] + + for projection in plan: + assert projection.coverage == "unknown" + assert projection.chunk_transform.domain == projection.cell_transform.domain + for cell_point in _points(projection.cell_transform.domain): + request_point = _storage_of(projection.cell_transform, cell_point) + chunk_point = _storage_of(projection.chunk_transform, cell_point) + storage_point = _storage_of(plan.transform, request_point) + chunk_origin = projection.chunk_domain.inclusive_min + assert chunk_point == tuple( + value - origin for value, origin in zip(storage_point, chunk_origin, strict=True) + ) + assert all( + 0 <= value < extent + for value, extent in zip(chunk_point, projection.chunk_domain.shape, strict=True) + ) + request_points.append(request_point) + + assert sorted(request_points) == sorted(_points(transform.domain)) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_orthogonal_array_map_plan_rejects_coordinate_below_grid(grid: Any) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(np.array([-1, 1], dtype=np.intp)),), + ) + + # The sorted 1-D fast path reports the first offending coordinate. + with pytest.raises(IndexError, match=r"index -1 is out of bounds"): + list(plan_chunks(transform, (grid,))) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_orthogonal_array_map_plan_rejects_coordinate_above_grid(grid: Any) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(np.array([1, 4], dtype=np.intp)),), + ) + + # The sorted 1-D fast path reports the first offending coordinate. + with pytest.raises(IndexError, match=r"index 4 is out of bounds"): + list(plan_chunks(transform, (grid,))) + + +def test_nonempty_identity_plan_rejects_zero_size_fixed_dimension() -> None: + transform = IndexTransform.from_shape((4,)) + + with pytest.raises(ValueError, match="size must be > 0 when extent is nonzero"): + list(plan_chunks(transform, (FixedDimension(size=0, extent=4),))) + + +@given( + origin=st.integers(min_value=-4, max_value=4), + extent=st.integers(min_value=0, max_value=8), + stride=st.integers(min_value=-3, max_value=3), +) +def test_affine_projection_pairs_reconstruct_independent_source_coordinates( + origin: int, extent: int, stride: int +) -> None: + """Bounded literal-domain examples preserve every request/storage pair.""" + anchor = extent - 1 if stride < 0 else 0 + offset = anchor - stride * origin + expected_pairs = [ + ((coordinate,), (source_coordinate,)) + for coordinate in range(origin, origin + extent) + if 0 <= (source_coordinate := offset + stride * coordinate) < extent + ] + assume(expected_pairs) + + unrestricted = IndexTransform( + domain=IndexDomain((origin,), (origin + extent,)), + output=(DimensionMap(input_dimension=0, offset=offset, stride=stride),), + ) + intersection = unrestricted.intersect(IndexDomain.from_shape((extent,))) + assume(intersection is not None) + transform, _ = intersection + grids = dimension_grids_from_chunks((min(3, extent),), (extent,)) + + reconstructed_pairs = [ + ( + _storage_of(projection.cell_transform, cell_coordinate), + tuple( + local_coordinate + chunk_origin + for local_coordinate, chunk_origin in zip( + _storage_of(projection.chunk_transform, cell_coordinate), + projection.chunk_domain.inclusive_min, + strict=True, + ) + ), + ) + for projection in plan_chunks(transform, grids) + for cell_coordinate in _points(projection.cell_transform.domain) + ] + + assert sorted(reconstructed_pairs) == sorted(expected_pairs) + + +def test_correlated_projection_preserves_nonzero_request_coordinates() -> None: + base = IndexTransform.identity(IndexDomain((2, 5), (4, 8))) + transform = base.vindex[np.array([2, 3], dtype=np.intp), :] + grids = dimension_grids_from_chunks((2, 4), (4, 8)) + + points = [ + transform.apply(projection.cell_transform.apply(cell)) + for projection in plan_chunks(transform, grids) + for cell in _points(projection.cell_transform.domain) + ] + + assert sorted(points) == [(2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] + + +def test_correlated_projection_preserves_translated_advanced_axis_coordinates() -> None: + transform = ( + IndexTransform.from_shape((4,)) + .vindex[np.array([0, 3], dtype=np.intp)] + .translate_domain_by((5,)) + ) + grids = dimension_grids_from_chunks((2,), (4,)) + + request_points = [ + projection.cell_transform.apply(cell) + for projection in plan_chunks(transform, grids) + for cell in _points(projection.cell_transform.domain) + ] + + assert sorted(request_points) == [(5,), (6,)] + + +def test_empty_request_has_no_projections() -> None: + """An empty fancy selection does not fabricate a touched chunk.""" + transform = IndexTransform.from_shape((10,)).oindex[np.array([], dtype=np.intp)] + grids = dimension_grids_from_chunks((3,), (10,)) + + assert list(plan_chunks(transform, grids)) == [] + + +class TestSortedOneDimensionalPlan: + def test_matches_general_resolution_for_randomized_selections( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """The direct sorted path has the same paired transforms as intersection.""" + rng = np.random.default_rng(0) + grids = ( + ChunkGrid(dimensions=(FixedDimension(size=7, extent=30),)), + ChunkGrid(dimensions=(VaryingDimension(edges=(3, 4, 8, 5, 10), extent=30),)), + ) + for grid in grids: + for _ in range(50): + indices = np.sort(rng.integers(0, 30, size=int(rng.integers(1, 80)))).astype( + np.intp + ) + transform = IndexTransform.from_shape((30,)).vindex[indices] + direct = list(plan_chunks(transform, grid.dimensions)) + with monkeypatch.context() as context: + context.setattr( + chunk_resolution, + "_one_dimensional_array_map", + lambda _transform: None, + ) + general = list(plan_chunks(transform, grid.dimensions)) + assert direct == general + + def test_sorted_coordinates_bypass_intersection(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Sorted coordinates partition directly at touched chunk boundaries.""" + transform = IndexTransform.from_shape((12,)).vindex[ + np.array([0, 3, 4, 4, 9, 11], dtype=np.intp) + ] + grid = ChunkGrid(dimensions=(FixedDimension(size=4, extent=12),)) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert [projection.chunk_coords for projection in projections] == [(0,), (1,), (2,)] + assert calls["n"] == 0 + assert [ + [ + _storage_of(projection.cell_transform, point)[0] + for point in _points(projection.cell_transform.domain) + ] + for projection in projections + ] == [[0, 1], [2, 3], [4, 5]] + + def test_unsorted_coordinates_use_intersection(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Unsorted coordinates retain the general intersection path.""" + transform = IndexTransform.from_shape((12,)).vindex[np.array([9, 0, 4], dtype=np.intp)] + grid = ChunkGrid(dimensions=(FixedDimension(size=4, extent=12),)) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert [projection.chunk_coords for projection in projections] == [(0,), (1,), (2,)] + assert calls["n"] == 3 + + +class CountingUnitGrid: + """A real unit grid that counts every planner-grid operation.""" + + def __init__(self, extent: int) -> None: + self._grid = FixedDimension(size=1, extent=extent) + self.calls = 0 + + def index_to_chunk(self, idx: int) -> int: + self.calls += 1 + return self._grid.index_to_chunk(idx) + + def chunk_offset(self, chunk_ix: int) -> int: + self.calls += 1 + return self._grid.chunk_offset(chunk_ix) + + def chunk_size(self, chunk_ix: int) -> int: + self.calls += 1 + return self._grid.chunk_size(chunk_ix) + + def indices_to_chunks( + self, indices: np.ndarray[Any, np.dtype[np.intp]] + ) -> np.ndarray[Any, np.dtype[np.intp]]: + self.calls += 1 + return self._grid.indices_to_chunks(indices) + + +def test_sparse_affine_plan_does_not_visit_intervening_chunks() -> None: + grid = CountingUnitGrid(extent=100_001) + transform = IndexTransform.from_shape((100_001,))[::100_000] + + assert [projection.chunk_coords for projection in plan_chunks(transform, (grid,))] == [ + (0,), + (100_000,), + ] + assert grid.calls <= 12 + + +def test_sparse_affine_plan_handles_large_origin_cancellation() -> None: + origin = int(np.iinfo(np.intp).max) + transform = IndexTransform( + domain=IndexDomain((origin,), (origin + 2,)), + output=(DimensionMap(input_dimension=0, offset=-2 * origin, stride=2),), + ) + grids = dimension_grids_from_chunks((1,), (3,)) + + assert [projection.chunk_coords for projection in plan_chunks(transform, grids)] == [ + (0,), + (2,), + ] + + +class TestTouchedOnlyCandidateEnumeration: + def test_sparse_one_dimensional_selection_skips_the_dense_span( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Two sorted points on a 1000-cell grid require no intersections.""" + transform = IndexTransform.from_shape((4000,)).vindex[np.array([1, 3997], dtype=np.intp)] + grid = ChunkGrid(dimensions=(FixedDimension(size=4, extent=4000),)) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert [projection.chunk_coords for projection in projections] == [(0,), (999,)] + assert calls["n"] == 0 + + @pytest.mark.parametrize( + ("mode", "expected_coords", "expected_calls"), + [ + ("orthogonal", [(0, 0), (0, 999), (999, 0), (999, 999)], 4), + ("correlated", [(0, 0), (999, 999)], 2), + ], + ) + def test_sparse_two_dimensional_selection_uses_only_touched_combinations( + self, + monkeypatch: pytest.MonkeyPatch, + mode: str, + expected_coords: list[tuple[int, int]], + expected_calls: int, + ) -> None: + """Orthogonal points use their outer product; correlated points remain paired.""" + base = IndexTransform.from_shape((4000, 4000)) + first = np.array([1, 3997], dtype=np.intp) + second = np.array([2, 3998], dtype=np.intp) + transform = ( + base.oindex[first, second] if mode == "orthogonal" else base.vindex[first, second] + ) + grid = ChunkGrid( + dimensions=( + FixedDimension(size=4, extent=4000), + FixedDimension(size=4, extent=4000), + ) + ) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert sorted(projection.chunk_coords for projection in projections) == expected_coords + assert calls["n"] == expected_calls + + def test_correlated_diagonal_scales_with_points_not_their_product( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Fifty diagonal points require fifty, rather than 2500, intersections.""" + n_points = 50 + coordinates = np.arange(n_points, dtype=np.intp) * 8 + transform = IndexTransform.from_shape((4000, 4000)).vindex[coordinates, coordinates] + grid = ChunkGrid( + dimensions=( + FixedDimension(size=4, extent=4000), + FixedDimension(size=4, extent=4000), + ) + ) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert sorted(projection.chunk_coords for projection in projections) == [ + (2 * index, 2 * index) for index in range(n_points) + ] + assert calls["n"] == n_points diff --git a/packages/zarr-indexing/tests/test_composition.py b/packages/zarr-indexing/tests/test_composition.py new file mode 100644 index 0000000000..0cb6155344 --- /dev/null +++ b/packages/zarr-indexing/tests/test_composition.py @@ -0,0 +1,474 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import IndexTransform + + +class TestComposeConstantInner: + """Inner = constant. Result is always constant.""" + + def test_constant_inner_any_outer(self) -> None: + outer = IndexTransform.from_shape((5,)) + inner = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ConstantMap(offset=42),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 42 + + +class TestComposeDimensionInner: + """Inner = DimensionMap.""" + + def test_dimension_inner_constant_outer(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=3),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 25 + + def test_dimension_inner_constant_outer_rejects_affine_overflow(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=2**62),), + ) + inner = IndexTransform( + domain=IndexDomain((2**62,), (2**62 + 1,)), + output=(DimensionMap(input_dimension=0, stride=4),), + ) + + with pytest.raises(OverflowError, match="outside np.intp"): + outer.compose(inner) + + def test_dimension_inner_dimension_outer(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=5, stride=2),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=3),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 25 + assert result.output[0].stride == 6 + assert result.output[0].input_dimension == 0 + + def test_dimension_inner_array_outer(self) -> None: + arr = np.array([0, 1, 2], dtype=np.intp) + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=arr, offset=5, stride=2),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=3),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + assert result.output[0].offset == 25 + assert result.output[0].stride == 6 + np.testing.assert_array_equal(result.output[0].index_array, arr) + + +class TestComposeArrayInner: + """Inner = ArrayMap.""" + + def test_array_inner_constant_outer(self) -> None: + inner_arr = np.array([10, 20, 30], dtype=np.intp) + outer = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ConstantMap(offset=1),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=inner_arr, offset=0, stride=1),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 20 + + def test_array_inner_constant_outer_rejects_affine_overflow(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=0),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + + with pytest.raises(OverflowError, match="outside np.intp"): + outer.compose(inner) + + def test_array_inner_array_outer(self) -> None: + outer_arr = np.array([0, 2, 1], dtype=np.intp) + inner_arr = np.array([10, 20, 30], dtype=np.intp) + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=outer_arr, offset=0, stride=1),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=inner_arr, offset=0, stride=1),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + expected = np.array([10, 30, 20], dtype=np.intp) + np.testing.assert_array_equal(result.output[0].index_array, expected) + + +def _storage_of(transform: IndexTransform, point: tuple[int, ...]) -> tuple[int, ...]: + """The storage coordinates a transform assigns to one input point. + + The point is given in the transform's own domain coordinates; an index array + carries the full input rank, singleton on the axes it does not vary over, and + is addressed positionally from the domain origin. + """ + coords: list[int] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + coords.append(m.offset) + elif isinstance(m, DimensionMap): + coords.append(m.offset + m.stride * point[m.input_dimension]) + else: + origin = transform.domain.inclusive_min + idx = tuple( + 0 if m.index_array.shape[axis] == 1 else point[axis] - origin[axis] + for axis in range(m.index_array.ndim) + ) + coords.append(m.offset + m.stride * int(m.index_array[idx])) + return tuple(coords) + + +def _assert_composes_pointwise(outer: IndexTransform, inner: IndexTransform) -> None: + """`outer.compose(inner)` must agree with running the two in sequence.""" + composed = outer.compose(inner) + assert composed.domain == outer.domain + lo = outer.domain.inclusive_min + hi = outer.domain.exclusive_max + for coord in np.ndindex(*outer.domain.shape): + point = tuple(int(c) + int(o) for c, o in zip(coord, lo, strict=True)) + assert all(point[d] < hi[d] for d in range(len(hi))) + intermediate = _storage_of(outer, point) + assert _storage_of(composed, point) == _storage_of(inner, intermediate) + + +class TestComposeOverANonZeroOriginDomain: + """The outer domain need not start at 0 — a step-1 slice preserves its + literal bounds and a negative step produces a negative origin — so the inner + map has to be evaluated over the outer domain's real range.""" + + def test_array_inner_sliced_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.identity(IndexDomain.from_shape((5,)))[1:4] + assert outer.domain.inclusive_min == (1,) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal( + result.output[0].index_array, np.array([1, 4, 1], dtype=np.intp) + ) + _assert_composes_pointwise(outer, inner) + + def test_array_inner_reversed_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.identity(IndexDomain.from_shape((5,)))[::-1] + assert outer.domain.inclusive_min == (-4,) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal( + result.output[0].index_array, np.array([5, 1, 4, 1, 3], dtype=np.intp) + ) + _assert_composes_pointwise(outer, inner) + + def test_array_inner_strided_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5, 9])] + outer = IndexTransform.identity(IndexDomain.from_shape((6,)))[1::2] + _assert_composes_pointwise(outer, inner) + + def test_array_inner_translated_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.identity(IndexDomain.from_shape((5,))).translate_domain_to((-2,)) + _assert_composes_pointwise(outer, inner) + + def test_array_inner_array_outer_over_a_shifted_domain(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.from_shape((5,)).oindex[np.array([4, 0, 2])] + _assert_composes_pointwise(outer, inner) + + def test_array_inner_constant_outer_over_a_shifted_domain(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ConstantMap(offset=3),), + ) + _assert_composes_pointwise(outer, inner) + + +class TestComposeMultiDim: + def test_2d_identity_compose(self) -> None: + a = IndexTransform.from_shape((10, 20)) + b = IndexTransform.from_shape((10, 20)) + result = a.compose(b) + assert result.domain.shape == (10, 20) + for i in range(2): + m = result.output[i] + assert isinstance(m, DimensionMap) + assert m.input_dimension == i + assert m.offset == 0 + assert m.stride == 1 + + def test_mixed_map_types(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=( + ConstantMap(offset=5), + DimensionMap(input_dimension=0, offset=0, stride=1), + ), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10, 10)), + output=( + DimensionMap(input_dimension=0, offset=2, stride=3), + DimensionMap(input_dimension=1, offset=0, stride=1), + ), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 17 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 0 + assert result.output[1].offset == 0 + assert result.output[1].stride == 1 + + def test_rank_mismatch_raises(self) -> None: + outer = IndexTransform.from_shape((10,)) + inner = IndexTransform.from_shape((10, 20)) + with pytest.raises(ValueError, match="rank"): + outer.compose(inner) + + +class TestComposeInnerDomainValidation: + @pytest.mark.parametrize( + ("outer_map", "inner_lower"), + [ + (ConstantMap(offset=10), 10), + (ConstantMap(offset=14), 10), + (DimensionMap(input_dimension=0, offset=10, stride=1), 10), + (DimensionMap(input_dimension=0, offset=14, stride=-1), 10), + (DimensionMap(input_dimension=0, offset=10**100, stride=1), 10**100), + ], + ids=["lower-bound", "upper-bound", "forward", "reverse", "arbitrary-integer"], + ) + def test_valid_constant_and_affine_boundaries( + self, outer_map: ConstantMap | DimensionMap, inner_lower: int + ) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(outer_map,), + ) + inner = IndexTransform( + domain=IndexDomain((inner_lower,), (inner_lower + 5,)), + output=(DimensionMap(input_dimension=0),), + ) + + result = outer.compose(inner) + + assert result.domain == outer.domain + _assert_composes_pointwise(outer, inner) + + def test_rejects_constant_outer_coordinate_outside_inner_domain(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=2),), + ) + inner = IndexTransform.identity(IndexDomain((0,), (2,))) + + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) + + def test_rejects_affine_outer_range_crossing_inner_domain(self) -> None: + outer = IndexTransform( + domain=IndexDomain((10**100,), (10**100 + 3,)), + output=(DimensionMap(input_dimension=0),), + ) + inner = IndexTransform.identity(IndexDomain((10**100,), (10**100 + 2,))) + + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) + + def test_empty_outer_domain_does_not_evaluate_nonexistent_points(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((0,)), + output=(ConstantMap(offset=99),), + ) + inner = IndexTransform.identity(IndexDomain((0,), (2,))) + + result = outer.compose(inner) + + assert result.domain.shape == (0,) + assert result.output == (ConstantMap(offset=99),) + + +class TestComposeMultidimensionalArrayInner: + def test_identity_gathers_a_two_dimensional_array_map(self) -> None: + inner = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap( + index_array=np.array([[11, 13, 17], [19, 23, 29]], dtype=np.intp), + offset=5, + stride=2, + ), + ), + ) + outer = IndexTransform.identity(inner.domain) + + result = outer.compose(inner) + + assert result == inner + _assert_composes_pointwise(outer, inner) + + def test_mixed_affine_and_constant_outputs_gather_with_metadata(self) -> None: + inner = IndexTransform( + domain=IndexDomain((4, 8), (7, 10)), + output=( + ArrayMap( + index_array=np.array([[2, 3], [5, 7], [11, 13]], dtype=np.intp), + offset=-3, + stride=4, + ), + ), + ) + outer = IndexTransform( + domain=IndexDomain((-2,), (0,)), + output=( + DimensionMap(input_dimension=0, offset=7, stride=1), + ConstantMap(offset=9), + ), + ) + + result = outer.compose(inner) + + assert result.domain == outer.domain + assert len(result.output) == 1 + array_map = result.output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (2,) + assert array_map.offset == -3 + assert array_map.stride == 4 + np.testing.assert_array_equal(array_map.index_array, np.array([7, 13], dtype=np.intp)) + _assert_composes_pointwise(outer, inner) + + def test_out_of_bounds_affine_output_is_rejected_before_gather(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=( + DimensionMap(input_dimension=0, offset=1, stride=1), + ConstantMap(offset=0), + ), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(np.arange(6, dtype=np.intp).reshape(3, 2)),), + ) + + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) + + def test_rank_zero_array_map_composition(self) -> None: + domain = IndexDomain((), ()) + outer = IndexTransform.identity(domain) + inner = IndexTransform( + domain=domain, + output=(ArrayMap(np.array(7, dtype=np.intp), offset=2, stride=3),), + ) + + result = outer.compose(inner) + + assert result.domain == domain + assert result.output == (ConstantMap(offset=23),) + + +class TestComposeChain: + def test_three_transforms(self) -> None: + a = IndexTransform.from_shape((100,)) + b = IndexTransform( + domain=IndexDomain.from_shape((100,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=1),), + ) + c = IndexTransform( + domain=IndexDomain.from_shape((110,)), + output=(DimensionMap(input_dimension=0, offset=5, stride=2),), + ) + bc = b.compose(c) + abc = a.compose(bc) + assert isinstance(abc.output[0], DimensionMap) + assert abc.output[0].offset == 25 + assert abc.output[0].stride == 2 + + +def test_composing_an_inner_array_with_a_broadcast_axis_wider_than_one_cell() -> None: + """A non-dependency axis is a singleton that broadcasts, so its coordinate is 0. + + Indexing it by the raw intermediate coordinate walked off the end of an axis + the array only has one entry for. + """ + outer = IndexTransform( + domain=IndexDomain(inclusive_min=(-2,), exclusive_max=(0,)), + output=(ConstantMap(offset=1), ConstantMap(offset=0)), + ) + inner = IndexTransform( + domain=IndexDomain(inclusive_min=(0, 0), exclusive_max=(2, 1)), + output=(ArrayMap(index_array=np.array([[13]], dtype=np.intp), offset=-2, stride=2),), + ) + composed = outer.compose(inner) + assert composed.output[0] == ConstantMap(offset=24) + + +def test_composing_a_one_dimensional_inner_array_under_a_higher_rank_outer() -> None: + """The shortcut gated on the output rank but sized by the input rank. + + A rank-2 outer therefore built a rank-1 array for a rank-2 domain, which the + engine's own invariant then rejected. + """ + outer = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=(DimensionMap(input_dimension=0, offset=1, stride=1),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ArrayMap(index_array=np.array([7, 3, 5, 1], dtype=np.intp)),), + ) + composed = outer.compose(inner) + array_map = composed.output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (2, 1) + np.testing.assert_array_equal(array_map.index_array, np.array([[3], [5]])) + + +def test_composing_out_of_the_inner_domain_is_refused() -> None: + """An intermediate outside the inner domain wrapped NumPy-style and read a cell.""" + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=-3),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(index_array=np.array([7, 3], dtype=np.intp)),), + ) + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) diff --git a/packages/zarr-indexing/tests/test_conformance.py b/packages/zarr-indexing/tests/test_conformance.py new file mode 100644 index 0000000000..207a9d8236 --- /dev/null +++ b/packages/zarr-indexing/tests/test_conformance.py @@ -0,0 +1,55 @@ +"""ndsel conformance corpus harness. + +Runs the vendored, language-agnostic ndsel fixtures (see +`tests/conformance/PROVENANCE.md`) against this package's message layer +(`zarr_indexing.messages`). An implementation is conformant iff: + +- for every *success* fixture, `normalize_ndsel(input)` equals the fixture's + `normalized` value by structural JSON equality; +- for every *error* fixture, `normalize_ndsel(input)` is rejected with an + `NdselError` carrying the fixture's `error` reason code. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from zarr_indexing.messages import NdselError, normalize_ndsel + +_CONFORMANCE_DIR = Path(__file__).parent / "conformance" + + +def _load_cases() -> list[tuple[str, dict[str, Any]]]: + cases: list[tuple[str, dict[str, Any]]] = [] + for path in sorted(_CONFORMANCE_DIR.glob("*.json")): + data = json.loads(path.read_text()) + cases.extend((f"{path.stem}::{case['name']}", case) for case in data) + return cases + + +_CASES = _load_cases() +_SUCCESS = [(name, c) for name, c in _CASES if "normalized" in c] +_ERROR = [(name, c) for name, c in _CASES if "error" in c] + + +def test_corpus_is_present() -> None: + # Guard against an empty/missing vendored corpus silently passing. + assert len(_SUCCESS) > 0 + assert len(_ERROR) > 0 + + +@pytest.mark.parametrize(("name", "case"), _SUCCESS, ids=[name for name, _ in _SUCCESS]) +def test_success_fixture(name: str, case: dict[str, Any]) -> None: + result = normalize_ndsel(case["input"]) + assert result == case["normalized"] + + +@pytest.mark.parametrize(("name", "case"), _ERROR, ids=[name for name, _ in _ERROR]) +def test_error_fixture(name: str, case: dict[str, Any]) -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel(case["input"]) + assert excinfo.value.reason == case["error"] diff --git a/packages/zarr-indexing/tests/test_doc_examples.py b/packages/zarr-indexing/tests/test_doc_examples.py new file mode 100644 index 0000000000..240bd48531 --- /dev/null +++ b/packages/zarr-indexing/tests/test_doc_examples.py @@ -0,0 +1,488 @@ +"""Executable documentation contracts. + +Two kinds of test live here, and nothing else: + +1. **Structural.** Every snippet include in the rendered docs resolves to a + real file and a balanced, non-empty region — discovered by scanning the + markdown, never hand-registered — and every example file executes. The + examples carry their own inline assertions, so executing one *is* the + value check; expected values are stated once, in the example, beside the + prose that narrates them. +2. **Behavioral.** Documented classes are exercised where the example cannot + assert the behavior itself: error paths, cache lifecycle invariants, and + contracts stated in prose about types the docs define. + +Editorial choices — section order, exact wording, teaching progression — are +deliberately not pinned here; they belong to review. Structural breakage +belongs to `mkdocs build --strict`, whose configuration makes it actually +fail on the relevant classes: `check_paths: true` for unresolvable includes, +and `validation` set to warn (strict turns warnings into errors) for broken +link anchors and nav-omitted pages. +""" + +from __future__ import annotations + +import re +import runpy +import subprocess +import sys +from pathlib import Path +from typing import Any + +import numpy as np +import pytest + +import zarr_indexing +import zarr_indexing.lazy_array as lazy_array_module +from zarr_indexing import IndexTransform, LazyArray, ReadContext + +DOCS = Path(__file__).parents[1] / "docs" +PACKAGE_ROOT = DOCS.parent +STANDALONE_EXAMPLES = PACKAGE_ROOT / "examples" +DOC_SNIPPETS_DIR = DOCS / "snippets" +CACHE_EXAMPLE = STANDALONE_EXAMPLES / "system_memory_chunk_cache" / "system_memory_chunk_cache.py" + +# Mirrors `pymdownx.snippets: base_path` in mkdocs.yml. If that list changes, +# change this one in the same commit. +SNIPPET_BASE_PATHS = (DOCS, STANDALONE_EXAMPLES) + +_INCLUDE = re.compile(r'--8<--\s+"(?P[^":\n]+?)(?::(?P[^"\n]+))?"') + + +def _markdown_includes() -> tuple[tuple[str, str, str | None], ...]: + """Every snippet include in the rendered docs: (page, target, region).""" + return tuple( + (str(page.relative_to(DOCS)), match["target"], match["region"]) + for page in sorted(DOCS.rglob("*.md")) + for match in _INCLUDE.finditer(page.read_text()) + ) + + +INCLUDES = _markdown_includes() +# In-process executables: every snippet, plus the one standalone example that +# is importable as a module. The lazy_indexing_* examples are CLI scripts +# (they parse argv and call sys.exit), so they run as subprocesses below — +# no other test in the repository executes them. +EXECUTABLES = (*sorted(DOC_SNIPPETS_DIR.glob("*.py")), CACHE_EXAMPLE) +CLI_EXAMPLES = tuple( + script for script in sorted(STANDALONE_EXAMPLES.glob("*/*.py")) if script not in EXECUTABLES +) + +PATTERN_NAMESPACE: dict[str, Any] = runpy.run_path(str(DOC_SNIPPETS_DIR / "indexing_patterns.py")) +PATTERN_CASES: tuple[dict[str, Any], ...] = PATTERN_NAMESPACE["PATTERN_CASES"] +CACHE_NAMESPACE: dict[str, Any] = runpy.run_path(str(CACHE_EXAMPLE)) + +# The documented pattern matrix must keep covering every selection family. +REQUIRED_PATTERNS = { + "basic-slice", + "integer-axis-removal", + "negative-stride", + "empty-selection", + "boolean-mask", + "orthogonal", + "vectorized", + "broadcasting", + "repeated-out-of-order", +} + + +# --------------------------------------------------------------------------- # +# Structural: the include graph and the executable examples +# --------------------------------------------------------------------------- # + + +def test_docs_reference_snippets_at_all() -> None: + """An empty scan means the include regex rotted, not that the docs did.""" + assert len(INCLUDES) >= 10 + assert any(region for _, _, region in INCLUDES) + + +@pytest.mark.parametrize( + ("page", "target", "region"), + INCLUDES, + ids=[ + f"{page}->{target}" + (f":{region}" if region else "") for page, target, region in INCLUDES + ], +) +def test_markdown_include_resolves(page: str, target: str, region: str | None) -> None: + """Each include names exactly one real file; each region is balanced and non-empty.""" + resolved = [base / target for base in SNIPPET_BASE_PATHS if (base / target).is_file()] + assert len(resolved) == 1, f"{page} includes {target!r}: resolved to {resolved or 'nothing'}" + if region is None: + return + source = resolved[0].read_text() + starts = re.findall(rf"^\s*# --8<-- \[start:{re.escape(region)}\]$", source, re.MULTILINE) + ends = re.findall(rf"^\s*# --8<-- \[end:{re.escape(region)}\]$", source, re.MULTILINE) + assert len(starts) == 1, f"{target}:{region} needs exactly one start marker, has {len(starts)}" + assert len(ends) == 1, f"{target}:{region} needs exactly one end marker, has {len(ends)}" + body = source.split(starts[0], maxsplit=1)[1].split(ends[0], maxsplit=1)[0] + assert body.strip(), f"{target}:{region} is empty" + + +def test_snippet_directories_hold_only_their_kind() -> None: + """Rendered pages are markdown; executable snippets are Python.""" + assert all(p.suffix == ".md" for p in (DOCS / "examples").iterdir() if p.is_file()) + assert all(p.suffix == ".py" for p in DOC_SNIPPETS_DIR.iterdir() if p.is_file()) + + +@pytest.mark.parametrize("example", EXECUTABLES, ids=lambda path: path.stem) +def test_documentation_example_executes(example: Path) -> None: + """Examples are executable contracts; their inline asserts are the values check.""" + runpy.run_path(str(example), run_name="__main__") + + +@pytest.mark.parametrize("script", CLI_EXAMPLES, ids=lambda path: path.stem) +def test_cli_example_runs_as_a_subprocess(script: Path) -> None: + """The CLI examples exit 0 when run the way their READMEs instruct.""" + if "dask" in script.stem: + pytest.importorskip("dask.array") + completed = subprocess.run( + [sys.executable, str(script)], + capture_output=True, + text=True, + cwd=script.parent, + check=False, + ) + assert completed.returncode == 0, completed.stderr[-2000:] + + +@pytest.mark.parametrize( + "example_dir", + sorted(p for p in STANDALONE_EXAMPLES.iterdir() if p.is_dir()), + ids=lambda path: path.name, +) +def test_standalone_example_is_a_documented_script(example_dir: Path) -> None: + """Each standalone example ships a README and a same-named runnable script.""" + script = example_dir / f"{example_dir.name}.py" + assert script.is_file() + assert (example_dir / "README.md").is_file() + assert (DOCS / "examples" / f"{example_dir.name}.md").is_file() + assert script.read_text().startswith("# /// script\n"), "examples stay PEP 723 runnable" + + +# --------------------------------------------------------------------------- # +# Behavioral: the documented pattern matrix +# --------------------------------------------------------------------------- # + + +def test_indexing_pattern_matrix_is_complete() -> None: + assert {case["name"] for case in PATTERN_CASES} == REQUIRED_PATTERNS + + +def test_pattern_page_tabs_are_the_models() -> None: + """Both tabs of every matrix entry are the executable model, in order. + + The JSON tab must be the model's canonical wire form; the Python tab + must evaluate (in the executable matrix's namespace) to the model + itself. Either tab drifting from the snippet fails here. + """ + import json + import textwrap + + page = (DOCS / "guide" / "patterns.md").read_text() + + json_blocks = re.findall(r"```json\n(.*?)```", page, re.DOTALL) + assert len(json_blocks) == len(PATTERN_CASES) + for block, case in zip(json_blocks, PATTERN_CASES, strict=True): + assert json.loads(block) == case["transform"].to_json(), case["name"] + + python_blocks = [ + textwrap.dedent(block) + for block in re.findall(r"```python\n(.*?)```", page, re.DOTALL) + if "--8<--" not in block + ] + assert len(python_blocks) == len(PATTERN_CASES) + for block, case in zip(python_blocks, PATTERN_CASES, strict=True): + constructed = eval(block, dict(PATTERN_NAMESPACE)) + assert constructed == case["transform"], case["name"] + + +@pytest.mark.parametrize("case", PATTERN_CASES, ids=lambda case: case["name"]) +def test_indexing_pattern_matrix_matches_numpy(case: dict[str, Any]) -> None: + """The wrapper agrees with the matrix the snippet proves at the transform level.""" + image = PATTERN_NAMESPACE["image"] + lazy = LazyArray.from_numpy(image) + accessor = { + "basic": lazy.lazy, + "oindex": lazy.lazy.oindex, + "vindex": lazy.lazy.vindex, + }[case["mode"]] + view = accessor[case["selection"]] + result = view.result() + + np.testing.assert_array_equal(result, case["expected"]) + assert result.shape == case["shape"] + assert ("box" if view.is_box else "query") == case["category"] + + +# --------------------------------------------------------------------------- # +# Behavioral: contracts the guide states about wrapped sources and parts +# --------------------------------------------------------------------------- # + + +def test_default_source_contract_converts_basic_selected_slabs_to_system_memory() -> None: + """A source may return Python slabs as long as NumPy can convert each selected slab.""" + + class ListSlabSource: + def __init__(self) -> None: + self.data = np.arange(20).reshape(4, 5) + self.keys: list[tuple[Any, ...]] = [] + + @property + def shape(self) -> tuple[int, ...]: + return self.data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self.data.dtype + + def __getitem__(self, key: tuple[Any, ...]) -> object: + assert all(isinstance(item, (int, slice)) for item in key) + self.keys.append(key) + return self.data[key].tolist() + + source = ListSlabSource() + result = LazyArray(source).with_parts((2, 3)).lazy.oindex[[3, 1, 1], 1:5:2].result() + + np.testing.assert_array_equal(result, np.array([[16, 18], [6, 8], [6, 8]])) + assert len(source.keys) > 0 + assert all(all(isinstance(item, (int, slice)) for item in key) for key in source.keys) + + +def test_coordinate_array_example_preserves_order_and_duplicates() -> None: + """Coordinate arrays are ordered sequences, not mathematical sets.""" + view = LazyArray.from_numpy(np.arange(6)).with_parts((2,)).lazy.oindex[[4, 1, 1, 3]] + + np.testing.assert_array_equal(view.result(), np.array([4, 1, 1, 3])) + assembled = np.empty(view.shape, dtype=view.dtype) + for part in view.parts(): + assembled[part.out_selection] = part.view.result() + np.testing.assert_array_equal(assembled, np.array([4, 1, 1, 3])) + + +def test_documented_partition_transform_is_global_and_projection_is_chunk_local() -> None: + source = np.arange(8) + part = tuple(LazyArray.from_numpy(source).with_parts((4,)).parts())[1] + + assert part.view.transform.apply((0,)) == (4,) + assert part.view.array[part.view.transform.apply((0,))] == 4 + assert part.projection.chunk_transform.apply((0,)) == (0,) + + +@pytest.mark.parametrize( + ("mode", "parts"), + [ + ("per-axis", ((0,), (3,))), + ("per-axis", ((), (3,))), + ("uniform", (1, 1)), + ("per-axis", ((0, 0), (3,))), + ], + ids=["single-zero", "empty-sequence", "positive-uniform", "repeated-zero"], +) +def test_documented_zero_length_axis_partition_spellings_execute(mode: str, parts: Any) -> None: + data = np.zeros((0, 3)) + base = LazyArray.from_numpy(data) + view = base.with_parts(parts) if mode == "uniform" else base.with_parts_per_axis(parts) + + assert view.result().shape == (0, 3) + assert tuple(view.parts()) == () + + +def test_projection_example_exposes_paired_directions() -> None: + """Both transforms of every projection keep their documented output ranks.""" + namespace = runpy.run_path(str(DOC_SNIPPETS_DIR / "chunk_projection.py")) + np.testing.assert_array_equal(namespace["ADVANCED_RESULT"], namespace["ADVANCED_EXPECTED"]) + assert all(p.chunk_transform.output_rank == 2 for p in namespace["PROJECTIONS"]) + assert all(p.cell_transform.output_rank == 1 for p in namespace["PROJECTIONS"]) + + +@pytest.mark.parametrize( + "example", + [DOC_SNIPPETS_DIR / "integrations.py", CACHE_EXAMPLE], + ids=lambda path: path.stem, +) +def test_projection_examples_assemble_rank_zero_domains(example: Path) -> None: + """The examples' shared assembly helpers handle a zero-rank cell domain.""" + namespace = runpy.run_path(str(example)) + domain = zarr_indexing.IndexDomain((), ()) + cell_points = namespace["_domain_points"](domain) + destination = np.empty((), dtype=np.intp) + + values = namespace["_gather_and_scatter"]( + destination, + np.array(7, dtype=np.intp), + cell_points, + cell_points, + ) + + assert cell_points.shape == (1, 0) + assert values.shape == (1,) + assert destination[()] == 7 + + +# --------------------------------------------------------------------------- # +# Behavioral: the documented chunk cache (error paths the example cannot show) +# --------------------------------------------------------------------------- # + + +def make_documented_cache() -> tuple[Any, Any]: + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + cache_type = CACHE_NAMESPACE["SystemMemoryChunkCache"] + source = source_type(np.arange(48).reshape(6, 8), chunks=(3, 4)) + return source, cache_type(source, capacity=2) + + +def test_system_memory_cache_assembles_and_deduplicates_public_projections() -> None: + source, cache = make_documented_cache() + + np.testing.assert_array_equal(cache.oindex[[1, 1], 2], np.array([10, 10])) + assert tuple(source.reads) == ((0, 0),) + assert cache.projection_uses == (("chunk_transform", "context.transform"),) + + +def test_chunk_cache_queues_all_parts_before_loading( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source, cache = make_documented_cache() + planning_count = 0 + original_plan_chunks = lazy_array_module.plan_chunks + + def counted_plan_chunks(*args: Any, **kwargs: Any) -> Any: + nonlocal planning_count + planning_count += 1 + return original_plan_chunks(*args, **kwargs) + + with monkeypatch.context() as request_patch: + request_patch.setattr(lazy_array_module, "plan_chunks", counted_plan_chunks) + result = cache[1:5, 2] + + np.testing.assert_array_equal(result, np.array([10, 18, 26, 34])) + assert planning_count == 1 + assert source.reads == [(0, 0), (1, 0)] + + assert [ + (event.chunk_coords, event.previous.value, event.current.value) for event in cache.events + ] == [ + ((0, 0), "new", "queued"), + ((1, 0), "new", "queued"), + ((0, 0), "queued", "loading"), + ((0, 0), "loading", "ready"), + ((1, 0), "queued", "loading"), + ((1, 0), "loading", "ready"), + ] + + +def test_chunk_cache_reader_resolves_a_transform_from_cached_chunks() -> None: + """The reader boundary consumes the prepared projections of real parts.""" + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + reader_type = CACHE_NAMESPACE["SystemMemoryChunkReader"] + source = source_type(np.arange(48).reshape(6, 8), chunks=(3, 4)) + reader = reader_type(capacity=2) + view = LazyArray(source).with_reader(reader).lazy[1:5, 2] + parts = tuple(view.parts()) + out = np.empty(view.shape, dtype=source.dtype) + for part in parts: + destination = out[part.out_selection] + assert ( + reader.read_into( + source, + ReadContext(part.view.transform, part.projection), + destination, + ) + is None + ) + + np.testing.assert_array_equal(out, np.array([10, 18, 26, 34])) + assert source.reads == [(0, 0), (1, 0)] + assert reader.projection_uses == [ + ("chunk_transform", "context.transform"), + ("chunk_transform", "context.transform"), + ] + + +def test_chunk_cache_reader_requires_a_prepared_projection() -> None: + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + reader_type = CACHE_NAMESPACE["SystemMemoryChunkReader"] + source = source_type(np.arange(48).reshape(6, 8), chunks=(3, 4)) + transform = IndexTransform.from_shape(source.shape)[1:3, 2].translate_domain_to((0,)) + out = np.empty(transform.domain.shape, dtype=source.dtype) + + with pytest.raises(ValueError, match="requires context.projection"): + reader_type(capacity=2).read_into(source, ReadContext(transform), out) + + +def test_system_memory_cache_separates_basic_and_orthogonal_indexing() -> None: + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + cache_type = CACHE_NAMESPACE["SystemMemoryChunkCache"] + data = np.arange(48).reshape(6, 8) + cache = cache_type(source_type(data, chunks=(3, 4)), capacity=4) + row = np.array([0, 2]) + column = np.array([1, 3]) + + np.testing.assert_array_equal(cache[0:3, 1:4], data[0:3, 1:4]) + np.testing.assert_array_equal( + cache.oindex[row, column], + data[np.ix_(row, column)], + ) + + +def test_system_memory_cache_does_not_treat_array_keys_as_orthogonal() -> None: + source, cache = make_documented_cache() + row = np.array([0, 2]) + column = np.array([1, 3]) + + with pytest.raises(IndexError, match="unsupported selection type for basic indexing"): + cache[row, column] + + assert tuple(source.reads) == () + + +def test_system_memory_cache_assembles_a_scalar_selection() -> None: + source, cache = make_documented_cache() + + result = cache[1, 2] + + assert result.shape == () + assert result[()] == 10 + assert tuple(source.reads) == ((0, 0),) + assert cache.projection_uses == (("chunk_transform", "context.transform"),) + + +def test_system_memory_cache_is_documentation_only() -> None: + assert not hasattr(zarr_indexing, "SystemMemoryChunkCache") + assert not hasattr(zarr_indexing, "ChunkState") + + +def test_chunk_source_failure_is_retained_as_failed_with_its_cause() -> None: + source, cache = make_documented_cache() + source.failures.add((1, 1)) + + with pytest.raises(CACHE_NAMESPACE["ChunkLoadError"]) as error: + cache[3:5, 4:6] + + assert isinstance(error.value.__cause__, OSError) + assert cache.state((1, 1)).value == "failed" + assert tuple(source.reads) == ((1, 1),) + + +def test_failed_chunk_is_not_retried_implicitly() -> None: + source, cache = make_documented_cache() + source.failures.add((1, 1)) + with pytest.raises(CACHE_NAMESPACE["ChunkLoadError"]): + cache[3:5, 4:6] + with pytest.raises(CACHE_NAMESPACE["ChunkLoadError"]): + cache[3:5, 4:6] + + assert tuple(source.reads) == ((1, 1),) + + +def test_retry_requires_a_failed_chunk() -> None: + _, cache = make_documented_cache() + with pytest.raises(ValueError, match="retry requires failed chunk .*new"): + cache.retry((0, 0)) + + +def test_illegal_chunk_transition_is_rejected() -> None: + _, cache = make_documented_cache() + with pytest.raises(ValueError, match="illegal chunk transition new -> ready"): + cache.reader._transition((0, 0), CACHE_NAMESPACE["ChunkState"].READY, "test") diff --git a/packages/zarr-indexing/tests/test_domain.py b/packages/zarr-indexing/tests/test_domain.py new file mode 100644 index 0000000000..0278ecd714 --- /dev/null +++ b/packages/zarr-indexing/tests/test_domain.py @@ -0,0 +1,218 @@ +from __future__ import annotations + +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError + + +class TestIndexDomainConstruction: + def test_from_shape(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.inclusive_min == (0, 0) + assert d.exclusive_max == (10, 20) + assert d.ndim == 2 + assert d.origin == (0, 0) + assert d.shape == (10, 20) + + def test_from_shape_0d(self) -> None: + d = IndexDomain.from_shape(()) + assert d.ndim == 0 + assert d.shape == () + + def test_non_zero_origin(self) -> None: + d = IndexDomain(inclusive_min=(5, 10), exclusive_max=(15, 30)) + assert d.origin == (5, 10) + assert d.shape == (10, 20) + assert d.ndim == 2 + + def test_validation_mismatched_lengths(self) -> None: + with pytest.raises(ValueError, match="same length"): + IndexDomain(inclusive_min=(0,), exclusive_max=(10, 20)) + + def test_validation_min_greater_than_max(self) -> None: + with pytest.raises(ValueError, match="inclusive_min must be <="): + IndexDomain(inclusive_min=(10,), exclusive_max=(5,)) + + def test_empty_domain(self) -> None: + d = IndexDomain(inclusive_min=(5,), exclusive_max=(5,)) + assert d.shape == (0,) + + def test_labels(self) -> None: + d = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 20), labels=("x", "y")) + assert d.labels == ("x", "y") + + def test_labels_none(self) -> None: + d = IndexDomain.from_shape((10,)) + assert d.labels is None + + +class TestIndexDomainContains: + def test_contains_inside(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.contains((0, 0)) is True + assert d.contains((9, 19)) is True + assert d.contains((5, 10)) is True + + def test_contains_outside(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.contains((10, 0)) is False + assert d.contains((-1, 0)) is False + assert d.contains((0, 20)) is False + + def test_contains_non_zero_origin(self) -> None: + d = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + assert d.contains((5,)) is True + assert d.contains((9,)) is True + assert d.contains((4,)) is False + assert d.contains((10,)) is False + + def test_contains_wrong_ndim(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.contains((5,)) is False + + def test_contains_domain_inside(self) -> None: + outer = IndexDomain.from_shape((10, 20)) + inner = IndexDomain(inclusive_min=(2, 3), exclusive_max=(8, 15)) + assert outer.contains_domain(inner) is True + + def test_contains_domain_outside(self) -> None: + outer = IndexDomain.from_shape((10, 20)) + inner = IndexDomain(inclusive_min=(2, 3), exclusive_max=(11, 15)) + assert outer.contains_domain(inner) is False + + def test_contains_domain_wrong_ndim(self) -> None: + outer = IndexDomain.from_shape((10, 20)) + inner = IndexDomain.from_shape((5,)) + assert outer.contains_domain(inner) is False + + +class TestIndexDomainIntersect: + def test_overlapping(self) -> None: + a = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 10)) + b = IndexDomain(inclusive_min=(5, 5), exclusive_max=(15, 15)) + result = a.intersect(b) + assert result is not None + assert result.inclusive_min == (5, 5) + assert result.exclusive_max == (10, 10) + + def test_disjoint(self) -> None: + a = IndexDomain(inclusive_min=(0,), exclusive_max=(5,)) + b = IndexDomain(inclusive_min=(10,), exclusive_max=(15,)) + assert a.intersect(b) is None + + def test_touching_boundary(self) -> None: + a = IndexDomain(inclusive_min=(0,), exclusive_max=(5,)) + b = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + assert a.intersect(b) is None + + def test_contained(self) -> None: + a = IndexDomain.from_shape((20,)) + b = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + result = a.intersect(b) + assert result is not None + assert result.inclusive_min == (5,) + assert result.exclusive_max == (10,) + + def test_wrong_ndim(self) -> None: + a = IndexDomain.from_shape((10,)) + b = IndexDomain.from_shape((10, 20)) + with pytest.raises(ValueError, match="different ranks"): + a.intersect(b) + + +class TestIndexDomainTranslate: + def test_translate_positive(self) -> None: + d = IndexDomain.from_shape((10, 20)) + result = d.translate((5, 10)) + assert result.inclusive_min == (5, 10) + assert result.exclusive_max == (15, 30) + + def test_translate_negative(self) -> None: + d = IndexDomain(inclusive_min=(10, 20), exclusive_max=(30, 40)) + result = d.translate((-10, -20)) + assert result.inclusive_min == (0, 0) + assert result.exclusive_max == (20, 20) + + def test_translate_wrong_length(self) -> None: + d = IndexDomain.from_shape((10,)) + with pytest.raises(ValueError, match="same length"): + d.translate((1, 2)) + + +class TestIndexDomainNarrow: + def test_narrow_slice(self) -> None: + d = IndexDomain.from_shape((10, 20)) + result = d.narrow((slice(2, 8), slice(5, 15))) + assert result.inclusive_min == (2, 5) + assert result.exclusive_max == (8, 15) + + def test_narrow_int(self) -> None: + d = IndexDomain.from_shape((10, 20)) + result = d.narrow((3, slice(None))) + assert result.inclusive_min == (3, 0) + assert result.exclusive_max == (4, 20) + + def test_narrow_ellipsis(self) -> None: + d = IndexDomain.from_shape((10, 20, 30)) + result = d.narrow((slice(1, 5), ...)) + assert result.inclusive_min == (1, 0, 0) + assert result.exclusive_max == (5, 20, 30) + + def test_narrow_slice_none(self) -> None: + d = IndexDomain.from_shape((10,)) + result = d.narrow((slice(None),)) + assert result == d + + def test_narrow_non_zero_origin(self) -> None: + d = IndexDomain(inclusive_min=(10,), exclusive_max=(20,)) + result = d.narrow((slice(12, 18),)) + assert result.inclusive_min == (12,) + assert result.exclusive_max == (18,) + + def test_narrow_int_out_of_bounds(self) -> None: + d = IndexDomain.from_shape((10,)) + with pytest.raises(BoundsCheckError, match="out of bounds"): + d.narrow((10,)) + + def test_narrow_int_below_origin(self) -> None: + d = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + with pytest.raises(BoundsCheckError, match="out of bounds"): + d.narrow((4,)) + + def test_narrow_refuses_a_bound_outside_the_domain(self) -> None: + """Clamping made two different requests answer alike, and neither well. + + Indices here are absolute coordinates, so `-5` is a coordinate this + domain does not contain rather than NumPy's "five from the end" — and + clamping returned the whole axis for it, which is what a caller writing + the NumPy spelling would least expect. A stop past the end produced a + domain the parent did not contain. + """ + d = IndexDomain.from_shape((10,)) + with pytest.raises(BoundsCheckError, match="absolute coordinates"): + d.narrow((slice(-5, 100),)) + with pytest.raises(BoundsCheckError, match="out of bounds"): + d.narrow((slice(20, 30),)) + + def test_narrow_accepts_the_bounds_of_the_domain_itself(self) -> None: + d = IndexDomain.from_shape((10,)) + assert d.narrow((slice(0, 10),)) == d + + def test_narrow_bare_slice(self) -> None: + d = IndexDomain.from_shape((10,)) + result = d.narrow(slice(2, 8)) + assert result.inclusive_min == (2,) + assert result.exclusive_max == (8,) + + def test_narrow_too_many_indices(self) -> None: + d = IndexDomain.from_shape((10,)) + with pytest.raises(IndexError, match="too many indices"): + d.narrow((1, 2)) + + def test_narrow_step_not_one(self) -> None: + """A stride is not a bounds failure — the rest of the algebra raises + `ValueError` for a request it does not implement, and so does this.""" + d = IndexDomain.from_shape((10,)) + with pytest.raises(ValueError, match="step=1"): + d.narrow((slice(0, 10, 2),)) diff --git a/packages/zarr-indexing/tests/test_json.py b/packages/zarr-indexing/tests/test_json.py new file mode 100644 index 0000000000..9848c6801f --- /dev/null +++ b/packages/zarr-indexing/tests/test_json.py @@ -0,0 +1,586 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.messages import NdselError +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + output_index_map_from_json, +) +from zarr_indexing.transform import IndexTransform + +if TYPE_CHECKING: + from zarr_indexing.json import IndexTransformJSON + + +def _maps_equal(a: object, b: object) -> bool: + if type(a) is not type(b): + return False + if isinstance(a, ConstantMap): + assert isinstance(b, ConstantMap) + return a.offset == b.offset + if isinstance(a, DimensionMap): + assert isinstance(b, DimensionMap) + return (a.input_dimension, a.offset, a.stride) == (b.input_dimension, b.offset, b.stride) + assert isinstance(a, ArrayMap) + assert isinstance(b, ArrayMap) + return ( + a.offset == b.offset + and a.stride == b.stride + and np.array_equal(a.index_array, b.index_array) + ) + + +def _transforms_equal(a: IndexTransform, b: IndexTransform) -> bool: + """Structural equality that compares `ArrayMap` index arrays element-wise + (`IndexTransform`'s dataclass `__eq__` cannot, as numpy `==` is ambiguous).""" + return ( + a.domain == b.domain + and len(a.output) == len(b.output) + and all(_maps_equal(x, y) for x, y in zip(a.output, b.output, strict=True)) + ) + + +class TestIndexDomainJSON: + def test_roundtrip(self) -> None: + domain = IndexDomain(inclusive_min=(2, 5), exclusive_max=(10, 20)) + json = domain.to_json() + assert json == { + "input_inclusive_min": [2, 5], + "input_exclusive_max": [10, 20], + "input_labels": ["", ""], + } + restored = IndexDomain.from_json(json) + assert restored == domain + + def test_with_labels(self) -> None: + domain = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 20), labels=("x", "y")) + json = domain.to_json() + assert json["input_labels"] == ["x", "y"] + restored = IndexDomain.from_json(json) + assert restored.labels == ("x", "y") + + def test_without_labels_emits_empty_and_round_trips_to_none(self) -> None: + domain = IndexDomain.from_shape((5,)) + json = domain.to_json() + # Canonical form always writes labels; an unlabeled domain gets [""]*rank. + assert json["input_labels"] == [""] + restored = IndexDomain.from_json(json) + assert restored.labels is None + + def test_zero_origin(self) -> None: + domain = IndexDomain.from_shape((10, 20, 30)) + json = domain.to_json() + assert json == { + "input_inclusive_min": [0, 0, 0], + "input_exclusive_max": [10, 20, 30], + "input_labels": ["", "", ""], + } + assert IndexDomain.from_json(json) == domain + + +class TestOutputIndexMapJSON: + def test_constant(self) -> None: + m = ConstantMap(offset=42) + json = m.to_json() + assert json == {"offset": 42} + restored = output_index_map_from_json(json) + assert isinstance(restored, ConstantMap) + assert restored.offset == 42 + + def test_constant_zero(self) -> None: + m = ConstantMap(offset=0) + json = m.to_json() + assert json == {"offset": 0} + restored = output_index_map_from_json(json) + assert isinstance(restored, ConstantMap) + assert restored.offset == 0 + + def test_dimension(self) -> None: + m = DimensionMap(input_dimension=1, offset=10, stride=3) + json = m.to_json() + assert json == {"offset": 10, "stride": 3, "input_dimension": 1} + restored = output_index_map_from_json(json) + assert isinstance(restored, DimensionMap) + assert restored.input_dimension == 1 + assert restored.offset == 10 + assert restored.stride == 3 + + def test_dimension_stride_1_written(self) -> None: + """Canonical form writes stride even at its default of 1.""" + m = DimensionMap(input_dimension=0) + json = m.to_json() + assert json == {"offset": 0, "stride": 1, "input_dimension": 0} + restored = output_index_map_from_json(json) + assert isinstance(restored, DimensionMap) + assert restored.stride == 1 + + def test_array(self) -> None: + arr = np.array([1, 5, 9], dtype=np.intp) + m = ArrayMap(index_array=arr, offset=2, stride=3) + json = m.to_json() + # Canonical: stride/offset present, index_array_bounds present, and + # no input_dimension (ndsel/TensorStore reject it beside index_array). + assert json == { + "offset": 2, + "stride": 3, + "index_array": [1, 5, 9], + "index_array_bounds": ["-inf", "+inf"], + } + restored = output_index_map_from_json(json) + assert isinstance(restored, ArrayMap) + np.testing.assert_array_equal(restored.index_array, arr) + assert restored.offset == 2 + assert restored.stride == 3 + + def test_array_stride_1_written(self) -> None: + arr = np.array([0, 1, 2], dtype=np.intp) + m = ArrayMap(index_array=arr) + json = m.to_json() + assert json["stride"] == 1 + restored = output_index_map_from_json(json) + assert isinstance(restored, ArrayMap) + assert restored.stride == 1 + + def test_array_2d(self) -> None: + arr = np.array([[1, 2], [3, 4]], dtype=np.intp) + m = ArrayMap(index_array=arr) + json = m.to_json() + assert json["index_array"] == [[1, 2], [3, 4]] + restored = output_index_map_from_json(json) + assert isinstance(restored, ArrayMap) + np.testing.assert_array_equal(restored.index_array, arr) + + def test_degenerate_singleton_array_collapses_to_constant(self) -> None: + """An all-singleton index_array selects one coordinate -> constant map.""" + m = ArrayMap(index_array=np.array([[4]], dtype=np.intp), offset=1, stride=2) + json = m.to_json() + assert json == {"offset": 1 + 2 * 4} + restored = output_index_map_from_json(json) + assert isinstance(restored, ConstantMap) + assert restored.offset == 9 + + +class TestIndexTransformJSON: + def test_identity(self) -> None: + t = IndexTransform.from_shape((10, 20)) + json = t.to_json() + assert json == { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [10, 20], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "input_dimension": 0}, + {"offset": 0, "stride": 1, "input_dimension": 1}, + ], + } + restored = IndexTransform.from_json(json) + assert restored.domain == t.domain + assert len(restored.output) == 2 + for orig, rest in zip(t.output, restored.output, strict=True): + assert type(orig) is type(rest) + + def test_sliced(self) -> None: + t = IndexTransform.from_shape((100,))[10:50:2] + json = t.to_json() + restored = IndexTransform.from_json(json) + assert restored.domain.shape == t.domain.shape + assert isinstance(restored.output[0], DimensionMap) + orig = t.output[0] + assert isinstance(orig, DimensionMap) + assert restored.output[0].offset == orig.offset + assert restored.output[0].stride == orig.stride + + def test_with_constant(self) -> None: + t = IndexTransform.from_shape((10, 20))[3] + json = t.to_json() + restored = IndexTransform.from_json(json) + assert isinstance(restored.output[0], ConstantMap) + assert restored.output[0].offset == 3 + assert isinstance(restored.output[1], DimensionMap) + + def test_with_array(self) -> None: + idx = np.array([1, 5, 9], dtype=np.intp) + t = IndexTransform.from_shape((10, 20)).oindex[idx, :] + json = t.to_json() + # The oindex array must not carry input_dimension on the wire. + assert "input_dimension" not in json["output"][0] + restored = IndexTransform.from_json(json) + assert isinstance(restored.output[0], ArrayMap) + # Orthogonal arrays are normalized to full input rank with a singleton + # axis on the dimension they do not vary over. + assert restored.output[0].index_array.shape == (3, 1) + np.testing.assert_array_equal(restored.output[0].index_array, idx.reshape(3, 1)) + assert isinstance(restored.output[1], DimensionMap) + + def test_roundtrip_preserves_singleton_axes(self) -> None: + """Full-rank orthogonal arrays keep their singleton axes across JSON.""" + t = IndexTransform.from_shape((10, 20)).oindex[np.array([1, 3]), np.array([2, 4, 6])] + restored = IndexTransform.from_json(t.to_json()) + orig0, orig1 = t.output[0], t.output[1] + rest0, rest1 = restored.output[0], restored.output[1] + assert isinstance(orig0, ArrayMap) + assert isinstance(orig1, ArrayMap) + assert isinstance(rest0, ArrayMap) + assert isinstance(rest1, ArrayMap) + assert rest0.index_array.shape == (2, 1) + assert rest1.index_array.shape == (1, 3) + np.testing.assert_array_equal(rest0.index_array, orig0.index_array) + np.testing.assert_array_equal(rest1.index_array, orig1.index_array) + + def test_with_labels(self) -> None: + domain = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 20), labels=("x", "y")) + t = IndexTransform.identity(domain) + json = t.to_json() + assert json["input_labels"] == ["x", "y"] + restored = IndexTransform.from_json(json) + assert restored.domain.labels == ("x", "y") + + def test_tensorstore_compatible_format(self) -> None: + """A canonical body loads and round-trips through the engine layer.""" + json: IndexTransformJSON = { + "input_rank": 3, + "input_inclusive_min": [0, 0, 0], + "input_exclusive_max": [100, 200, 3], + "input_labels": ["x", "y", "channel"], + "output": [ + {"offset": 5}, + {"offset": 10, "stride": 2, "input_dimension": 1}, + # Full input rank, which is what TensorStore itself requires: + # it rejects a rank-1 array over a rank-3 domain outright. + {"offset": 0, "stride": 1, "index_array": [[[1, 2, 0]]]}, + ], + } + t = IndexTransform.from_json(json) + assert t.domain.shape == (100, 200, 3) + assert t.domain.labels == ("x", "y", "channel") + assert isinstance(t.output[0], ConstantMap) + assert t.output[0].offset == 5 + assert isinstance(t.output[1], DimensionMap) + assert t.output[1].offset == 10 + assert t.output[1].stride == 2 + assert t.output[1].input_dimension == 1 + assert isinstance(t.output[2], ArrayMap) + np.testing.assert_array_equal(t.output[2].index_array, [[[1, 2, 0]]]) + + # Roundtrip + json_rt = t.to_json() + t_rt = IndexTransform.from_json(json_rt) + assert t_rt.domain == t.domain + + +class TestCanonicalRoundTrips: + """Round-trip `transform == from(to(transform))`, up to the documented + degenerate-collapse (all-singleton ArrayMap -> ConstantMap).""" + + def test_oindex_multi_axis(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)).oindex[np.array([1, 3]), :, np.array([2, 4, 6])] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_oindex_with_slice(self) -> None: + t = IndexTransform.from_shape((10, 20))[2:8].oindex[np.array([3, 5, 7]), :] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_vindex(self) -> None: + t = IndexTransform.from_shape((10, 20)).vindex[np.array([1, 3, 5]), np.array([2, 4, 6])] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_vindex_with_residual_slice(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)).vindex[np.array([1, 3]), np.array([2, 4]), :] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_length1_degenerate_oindex_collapses(self) -> None: + """A length-1 oindex selection is the ConstantMap it equals. + + The selection layer collapses it at construction; a hand-built + all-singleton ArrayMap still collapses on serialize, so the canonical + wire form is a `constant` map either way. + """ + t = IndexTransform.from_shape((10, 20)).oindex[np.array([7]), :] + m = t.output[0] + assert isinstance(m, ConstantMap) + assert m.offset == 7 + + hand_built = IndexTransform( + domain=t.domain, + output=(ArrayMap(index_array=np.array([[7]], dtype=np.intp)), t.output[1]), + ) + rt = IndexTransform.from_json(hand_built.to_json()) + rm = rt.output[0] + assert isinstance(rm, ConstantMap) + assert rm.offset == 7 + # The size-1 input dimension survives, unconsumed, in the domain. + assert rt.domain == t.domain + + def test_slices_and_constants(self) -> None: + t = IndexTransform.from_shape((10, 20, 30))[2:8:2, 5, :] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + +def _index_array_body(index_array: Any, rank: int = 1, extent: int = 2) -> IndexTransformJSON: + return { + "input_rank": rank, + "input_inclusive_min": [0] * rank, + "input_exclusive_max": [extent] * rank, + "input_labels": [""] * rank, + "output": [{"offset": 0, "stride": 1, "index_array": index_array}], + } + + +@pytest.mark.parametrize( + ("index_array", "detail"), + [ + ([0.9, 1.9], "float64"), + ([0, 1.5], "float64"), + ([True, False], "bool"), + (["a", "b"], "str"), + # Not lists at all, so they are turned away before their content is + # looked at: a bare string would be iterated into characters, and a bare + # integer would become a rank-0 array and then a length-1 map, so a + # document naming no cells would select one. + ("abc", "must be an array of integers"), + (5, "must be an array of integers"), + ([None, None], "object"), + ], + ids=["floats", "mixed", "bools", "strings", "string", "scalar", "nulls"], +) +def test_a_non_integer_index_array_is_rejected(index_array: Any, detail: str) -> None: + """An `index_array` addresses output coordinates, so it must be integral. + + Lowering a float array silently truncated it (`[0.9, 1.9]` selected cells 0 + and 1), a bool array coerced to 0/1, and a string array leaked a raw NumPy + `ValueError` from the middle of the conversion. + """ + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(_index_array_body(index_array)) + assert excinfo.value.reason == "invalid_json" + assert "index_array" in str(excinfo.value) + assert detail in str(excinfo.value) + + +def test_a_ragged_index_array_is_rejected() -> None: + """A nested list that is not rectangular is not an array at all.""" + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(_index_array_body([[0, 1], [2]])) + assert excinfo.value.reason == "invalid_json" + + +@pytest.mark.parametrize( + ("index_array", "rank", "extent"), + [([0, 1], 1, 2), ([[0], [1]], 2, 2), ([], 1, 0)], + ids=["1d", "2d", "empty"], +) +def test_an_integer_index_array_is_accepted(index_array: Any, rank: int, extent: int) -> None: + """Integers of any nesting still lower, including an empty selection. + + An empty array selects nothing, so the domain it is read over is empty too; + a domain with room for coordinates the array does not supply is rejected + (see `test_an_index_array_that_does_not_span_its_domain_is_rejected`). + """ + t = IndexTransform.from_json(_index_array_body(index_array, rank, extent)) + m = t.output[0] + assert isinstance(m, ArrayMap) + assert m.index_array.dtype == np.intp + + +def test_a_non_integer_index_array_is_rejected_by_the_map_loader() -> None: + """The single-map loader enforces the same constraint as the transform one.""" + with pytest.raises(NdselError) as excinfo: + output_index_map_from_json({"index_array": [0.5, 1.5]}) + assert excinfo.value.reason == "invalid_json" + + +def test_infinite_bound_rejected_on_lowering() -> None: + body: IndexTransformJSON = { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [["+inf"]], + "input_labels": [""], + "output": [{"offset": 0, "stride": 1, "input_dimension": 0}], + } + with pytest.raises(ValueError, match="infinite"): + IndexTransform.from_json(body) + + +def test_a_lower_rank_index_array_is_widened_on_the_way_in() -> None: + """External JSON may broadcast a lower-rank array; the engine never holds one. + + ndsel leaves index-array rank unvalidated, so a conformant producer may send + an array of lower rank. It is widened at the boundary, which keeps the + full-rank invariant true of every transform the engine builds. + """ + # A rank-1 array widens into the trailing axis, so it spans that axis's + # extent of four. + body: IndexTransformJSON = { + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 4], + "output": [{"index_array": [1, 2, 0, 2]}, {"input_dimension": 1}], + } + transform = IndexTransform.from_json(body) + array_map = transform.output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (1, 4) + assert array_map.index_array.ndim == transform.domain.ndim + + +def test_an_index_array_of_the_wrong_rank_is_rejected() -> None: + """Inside the engine, a rank that does not match the domain is a bug.""" + with pytest.raises(ValueError, match="index_array has 1 dims"): + IndexTransform( + domain=IndexDomain.from_shape((3, 4)), + output=(ArrayMap(index_array=np.array([1, 2, 0], dtype=np.intp)),), + ) + + +def test_an_index_array_that_does_not_span_its_domain_is_rejected() -> None: + """An array with entries for only part of an axis is not a smaller selection. + + Reading it that way is how a truncated index array turned into a partially + written result rather than an error. + """ + with pytest.raises(ValueError, match="neither 1 nor the domain's extent"): + IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=( + ArrayMap(index_array=np.zeros((3, 0), dtype=np.intp)), + DimensionMap(input_dimension=1), + ), + ) + + +def test_an_empty_index_array_collapses_to_a_constant() -> None: + """Selecting nothing must survive a trip through JSON. + + An empty index array names no cell, and can only be empty because an input + dimension is, so nothing is ever read through it. It is degenerate in + exactly the way a size-1 array is, and collapses the same way — which is + also what TensorStore emits for `t[ts.d[0][[]]]`. + + Emitting the array instead produced a document nothing could load: + `tolist()` renders every empty array as `[]` once the leading axis is the + zero-length one, so the rank went with it, and the loader put the dependency + back on a different axis by prepending singletons. + """ + for shape, selection in ( + ((5, 3), (np.array([], dtype=np.intp), slice(None))), + ((5, 5), (np.array([], dtype=np.intp), np.array([], dtype=np.intp))), + ): + transform = IndexTransform.from_shape(shape).oindex[selection] + body = transform.to_json() + + assert all("index_array" not in m for m in body["output"]) + reloaded = IndexTransform.from_json(body) + assert reloaded.domain == transform.domain + assert reloaded.to_json() == body + + +def test_an_empty_index_array_from_elsewhere_is_recovered_from_the_domain() -> None: + """A producer that does emit one is still readable when the domain settles it. + + This package never writes such a document, but ndsel does not forbid it, and + the domain names the axis unambiguously when exactly one dimension is empty. + """ + body: IndexTransformJSON = { + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 4], + "output": [{"index_array": []}, {"input_dimension": 1}], + } + array_map = IndexTransform.from_json(body).output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (0, 1) + + +def test_an_ambiguous_empty_index_array_is_rejected() -> None: + """Two zero-length dimensions leave nothing to recover the axis from.""" + body: IndexTransformJSON = { + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 0], + "output": [{"index_array": []}, {"input_dimension": 1}], + } + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(body) + assert excinfo.value.reason == "invalid_json" + assert "zero-length" in str(excinfo.value) + + +@pytest.mark.parametrize( + ("document", "reason", "detail"), + [ + ( + {"input_inclusive_min": [0.0], "input_exclusive_max": [3], "input_labels": [""]}, + "invalid_json", + "must be an integer", + ), + ( + {"input_inclusive_min": [0], "input_exclusive_max": ["3"], "input_labels": [""]}, + "invalid_json", + "must be an integer", + ), + ( + {"input_inclusive_min": [False], "input_exclusive_max": [True], "input_labels": [""]}, + "invalid_json", + "must be an integer", + ), + ( + {"input_inclusive_min": [0], "input_exclusive_max": [3], "input_labels": [5]}, + "invalid_json", + "must be a string", + ), + ( + {"input_inclusive_min": [0], "input_exclusive_max": [2**200], "input_labels": [""]}, + "invalid_json", + "64-bit signed range", + ), + ], + ids=["float", "string", "bool", "non-string-label", "out-of-range"], +) +def test_a_malformed_domain_document_is_rejected(document: Any, reason: str, detail: str) -> None: + """The domain loader validates what the message layer validates. + + Reading the keys directly was a second, undefended way into the same + objects: a bare `int()` truncated `3.9` to 3, coerced `"3"` and `True`, and + let a non-string label into a `tuple[str, ...]` — each building a domain + that was not the document's, and re-dumping as a different document. + """ + with pytest.raises(NdselError) as excinfo: + IndexDomain.from_json(document) + assert excinfo.value.reason == reason + assert detail in str(excinfo.value) + + +def test_a_transform_body_cannot_reinterpret_itself_as_another_message() -> None: + """A `kind` inside the body must not change which message is being read.""" + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json({"kind": "points", "coords": [[1, 2], [3, 4]]}) + assert excinfo.value.reason == "invalid_json" + assert "kind" in str(excinfo.value) + + +def test_an_engine_invariant_failure_leaves_the_loader_as_a_typed_error() -> None: + """A document is invalid input however deep the check that catches it lives. + + The engine's rank and span invariants are the last gate a document passes, + and they raised a bare `ValueError` written in the engine's vocabulary. + """ + body: IndexTransformJSON = { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [5], + "input_labels": [""], + "output": [{"index_array": [[1, 2], [3, 4]]}], + } + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(body) + assert excinfo.value.reason == "rank_mismatch" diff --git a/packages/zarr-indexing/tests/test_lazy_array.py b/packages/zarr-indexing/tests/test_lazy_array.py new file mode 100644 index 0000000000..ab94be1ae5 --- /dev/null +++ b/packages/zarr-indexing/tests/test_lazy_array.py @@ -0,0 +1,2618 @@ +"""Tests for `zarr_indexing.grid` grids and the `LazyArray` wrapper. + +The happy-path suite is a single oracle test: every selection case is applied +both to a `LazyArray` and to the NumPy array it wraps, and the results must +match. The case list is crossed with four source flavors — an unchunked NumPy +array, NumPy with each of the two declared chunk conventions, and a zarr array +whose chunking is auto-discovered — so the chunked and unchunked resolution +strategies are held to the same answers. +""" + +from __future__ import annotations + +import operator +import pickle +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import pytest + +import zarr_indexing.lazy_array as lazy_array_module +from zarr_indexing import ( + ArrayMap, + ChunkGrid, + ChunkProjection, + ConstantMap, + DimensionMap, + EdgeDimensionGrid, + FixedDimension, + IndexTransform, + LazyArray, + ReadContext, + VaryingDimension, + dimension_grids_from_chunks, +) +from zarr_indexing.lazy_array import _out_selection_cell_count, _validate_prepared_parts +from zarr_indexing.reader import Reader, basic_reader, numpy_reader +from zarr_indexing.testing import repartition + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + +SHAPE = (7, 5, 4) +PART_SHAPE = (3, 2, 3) +EXPLICIT_PARTS = ((3, 3, 1), (2, 2, 1), (3, 1)) + + +class IndexLike: + """A scalar integer selector implemented only through `__index__`.""" + + def __init__(self, value: int) -> None: + self.value = value + + def __index__(self) -> int: + return self.value + + +class IntOnly: + def __int__(self) -> int: + return 2 + + +class BadIndex: + """An `__index__` that lies: the protocol requires an integer.""" + + def __index__(self) -> int: + return cast("int", 2.5) + + +def reference() -> np.ndarray[Any, np.dtype[np.int64]]: + """The array every source flavor holds, and the oracle for every case.""" + return np.arange(int(np.prod(SHAPE)), dtype=np.int64).reshape(SHAPE) + + +class DelegatingReader: + def __init__(self, inner: Reader) -> None: + self.inner = inner + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + self.inner.read_into(source, context, out) + + +def outer(ref: np.ndarray[Any, Any], selections: Sequence[Any]) -> np.ndarray[Any, Any]: + """NumPy oracle for orthogonal indexing: the outer product of per-axis selections. + + Scalar integers are basic indices — NumPy applies them first and drops the + axis — so they are peeled off before the outer product is formed. + """ + scalars = tuple( + sel if isinstance(sel, (int, np.integer)) and not isinstance(sel, bool) else slice(None) + for sel in selections + ) + reduced = ref[scalars] + axes = [ + np.arange(size)[sel] + for size, sel in zip( + reduced.shape, + [ + s + for s in selections + if not (isinstance(s, (int, np.integer)) and not isinstance(s, bool)) + ], + strict=True, + ) + ] + if len(axes) == 0: + return reduced + return reduced[np.ix_(*axes)] + + +# --------------------------------------------------------------------------- +# EdgeDimensionGrid +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("sizes", "expected_index_to_chunk", "expected_offsets", "expected_sizes"), + [ + # A clipped edge chunk. + ((3, 3, 1), [0, 0, 0, 1, 1, 1, 2], [0, 3, 6], [3, 3, 1]), + # A single chunk covering the whole axis. + ((4,), [0, 0, 0, 0], [0], [4]), + # A size-1 axis. + ((1,), [0], [0], [1]), + # Irregular sizes: the grid does not have to be regular. + ((1, 2, 1), [0, 1, 1, 2], [0, 1, 3], [1, 2, 1]), + ], +) +def test_edge_dimension_grid( + sizes: tuple[int, ...], + expected_index_to_chunk: list[int], + expected_offsets: list[int], + expected_sizes: list[int], +) -> None: + """All four `DimensionGridLike` methods agree with hand-computed values.""" + grid = EdgeDimensionGrid(sizes) + extent = sum(sizes) + + assert grid.num_chunks == len(sizes) + assert grid.extent == extent + assert [grid.index_to_chunk(i) for i in range(extent)] == expected_index_to_chunk + assert [grid.chunk_offset(c) for c in range(len(sizes))] == expected_offsets + assert [grid.chunk_size(c) for c in range(len(sizes))] == expected_sizes + np.testing.assert_array_equal( + grid.indices_to_chunks(np.arange(extent, dtype=np.intp)), + np.asarray(expected_index_to_chunk, dtype=np.intp), + ) + + +def test_edge_dimension_grid_rejects_nonpositive_size() -> None: + with pytest.raises(ValueError, match="chunk sizes must be positive"): + EdgeDimensionGrid((3, 0, 2)) + + +def test_edge_dimension_grid_rejects_out_of_bounds_index() -> None: + with pytest.raises(IndexError, match="out of bounds for an axis of extent 4"): + EdgeDimensionGrid((3, 1)).index_to_chunk(4) + + +def test_edge_dimension_grid_rejects_out_of_bounds_chunk() -> None: + with pytest.raises(IndexError, match="chunk index 2 is out of bounds"): + EdgeDimensionGrid((3, 1)).chunk_offset(2) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_compact_dimension_grid_rejects_vector_below_extent(grid: Any) -> None: + with pytest.raises(IndexError, match=r"indices must lie in \[0, 4\); got \[-1, 1\]"): + grid.indices_to_chunks(np.array([-1, 1], dtype=np.intp)) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_compact_dimension_grid_rejects_vector_above_extent(grid: Any) -> None: + with pytest.raises(IndexError, match=r"indices must lie in \[0, 4\); got \[1, 4\]"): + grid.indices_to_chunks(np.array([1, 4], dtype=np.intp)) + + +def test_fixed_dimension_rejects_zero_size_for_nonempty_extent() -> None: + with pytest.raises(ValueError, match="size must be > 0 when extent is nonzero"): + FixedDimension(size=0, extent=4) + + +def test_fixed_dimension_retains_zero_size_for_zero_extent() -> None: + grid = FixedDimension(size=0, extent=0) + + assert grid.nchunks == 0 + assert grid.ngridcells == 0 + + +@pytest.mark.parametrize( + ("chunks", "shape", "expected"), + [ + # Uniform chunk shape, tail clipped. + ((3, 4), (7, 4), (FixedDimension(size=3, extent=7), FixedDimension(size=4, extent=4))), + # Dask-convention per-axis sizes, passed through. + ( + ((3, 3, 1), (2, 2)), + (7, 4), + (VaryingDimension(edges=(3, 3, 1), extent=7), VaryingDimension(edges=(2, 2), extent=4)), + ), + # A chunk longer than the axis collapses to one clipped chunk. + ((10,), (4,), (FixedDimension(size=10, extent=4),)), + # A zero-length axis has no chunks at all. + ((3,), (0,), (FixedDimension(size=3, extent=0),)), + ], +) +def test_dimension_grids_from_chunks( + chunks: Any, shape: tuple[int, ...], expected: tuple[Any, ...] +) -> None: + grids = dimension_grids_from_chunks(chunks, shape) + assert grids == expected + + +def test_regular_dimension_metadata_is_constant_in_chunk_count() -> None: + dimensions = dimension_grids_from_chunks((1,), (1_000_000,)) + + assert dimensions == (FixedDimension(size=1, extent=1_000_000),) + assert dimensions[0].nchunks == 1_000_000 + assert dimensions[0].index_to_chunk(999_999) == 999_999 + + +def test_chunk_grid_distinguishes_codec_and_data_shape_at_the_edge() -> None: + grid = ChunkGrid(dimensions=(FixedDimension(size=3, extent=7),)) + + edge = grid[(2,)] + + assert edge is not None + assert edge.slices == (slice(6, 7, 1),) + assert edge.shape == (1,) + assert edge.codec_shape == (3,) + + +def test_dimension_grids_reject_negative_shape() -> None: + with pytest.raises(ValueError, match="shape entries must be non-negative"): + dimension_grids_from_chunks((3,), (-1,)) + + +def test_dimension_grids_from_chunks_rejects_wrong_length() -> None: + with pytest.raises(ValueError, match="one entry per dimension"): + dimension_grids_from_chunks((3,), (7, 4)) + + +def test_dimension_grids_from_chunks_rejects_mixed_conventions() -> None: + with pytest.raises(ValueError, match="not a mixture"): + dimension_grids_from_chunks((3, (2, 2)), (7, 4)) + + +def test_dimension_grids_from_chunks_rejects_wrong_total() -> None: + with pytest.raises(ValueError, match="sum to 5, but the array extent is 7"): + dimension_grids_from_chunks(((3, 2), (4,)), (7, 4)) + + +def test_dimension_grids_from_chunks_rejects_non_sequence_entry() -> None: + """A float entry is neither convention, and says so instead of raising TypeError.""" + with pytest.raises(ValueError, match=r"3\.5 at dimension 0 is neither"): + dimension_grids_from_chunks((3.5, (4,)), (7, 4)) + + +def test_array_map_dependent_axis_reports_no_axis() -> None: + """A map varying over nothing answers None rather than a stale binding.""" + correlated = ArrayMap(index_array=np.array([[1], [2]], dtype=np.intp)) + assert correlated.dependent_axis == 0 + assert ArrayMap(index_array=np.array([[3]], dtype=np.intp)).dependent_axis is None + + +def test_scalar_on_a_fancy_axis_collapses_to_a_constant() -> None: + """The degenerate-collapse rule: an all-singleton ArrayMap becomes a ConstantMap. + + Without it the map keeps an `input_dimension` naming an axis the integer + index just removed, which after renumbering aliases a different axis. + """ + view = IndexTransform.from_shape((7, 5)).oindex[np.array([3, 1]), slice(None)][0] + assert view.output[0] == ConstantMap(offset=3) + assert isinstance(view.output[1], DimensionMap) + assert view.domain.shape == (5,) + + +# --------------------------------------------------------------------------- +# Sources +# --------------------------------------------------------------------------- + + +def make_zarr_source() -> Any: + """A zarr array holding `reference()`, whose parts are auto-discovered.""" + zarr = pytest.importorskip("zarr") + array = zarr.create_array({}, shape=SHAPE, chunks=PART_SHAPE, dtype="int64") + array[:] = reference() + return array + + +def make_source(flavor: str) -> LazyArray: + """Build a `LazyArray` over `reference()` with the requested partitioning.""" + data = reference() + if flavor == "numpy-whole": + return LazyArray(data) + if flavor == "numpy-explicit-parts": + return LazyArray(data).with_parts_per_axis(EXPLICIT_PARTS) + if flavor == "numpy-uniform-parts": + return LazyArray(data).with_parts(PART_SHAPE) + if flavor == "zarr": + return LazyArray(make_zarr_source()) + if flavor == "zarr-misaligned": + # Parts that deliberately straddle the zarr array's own chunks. + return LazyArray(make_zarr_source()).with_parts((4, 3, 3)) + raise TypeError(f"unknown source flavor {flavor!r}") + + +FLAVORS = [ + "numpy-whole", + "numpy-explicit-parts", + "numpy-uniform-parts", + "zarr", + "zarr-misaligned", +] + + +@pytest.fixture(params=FLAVORS) +def source(request: pytest.FixtureRequest) -> LazyArray: + return make_source(request.param) + + +# --------------------------------------------------------------------------- +# The oracle +# --------------------------------------------------------------------------- + +MASK = (reference() % 11) == 0 +# A mask over the two trailing axes, for the `vindex[..., mask]` idiom. +TRAILING_MASK = (reference()[0] % 3) == 0 + +# (id, lazy view builder, NumPy oracle). Integer scalars are deliberately absent +# from the orthogonal cases: the transform algebra keeps an int-selected axis as +# a length-1 axis under `oindex`, which `np.ix_` cannot express. +CASES: list[tuple[str, Callable[[LazyArray], LazyArray], Callable[[Any], Any]]] = [ + ( + "basic-strided-and-int-drop", + lambda a: a.lazy[1:6:2, :, -1], + lambda r: r[1:6:2, :, -1], + ), + ("basic-ellipsis", lambda a: a.lazy[..., -2], lambda r: r[..., -2]), + ("basic-negative-scalar", lambda a: a.lazy[-3], lambda r: r[-3]), + ("basic-newaxis", lambda a: a.lazy[None, :, :, None], lambda r: r[None, :, :, None]), + ("basic-empty", lambda a: a.lazy[:, 2:2, :], lambda r: r[:, 2:2, :]), + ("basic-all-scalars", lambda a: a.lazy[-1, 0, 2], lambda r: r[-1, 0, 2]), + ( + "oindex-unsorted-duplicates-multi-axis", + lambda a: a.lazy.oindex[[4, 0, 0, 2], :, [3, 1]], + lambda r: outer(r, ([4, 0, 0, 2], slice(None), [3, 1])), + ), + ( + "oindex-negative-and-slice", + lambda a: a.lazy.oindex[:, [-1, 0], 1:4], + lambda r: outer(r, (slice(None), [-1, 0], slice(1, 4))), + ), + ( + "oindex-boolean-axis", + lambda a: a.lazy.oindex[np.array([True, False, True, False, False, False, True]), :, :], + lambda r: outer( + r, + (np.array([True, False, True, False, False, False, True]), slice(None), slice(None)), + ), + ), + ( + "vindex-coordinates", + lambda a: a.lazy.vindex[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])], + lambda r: r[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])], + ), + ( + "vindex-broadcast-pair", + lambda a: a.lazy.vindex[np.array([[0], [6]]), np.array([1, 4]), np.array([2, 0])], + lambda r: r[np.array([[0], [6]]), np.array([1, 4]), np.array([2, 0])], + ), + ( + "vindex-negative-coordinates", + lambda a: a.lazy.vindex[np.array([-1, -7]), np.array([-2, 0]), np.array([0, -1])], + lambda r: r[np.array([-1, -7]), np.array([-2, 0]), np.array([0, -1])], + ), + ("vindex-mask", lambda a: a.lazy.vindex[MASK], lambda r: r[MASK]), + ( + "compose-basic-then-oindex", + lambda a: a.lazy[1:6].lazy.oindex[[3, 0, 0], [4, 1], :], + lambda r: outer(r[1:6], ([3, 0, 0], [4, 1], slice(None))), + ), + ( + "compose-oindex-then-basic-other-axis", + lambda a: a.lazy.oindex[[4, 0, 2], :, :].lazy[:, 1:4, ::2], + lambda r: outer(r, ([4, 0, 2], slice(None), slice(None)))[:, 1:4, ::2], + ), + ( + "compose-basic-then-basic", + lambda a: a.lazy[2:, 1:].lazy[::2, -1], + lambda r: r[2:, 1:][::2, -1], + ), + ( + "compose-basic-then-vindex", + lambda a: a.lazy[1:6, :, 1:].lazy.vindex[ + np.array([0, 4]), np.array([2, 0]), np.array([1, 2]) + ], + lambda r: r[1:6, :, 1:][np.array([0, 4]), np.array([2, 0]), np.array([1, 2])], + ), + # Scalar integers are basic indices in the positional dialect: they drop the + # axis, in every mode, exactly as NumPy does. + ("oindex-scalar-drops-axis", lambda a: a.lazy.oindex[0], lambda r: r[0]), + ( + "oindex-scalar-with-arrays", + lambda a: a.lazy.oindex[0, [1, 2], :], + lambda r: outer(r, (0, [1, 2], slice(None))), + ), + ( + "oindex-scalar-middle-axis", + lambda a: a.lazy.oindex[[3, 1], -1, :], + lambda r: outer(r, ([3, 1], -1, slice(None))), + ), + ("oindex-all-scalars", lambda a: a.lazy.oindex[0, 1, 2], lambda r: r[0, 1, 2]), + ("vindex-all-scalars", lambda a: a.lazy.vindex[0, 1, 2], lambda r: r[0, 1, 2]), + ( + "vindex-scalar-with-arrays", + lambda a: a.lazy.vindex[0, [1, 2], [3, 0]], + lambda r: r[0, [1, 2], [3, 0]], + ), + ( + "vindex-scalar-on-middle-axis", + lambda a: a.lazy.vindex[[1, 2], 0, [3, 0]], + lambda r: r[[1, 2], 0, [3, 0]], + ), + # Scalar applied to a previously fancy-indexed axis, both orders. + ( + "compose-oindex-then-scalar", + lambda a: a.lazy.oindex[[3, 1], :, :].lazy[0], + lambda r: outer(r, ([3, 1], slice(None), slice(None)))[0], + ), + ( + "compose-oindex-then-scalar-negative", + lambda a: a.lazy.oindex[[3, 1, 1], :, :].lazy[-1, 2], + lambda r: outer(r, ([3, 1, 1], slice(None), slice(None)))[-1, 2], + ), + ( + "compose-scalar-then-oindex", + lambda a: a.lazy[0].lazy.oindex[[3, 1], :], + lambda r: outer(r[0], ([3, 1], slice(None))), + ), + ( + "compose-vindex-then-scalar", + lambda a: a.lazy.vindex[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])].lazy[ + 1 + ], + lambda r: r[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])][1], + ), + # Partial vindex whose coordinate arrays are NOT on the leading axes: NumPy + # inserts the gathered axis where the (adjacent) advanced indices sat. + ( + "vindex-trailing-arrays", + lambda a: a.lazy.vindex[..., np.array([1, 4, 0]), np.array([2, 0, 1])], + lambda r: r[..., np.array([1, 4, 0]), np.array([2, 0, 1])], + ), + ( + "vindex-single-trailing-array", + lambda a: a.lazy.vindex[..., np.array([3, 0, 1])], + lambda r: r[..., np.array([3, 0, 1])], + ), + ( + "vindex-trailing-mask", + lambda a: a.lazy.vindex[..., TRAILING_MASK], + lambda r: r[..., TRAILING_MASK], + ), + ( + "vindex-leading-partial", + lambda a: a.lazy.vindex[np.array([1, 2, 2])], + lambda r: r[np.array([1, 2, 2])], + ), + ( + "compose-basic-then-vindex-trailing", + lambda a: a.lazy[2:, 1:].lazy.vindex[..., np.array([1, 3, 0])], + lambda r: r[2:, 1:][..., np.array([1, 3, 0])], + ), + # A ConstantMap sitting between a slice and the coordinate arrays: NumPy + # counts the integer as an advanced index, so the gathered axis moves to the + # front of the chunk block even though the arrays are trailing. + ( + "compose-vindex-trailing-then-scalar", + lambda a: a.lazy.vindex[..., np.array([3, 0])].lazy[2], + lambda r: r[..., np.array([3, 0])][2], + ), + # Two fancy axes, then a scalar on the first: the surviving ArrayMap ends up + # behind a ConstantMap and a slice, which is where NumPy's integer-counts-as- + # advanced rule bites. + ( + "compose-oindex-two-axes-then-scalar", + lambda a: a.lazy.oindex[[3, 1, 0], 3:5, [2, 0, 2]].lazy[0], + lambda r: outer(r, ([3, 1, 0], slice(3, 5), [2, 0, 2]))[0], + ), + # Negative steps: the positional dialect is NumPy's, including the empty + # cases NumPy allows where the transform algebra alone would object. + ("reverse", lambda a: a.lazy[::-1], lambda r: r[::-1]), + ("reverse-every-axis", lambda a: a.lazy[::-1, ::-1, ::-1], lambda r: r[::-1, ::-1, ::-1]), + ("reverse-strided", lambda a: a.lazy[::-2], lambda r: r[::-2]), + ("reverse-nondivisible", lambda a: a.lazy[::-3], lambda r: r[::-3]), + ("reverse-bounded", lambda a: a.lazy[5:1:-1], lambda r: r[5:1:-1]), + ("reverse-negative-start", lambda a: a.lazy[-1:None:-1], lambda r: r[-1:None:-1]), + ("reverse-past-the-start", lambda a: a.lazy[:-8:-1], lambda r: r[:-8:-1]), + ("reverse-empty", lambda a: a.lazy[2:2:-1], lambda r: r[2:2:-1]), + # NumPy reads a reversed *positional* interval as empty; only the literal + # layer calls it a direction error. + ("reverse-inverted-is-empty", lambda a: a.lazy[2:5:-1], lambda r: r[2:5:-1]), + ("reverse-with-int-drop", lambda a: a.lazy[::-2, 2, ::-1], lambda r: r[::-2, 2, ::-1]), + ("reverse-trailing-axis", lambda a: a.lazy[..., ::-1], lambda r: r[..., ::-1]), + ( + "compose-reverse-then-reverse", + lambda a: a.lazy[::-1].lazy[::-1], + lambda r: r[::-1][::-1], + ), + ( + "compose-strided-then-reverse", + lambda a: a.lazy[::2].lazy[::-1], + lambda r: r[::2][::-1], + ), + ( + "compose-reverse-then-strided", + lambda a: a.lazy[::-1].lazy[::2], + lambda r: r[::-1][::2], + ), + ( + "compose-reverse-then-oindex", + lambda a: a.lazy[::-1].lazy.oindex[[3, 0, 0], :, :], + lambda r: outer(r[::-1], ([3, 0, 0], slice(None), slice(None))), + ), + ( + "compose-oindex-then-reverse", + lambda a: a.lazy.oindex[[3, 1, 2], :, :].lazy[::-1], + lambda r: outer(r, ([3, 1, 2], slice(None), slice(None)))[::-1], + ), + ( + "compose-reverse-then-vindex", + lambda a: a.lazy[::-1].lazy.vindex[..., np.array([1, 3, 0])], + lambda r: r[::-1][..., np.array([1, 3, 0])], + ), + ( + "compose-vindex-trailing-then-scalar-and-slice", + lambda a: a.lazy.vindex[..., np.array([3, 0, 1])].lazy[-1, 1:4], + lambda r: r[..., np.array([3, 0, 1])][-1, 1:4], + ), + # A downward walk that begins off the front of the axis selects nothing. + # Written against an oindex axis and a vindex axis, where the selection is + # carried by an index array rather than by the domain. + ( + "compose-oindex-then-empty-downward-walk", + lambda a: a.lazy.oindex[np.array([3, 1, 4]), :, :].lazy[-8::-1], + lambda r: r[np.array([3, 1, 4])][-8::-1], + ), + ( + "compose-vindex-then-empty-downward-walk", + lambda a: a.lazy.vindex[np.array([3, 1]), np.array([2, 0])].lazy[-9::-2], + lambda r: r[np.array([3, 1]), np.array([2, 0])][-9::-2], + ), + ( + "empty-downward-walk-on-a-plain-axis", + lambda a: a.lazy[-11::-1], + lambda r: r[-11::-1], + ), + # A fancy *spelling* whose entries are all slices is not a fancy selection: + # it narrows the view's own axes and must compose exactly like basic + # indexing. The slices start past 0, so a step that applied them to the + # broadcast (singleton) axes of the existing index array would truncate it. + ( + "compose-oindex-then-oindex-slices-only", + lambda a: a.lazy.oindex[[4, 0, 0], :, :].lazy.oindex[:, 2:5, 1:], + lambda r: outer(r, ([4, 0, 0], slice(None), slice(None)))[:, 2:5, 1:], + ), + ( + "compose-oindex-then-oindex-slices-only-strided", + lambda a: a.lazy.oindex[:, [3, 1, 1], :].lazy.oindex[1::2, :, ::-1], + lambda r: outer(r, (slice(None), [3, 1, 1], slice(None)))[1::2, :, ::-1], + ), + ( + "compose-vindex-then-oindex-slices-only", + lambda a: a.lazy.vindex[np.array([4, 0, 2]), np.array([1, 3, 0])].lazy.oindex[1:, 2:], + lambda r: r[np.array([4, 0, 2]), np.array([1, 3, 0])][1:, 2:], + ), + ( + "compose-oindex-then-oindex-array-on-its-own-axis", + lambda a: a.lazy.oindex[[4, 0, 0], :, :].lazy.oindex[[2, 0], 3:, :], + lambda r: outer( + outer(r, ([4, 0, 0], slice(None), slice(None))), + ([2, 0], slice(3, None), slice(None)), + ), + ), +] + + +@pytest.mark.parametrize(("build", "oracle"), [c[1:] for c in CASES], ids=[c[0] for c in CASES]) +def test_selection_matches_numpy( + source: LazyArray, + build: Callable[[LazyArray], LazyArray], + oracle: Callable[[Any], Any], +) -> None: + """Every selection resolves to what NumPy computes positionally on the same data.""" + view = build(source) + expected = np.asarray(oracle(reference())) + + assert view.shape == expected.shape + assert view.ndim == expected.ndim + np.testing.assert_array_equal(np.asarray(view.result()), expected) + # `__getitem__` is eager, and `__array__` routes through `result()`. + np.testing.assert_array_equal(np.asarray(view), expected) + + +# --------------------------------------------------------------------------- +# Randomized chain sweep +# --------------------------------------------------------------------------- + + +def _random_basic(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + selection: list[Any] = [] + for size in shape: + roll = rng.random() + if roll < 0.3: + selection.append(int(rng.integers(-size, size))) + elif roll < 0.55: + start = int(rng.integers(0, size)) + stop = int(rng.integers(start, size + 1)) + selection.append(slice(start, stop, int(rng.integers(1, 4)))) + elif roll < 0.8: + # Downward: `start >= stop` and the stop may fall off the front, + # which is spelled `None`. The start is drawn from below `-size` as + # well, where the walk begins off the front and selects nothing — + # a case that reads as an ordinary negative index but is empty. + start = int(rng.integers(-2 * size - 1, size)) if size else 0 + stop_choice = int(rng.integers(-1, max(start, 0) + 1)) + stop = None if stop_choice < 0 else stop_choice + selection.append(slice(start, stop, -int(rng.integers(1, 4)))) + else: + selection.append(slice(None)) + return tuple(selection) + + +def _random_oindex(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + selection: list[Any] = [] + for size in shape: + roll = rng.random() + if roll < 0.25: + selection.append(int(rng.integers(-size, size))) + elif roll < 0.65: + count = int(rng.integers(1, 5)) + selection.append(rng.integers(-size, size, size=count).tolist()) + elif roll < 0.8: + mask = rng.random(size) < 0.5 + mask[int(rng.integers(0, size))] = True + selection.append(mask) + else: + start = int(rng.integers(0, size)) + selection.append(slice(start, size)) + return tuple(selection) + + +def _broadcast_singleton_axes( + rng: np.random.Generator, entries: list[Any], length: int +) -> list[Any]: + """Reshape 1-D coordinate arrays so the selection carries singleton axes. + + A coordinate array of shape `(1, n)` or `(n, 1)` contributes a broadcast axis + it does not vary over. That axis stays in the view's domain, and a later + basic index that consumes its partner leaves it referenced by no output map + at all — the shape that makes a broadcast axis and a genuine extent-1 axis + indistinguishable from the index array alone. + """ + rank = int(rng.integers(2, 4)) + reshaped: list[Any] = [] + for entry in entries: + if not isinstance(entry, np.ndarray): + reshaped.append(entry) + continue + varying = int(rng.integers(0, rank)) + reshaped.append( + entry.reshape(tuple(length if axis == varying else 1 for axis in range(rank))) + ) + return reshaped + + +def _random_vindex(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + ndim = len(shape) + count = int(rng.integers(1, ndim + 1)) + trailing = bool(rng.random() < 0.5) + axes = range(ndim - count, ndim) if trailing else range(count) + sizes = [shape[axis] for axis in axes] + + entries: list[Any] + if rng.random() < 0.2: + # A single boolean mask spanning the whole covered block. + mask = rng.random(tuple(sizes)) < 0.5 + mask.flat[int(rng.integers(0, mask.size))] = True + entries = [mask] + else: + length = int(rng.integers(1, 5)) + entries = [ + int(rng.integers(-size, size)) + if rng.random() < 0.25 + else rng.integers(-size, size, size=length) + for size in sizes + ] + if rng.random() < 0.35: + entries = _broadcast_singleton_axes(rng, entries, length) + return (Ellipsis, *entries) if trailing else tuple(entries) + + +def _apply_oracle( + ref: np.ndarray[Any, Any], mode: str, selection: tuple[Any, ...] +) -> np.ndarray[Any, Any]: + if mode == "orthogonal": + return outer(ref, selection) + # NumPy's own semantics *are* basic and vectorized indexing. + return ref[selection] + + +def _apply_view(view: LazyArray, mode: str, selection: tuple[Any, ...]) -> LazyArray: + if mode == "basic": + return view.lazy[selection] + if mode == "orthogonal": + return view.lazy.oindex[selection] + return view.lazy.vindex[selection] + + +def _random_slices_only(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + """A selection of slices alone, spelled through `oindex`. + + `oindex` entries that are all slices are not a fancy selection — they narrow + the view's own axes and must compose like basic indexing. A start past 0 is + what distinguishes a step that walks the index array's dependency axes from + one that walks its broadcast singletons, so slices are drawn to reach past + the origin. (`vindex` is coordinate-only and rejects a slice outright, so + this spelling has no vectorized counterpart.) + """ + selection: list[Any] = [] + for size in shape: + roll = rng.random() + if roll < 0.4: + start = int(rng.integers(0, size)) if size else 0 + selection.append(slice(start, size)) + elif roll < 0.7: + start = int(rng.integers(0, size)) if size else 0 + selection.append(slice(start, size, int(rng.integers(1, 3)))) + elif roll < 0.85: + selection.append(slice(None, None, -1)) + else: + selection.append(slice(None)) + return tuple(selection) + + +def _random_chain(rng: np.random.Generator) -> list[tuple[str, tuple[Any, ...]]]: + """A chain of 2-4 steps, any of which may be fancy. + + A step spelled through `oindex` but carrying only slices is drawn separately + (`slices-only`): it narrows an existing index array by a *slice* rather than + by coordinates, a distinct code path kept at full weight. + """ + n_steps = int(rng.integers(2, 5)) + fancy_steps = {int(rng.integers(0, n_steps)) for _ in range(2)} + slices_only_at = int(rng.integers(0, n_steps)) if rng.random() < 0.4 else -1 + + chain: list[tuple[str, tuple[Any, ...]]] = [] + running = reference() + for step in range(n_steps): + if running.ndim == 0 or running.size == 0: + break + if step in fancy_steps: + mode = "orthogonal" if rng.random() < 0.5 else "vectorized" + else: + mode = "basic" + if step == slices_only_at and step not in fancy_steps: + mode = "orthogonal" + selection = _random_slices_only(rng, running.shape) + elif mode == "basic": + selection = _random_basic(rng, running.shape) + elif mode == "orthogonal": + selection = _random_oindex(rng, running.shape) + else: + selection = _random_vindex(rng, running.shape) + chain.append((mode, selection)) + running = _apply_oracle(running, mode, selection) + return chain + + +@pytest.mark.parametrize("flavor", FLAVORS) +def test_random_chains_match_numpy(flavor: str) -> None: + """A seeded sweep of composed chains, under every partitioning. + + The partitioning invariant as a property: `result()` is identical whatever + boxes the read is broken into, including boxes deliberately misaligned with + the source's own. + """ + rng = np.random.default_rng(20260730) + source = make_source(flavor) + partitionings: list[Any] = [None, (2, 2, 2), (7, 5, 4), ((4, 3), (1, 3, 1), (3, 1))] + # Reads against a real store cost more per chain; the NumPy flavors carry + # the bulk of the sweep and exercise the identical code path. + n_chains = 120 if flavor.startswith("zarr") else 400 + + for _ in range(n_chains): + chain = _random_chain(rng) + expected = reference() + for mode, selection in chain: + expected = _apply_oracle(expected, mode, selection) + + view = source + for mode, selection in chain: + view = _apply_view(view, mode, selection) + + assert view.shape == expected.shape, f"{flavor}: {chain}" + np.testing.assert_array_equal( + np.asarray(view.result()), np.asarray(expected), err_msg=f"{flavor}: {chain}" + ) + for parts in partitionings: + np.testing.assert_array_equal( + np.asarray(repartition(view, parts).result()), + np.asarray(expected), + err_msg=f"{flavor} parts={parts}: {chain}", + ) + + +# `result()` can absorb a defect that `parts()` cannot — an empty view assembles +# correctly from no parts at all, and a rank-0 one can be reshaped into place — +# so the iteration contract needs its own sweep, asserting the documented +# assembly literally rather than through `result()`. That sweep is the +# `ChainedIndexing` state machine in `test_lazy_array_stateful.py`, which drives +# the same operations and shrinks a failure to the chain that caused it. + + +PARTITIONINGS_1D: list[Any] = [None, (1,), (2,), (5,)] + + +def test_a_slice_only_fancy_step_after_a_fancy_step_reads_real_data() -> None: + """`oindex[:, 2:8]` after an `oindex` narrows the view, it does not re-index it. + + The second step carries no coordinates, so it is not fancy-after-fancy: it + must compose like basic indexing. Applying its slices to the *broadcast* + axes of the first step's index array instead truncates that array to size 0, + which leaves the resolver with no parts to read and `result()` handing back + an unwritten buffer. + """ + base = np.arange(24).reshape(3, 8) + expected = base[np.ix_([0, 2], range(8))][:, 2:8] + + for parts in (None, (2, 4), (1, 8), (3, 3)): + view = ( + repartition(LazyArray(base), parts).lazy.oindex[np.array([0, 2]), :].lazy.oindex[:, 2:8] + ) + assert view.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=f"{parts}") + + +def test_a_fancy_step_composes_onto_any_axis_of_a_fancy_view() -> None: + """A second fancy step may land on axes the first one merely broadcasts along. + + Composition evaluates the existing index arrays at the new coordinates, so + `oindex` after `oindex`, `vindex` after `oindex`, and both orders around a + correlated gather all resolve — under every partitioning. + """ + base = np.arange(24).reshape(3, 8) + rows, cols = np.array([0, 2]), np.array([1, 3, 3]) + + for parts in (None, (2, 4), (1, 8), (3, 3)): + view = repartition(LazyArray(base), parts).lazy.oindex[rows, :] + + composed = view.lazy.oindex[:, cols] + expected = base[np.ix_(rows, cols)] + assert composed.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(composed.result()), expected, err_msg=f"{parts}") + + gathered = view.lazy.vindex[np.array([0, 1]), np.array([7, 0])] + np.testing.assert_array_equal( + np.asarray(gathered.result()), + base[np.ix_(rows, range(8))][[0, 1], [7, 0]], + err_msg=f"{parts}", + ) + + pointwise = repartition(LazyArray(base), parts).lazy.vindex[[0, 1, 2], [0, 2, 3]] + np.testing.assert_array_equal( + np.asarray(pointwise.lazy.oindex[[2, 0]].result()), + base[[0, 1, 2], [0, 2, 3]][[2, 0]], + err_msg=f"{parts}", + ) + np.testing.assert_array_equal( + np.asarray(pointwise.lazy.vindex[[1, 1, 0]].result()), + base[[0, 1, 2], [0, 2, 3]][[1, 1, 0]], + err_msg=f"{parts}", + ) + + +def test_a_partial_vindex_after_an_oindex_resolves_the_mixed_transform() -> None: + """A composed transform can mix correlated and orthogonal index arrays. + + `oindex` on the last axis then `vindex` on the first two leaves the + orthogonal gather in place while the new coordinate arrays are correlated; + resolution takes the pointwise path. + """ + base = np.arange(60).reshape(3, 4, 5) + expected = base[:, :, [4, 0]][[0, 2], [1, 3]] + + for parts in (None, (2, 2, 2), (3, 4, 5), (1, 1, 1)): + view = repartition(LazyArray(base), parts).lazy.oindex[:, :, [4, 0]] + composed = view.lazy.vindex[np.array([0, 2]), np.array([1, 3])] + assert composed.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(composed.result()), expected, err_msg=f"{parts}") + + +def test_a_boolean_mask_composes_onto_a_fancy_view() -> None: + base = np.arange(60).reshape(3, 4, 5) + mask = np.array([True, False, True]) + expected = base[[0, 1, 2]][mask] + + for parts in (None, (2, 2, 2), (1, 4, 5)): + view = repartition(LazyArray(base), parts).lazy.oindex[[0, 1, 2], :, :] + np.testing.assert_array_equal( + np.asarray(view.lazy.oindex[mask].result()), expected, err_msg=f"{parts}" + ) + + +def test_an_ellipsis_only_vindex_step_preserves_a_correlated_gather() -> None: + """Regression: a slice-only vindex step misread correlated maps as orthogonal. + + `vindex[...]` (and `vindex[..., scalar]`, whose remainder after the scalar + is split off is ellipsis-only) used to stamp each correlated map with its + block axis as an orthogonal binding. Two "orthogonal" maps then shared one + input axis, and the partition walk rejected its own transform mid-read. + """ + base = np.arange(16).reshape(4, 4) + + for parts in (None, (2, 2), (4, 4), (1, 3)): + pointwise = repartition(LazyArray(base), parts).lazy.vindex[[0, 1, 2], [0, 2, 3]] + np.testing.assert_array_equal( + np.asarray(pointwise.lazy.vindex[...].result()), + base[[0, 1, 2], [0, 2, 3]], + err_msg=f"{parts}", + ) + + planar = repartition(LazyArray(base), parts).lazy.vindex[ + np.array([[0], [1]]), np.array([[1], [3]]) + ] + np.testing.assert_array_equal( + np.asarray(planar.lazy.vindex[..., np.array(0)].result()), + base[[0, 1], [1, 3]], + err_msg=f"{parts}", + ) + + +# --------------------------------------------------------------------------- +# Domain dimensions no output map depends on +# --------------------------------------------------------------------------- +# +# A `vindex` coordinate array with a *singleton* broadcast axis leaves that axis +# in the view's domain while the map varies only over its partner. A later basic +# index that consumes the partner collapses the map to a `ConstantMap`, and the +# singleton axis survives with nothing referencing it. Every stage of resolution +# has to keep counting it: the lowered block needs the axis back at its true +# extent, and a part has to say where its values belong along it. + +UNREFERENCED_AXIS_PARTITIONINGS: list[Any] = [None, (1, 1, 1), (2, 2, 2), (3, 4, 5), (3, 1, 2)] + +# (id, view builder, NumPy oracle) over `np.arange(60).reshape(3, 4, 5)`. +UNREFERENCED_AXIS_CASES: list[ + tuple[str, Callable[[LazyArray], LazyArray], Callable[[Any], Any]] +] = [ + ( + "leading-singleton-row", + lambda a: a.lazy.vindex[np.array([[2, 0]])].lazy[:, 0], + lambda r: r[np.array([[2, 0]])][:, 0], + ), + ( + "trailing-singleton-column", + lambda a: a.lazy.vindex[np.array([[2], [0]])].lazy[0], + lambda r: r[np.array([[2], [0]])][0], + ), + ( + "repeated-coordinates-over-a-singleton", + lambda a: a.lazy.vindex[np.array([[1, 1]]), np.array([[3, 3]])].lazy[:, 0], + lambda r: r[np.array([[1, 1]]), np.array([[3, 3]])][:, 0], + ), + ( + "unreferenced-axis-emptied", + lambda a: a.lazy.vindex[np.array([[2, 0]])].lazy[0:0, 0], + lambda r: r[np.array([[2, 0]])][0:0, 0], + ), + ( + "partial-vindex-with-a-residual-slice", + lambda a: a.lazy.vindex[np.array([[2, 0]]), np.array([[1, 3]])].lazy[:, 0, 1:4], + lambda r: r[np.array([[2, 0]]), np.array([[1, 3]])][:, 0, 1:4], + ), +] + + +def unreferenced_axis_reference() -> np.ndarray[Any, np.dtype[np.int64]]: + return np.arange(60, dtype=np.int64).reshape(3, 4, 5) + + +@pytest.mark.parametrize( + ("build", "oracle"), + [case[1:] for case in UNREFERENCED_AXIS_CASES], + ids=[case[0] for case in UNREFERENCED_AXIS_CASES], +) +@pytest.mark.parametrize("parts", UNREFERENCED_AXIS_PARTITIONINGS) +def test_a_domain_axis_no_output_map_depends_on_still_resolves( + build: Callable[[LazyArray], LazyArray], + oracle: Callable[[Any], Any], + parts: Any, +) -> None: + """The value, the shape and the tiling all hold when an axis is unreferenced.""" + data = unreferenced_axis_reference() + expected = np.asarray(oracle(data)) + view = build(repartition(LazyArray(data), parts)) + + assert view.shape == expected.shape + np.testing.assert_array_equal(np.asarray(view.result()), expected) + + hits = np.zeros(view.shape, dtype=np.int64) + assembled = np.zeros(view.shape, dtype=view.dtype) + for part in view.parts(): + assembled[part.out_selection] = np.asarray(part.view.result()) + np.add.at(hits, part.out_selection, 1) + np.testing.assert_array_equal(assembled, expected) + np.testing.assert_array_equal(hits, np.ones(view.shape, dtype=np.int64)) + + +def test_an_unreferenced_domain_axis_of_extent_zero_stays_empty() -> None: + """An emptied broadcast axis must not be restored as a fabricated row. + + The lowered block has no axis for a dimension nothing depends on, so the + resolver puts one back. Putting it back at extent 1 invents a row of data + for a selection whose own `shape` says it is empty. + """ + data = np.arange(140, dtype=np.int64).reshape(7, 5, 4) + coords = np.array([[6], [3], [0]]) + for parts in (None, (1, 1, 1), (3, 2, 3), (7, 5, 4)): + view = repartition(LazyArray(data), parts).lazy.vindex[coords, -4].lazy[0, 0:0] + expected = data[coords, -4][0, 0:0] + assert view.shape == expected.shape == (0, 4), f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=f"{parts}") + assert list(view.parts()) == [] + + +def test_a_zero_length_axis_resolves_the_same_way_under_every_partitioning() -> None: + """A size-0 axis carries no dependency, so it cannot make a map correlated.""" + base = np.zeros((3, 0)) + expected = base[np.ix_([1, 0, 0], np.arange(0, dtype=int))] + + for parts in (None, ((1, 1, 1), ()), ((3,), ())): + view = ( + repartition(LazyArray(base), parts) + .lazy.oindex[np.array([1, -3, -3]), :] + .lazy.oindex[:, :] + ) + assert view.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=f"{parts}") + assert list(view.parts()) == [] + + +def test_an_empty_slice_of_a_length_one_correlated_axis_has_no_parts() -> None: + """`parts()` agrees with `result()` that an emptied view selects nothing. + + A correlated selection of exactly one point normalizes to an all-singleton + index array, indistinguishable by shape from an axis the map broadcasts + over — so a later slice that empties the domain leaves the array at size 1. + """ + base = np.arange(5) + mask = np.array([False, True, False, False, False]) + + for parts in PARTITIONINGS_1D: + view = repartition(LazyArray(base), parts).lazy.vindex[mask].lazy[1:-2] + assert view.shape == (0,), f"parts={parts}" + assert list(view.parts()) == [], f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), base[mask][1:-2]) + + +def test_an_empty_slice_of_a_length_one_vindex_pair_has_no_parts() -> None: + """The same emptied view, spelled with explicit coordinates over two axes.""" + base = np.arange(35).reshape(7, 5) + + for parts in (None, (2, 2), (7, 5)): + view = ( + repartition(LazyArray(base), parts).lazy.vindex[np.array([6]), np.array([0])].lazy[0:0] + ) + assert view.shape == (0,), f"parts={parts}" + assert list(view.parts()) == [], f"parts={parts}" + np.testing.assert_array_equal( + np.asarray(view.result()), base[np.array([6]), np.array([0])][0:0] + ) + + +def test_a_correlated_view_narrowed_to_one_point_has_parts_of_the_views_rank() -> None: + """A rank-0 broadcast block survives intersection without gaining an axis. + + `Partition` documents `out[part.out_selection] = part.view.result()` as the + assembly, so a part's values must arrive at the rank the view has — including + the rank 0 a correlated selection reaches once every coordinate is a scalar. + """ + base = np.arange(140).reshape(7, 5, 4) + cases = [ + # No residual slice: the whole view is the one gathered point. + ((np.array([-1]), np.array([-1]), np.array([2])), 0), + # One residual slice dimension survives alongside the collapsed block. + ((np.array([6, 1]), np.array([4, 0])), 1), + ] + + for parts in (None, (2, 2, 2), (3, 3, 3), (7, 5, 4)): + for selection, tail in cases: + expected = base[selection][tail] + view = repartition(LazyArray(base), parts).lazy.vindex[selection].lazy[tail] + assert view.shape == expected.shape, f"parts={parts}, {selection}" + + assembled = np.zeros(view.shape, dtype=view.dtype) + hits = np.zeros(view.shape, dtype=np.int64) + for part in view.parts(): + assembled[part.out_selection] = np.asarray(part.view.result()) + np.add.at(hits, part.out_selection, 1) + + err = f"parts={parts}, {selection}" + np.testing.assert_array_equal(assembled, expected, err_msg=err) + np.testing.assert_array_equal(hits, np.ones(view.shape, dtype=np.int64), err_msg=err) + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=err) + + +def test_eager_getitem_returns_data(source: LazyArray) -> None: + """`arr[...]` reads immediately, like `numpy.ndarray.__getitem__`.""" + np.testing.assert_array_equal(np.asarray(source[1:3, ::2, -1]), reference()[1:3, ::2, -1]) + + +# --------------------------------------------------------------------------- +# Attribute forwarding +# --------------------------------------------------------------------------- + + +def test_forwards_array_attributes(source: LazyArray) -> None: + assert source.shape == SHAPE + assert source.ndim == len(SHAPE) + assert source.size == int(np.prod(SHAPE)) + assert source.dtype == np.dtype("int64") + assert len(source) == SHAPE[0] + assert "LazyArray" in repr(source) + + +def test_view_shape_comes_from_the_transform(source: LazyArray) -> None: + """A view reports its own shape, not the wrapped array's.""" + view = source.lazy[1:6:2, :, -1] + assert view.shape == (3, 5) + assert view.ndim == 2 + assert view.size == 15 + assert view.dtype == source.dtype + assert "view=" in repr(view) + + +def test_the_wrapper_has_no_chunks_vocabulary() -> None: + """`chunks` is the *source's* word, never the wrapper's.""" + assert not hasattr(make_source("numpy-whole"), "chunks") + assert not hasattr(make_source("zarr"), "chunks") + with pytest.raises(TypeError): + LazyArray(reference(), chunks=PART_SHAPE) # type: ignore[call-arg] + + +def test_scalar_is_basic_even_when_a_slice_separates_it_from_the_arrays() -> None: + """A documented, deliberate departure from one NumPy corner. + + NumPy counts an integer as an *advanced* index for its placement rule, so + `x[0, :, i]` has shape `(len(i), x.shape[1])` — the arrays lead because the + slice separates the integer from them. The positional dialect instead treats + every scalar as a basic index applied first, which is the rule the rest of + the surface follows and the only one `oindex` can express, so the same + selection reads as `x[0][:, i]`. + """ + data = reference() + view = make_source("numpy-uniform-parts").lazy.vindex[0, ..., np.array([3, 0])] + np.testing.assert_array_equal(np.asarray(view.result()), data[0][..., np.array([3, 0])]) + assert view.shape == data[0][..., np.array([3, 0])].shape + assert view.shape != data[0, ..., np.array([3, 0])].shape + + +def test_zero_dimensional_result_is_an_array(source: LazyArray) -> None: + """Both resolvers agree on the kind of a zero-rank result.""" + result = source.lazy[0, 1, 2].result() + assert isinstance(result, np.ndarray) + assert result.ndim == 0 + assert result[()] == reference()[0, 1, 2] + + +def test_construction_selects_readers_explicitly() -> None: + data = reference() + assert LazyArray(data).reader is basic_reader + assert LazyArray.from_numpy(data).reader is numpy_reader + + +def test_reader_wrappers_forward_the_read_contract_unchanged() -> None: + events: list[tuple[str, Any, ReadContext, Any]] = [] + + class RecordingDelegatingReader: + def __init__(self, name: str, inner: Reader) -> None: + self.name = name + self.inner = inner + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + events.append((self.name, source, context, out)) + self.inner.read_into(source, context, out) + + data = reference() + inner = RecordingDelegatingReader("inner", numpy_reader) + outer = RecordingDelegatingReader("outer", inner) + view = LazyArray(data).with_reader(outer).lazy[1:6:2, ::-1, 1].unpartitioned() + + result = view.result() + + assert [name for name, _, _, _ in events] == ["outer", "inner"] + outer_call, inner_call = events + assert outer_call[1] is inner_call[1] is data + assert outer_call[2] is inner_call[2] + assert outer_call[3] is inner_call[3] is result + np.testing.assert_array_equal(result, data[1:6:2, ::-1, 1]) + + +@pytest.mark.parametrize("value", [object(), [1, 2, 3], "array"]) +def test_from_numpy_rejects_non_ndarrays(value: Any) -> None: + with pytest.raises(TypeError, match="from_numpy requires a numpy.ndarray"): + LazyArray.from_numpy(value) + + +class RecordingReader: + def __init__(self) -> None: + self.calls: list[tuple[Any, ReadContext, Any]] = [] + self.contexts: list[ReadContext] = [] + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + self.calls.append((source, context, out)) + self.contexts.append(context) + basic_reader.read_into(source, context, out) + + +def test_view_operations_preserve_the_reader_without_reading() -> None: + data = reference() + reader = RecordingReader() + base = LazyArray(data).with_reader(reader) + views = ( + base.lazy[1:5], + base.with_parts((2, 2, 2)), + base.with_parts_per_axis(((3, 3, 1), (2, 3), (1, 3))), + base.unpartitioned(), + ) + assert reader.calls == [] + assert all(view.reader is reader for view in views) + assert all(part.view.reader is reader for part in views[1].parts()) + + +@pytest.mark.parametrize("value", [object(), None, lambda: None]) +def test_with_reader_requires_callable_read_into(value: Any) -> None: + with pytest.raises(TypeError, match="reader.read_into must be callable"): + LazyArray(reference()).with_reader(value) + + +class ReturningReader: + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> Any: + return np.empty(context.transform.domain.shape, dtype=source.dtype) + + +def test_result_rejects_a_reader_that_returns_a_value() -> None: + view = LazyArray(reference()).with_reader(ReturningReader()) + with pytest.raises(TypeError, match="must return None"): + view.result() + + +class BufferRecordingReader(RecordingReader): + def __init__(self) -> None: + super().__init__() + self.owns_data: list[bool] = [] + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + self.owns_data.append(bool(out.flags.owndata)) + super().read_into(source, context, out) + + +def test_reader_is_called_once_per_touched_part() -> None: + data = np.arange(48).reshape(6, 8) + reader = RecordingReader() + view = LazyArray(data).with_reader(reader).with_parts((3, 4)).lazy[1:5, 2] + np.testing.assert_array_equal(view.result(), data[1:5, 2]) + assert len(reader.calls) == len(tuple(view.parts())) == 2 + assert all( + call[1].transform.domain.inclusive_min == (0,) * call[1].transform.input_rank + for call in reader.calls + ) + + +def test_partition_reader_receives_global_transform_and_existing_projection() -> None: + reader = RecordingReader() + view = LazyArray(np.arange(8)).with_reader(reader).with_parts((4,)) + expected = [part.projection for part in view.parts()] + + np.testing.assert_array_equal(view.result(), np.arange(8)) + + assert [context.projection for context in reader.contexts] == expected + assert [context.transform.apply((0,)) for context in reader.contexts] == [(0,), (4,)] + + +def test_an_empty_result_does_not_call_the_reader() -> None: + reader = RecordingReader() + result = LazyArray(reference()).with_reader(reader).lazy[:, 0:0, :].result() + assert result.shape == (7, 0, 4) + assert reader.calls == [] + + +def test_rectangular_parts_write_into_result_views() -> None: + reader = BufferRecordingReader() + view = LazyArray(reference()).with_reader(reader).with_parts((2, 2, 2)).lazy[1:6, 1:4] + view.result() + assert reader.owns_data + assert not any(reader.owns_data) + + +def test_fancy_part_placement_uses_owned_dense_temporaries() -> None: + reader = BufferRecordingReader() + view = ( + LazyArray(reference()) + .with_reader(reader) + .with_parts((2, 2, 2)) + .lazy.oindex[[6, 1, 1], :, :] + ) + np.testing.assert_array_equal(view.result(), reference()[np.ix_([6, 1, 1], range(5), range(4))]) + assert any(reader.owns_data) + + +def test_reader_exception_propagates_unchanged() -> None: + error = RuntimeError("backend failed") + + class FailingReader: + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + raise error + + with pytest.raises(RuntimeError) as caught: + LazyArray(reference()).with_reader(FailingReader()).result() + assert caught.value is error + + +class ForeignArray: + """A minimal array-like whose advertised `chunks` we do not control.""" + + def __init__(self, data: np.ndarray[Any, Any], chunks: Any) -> None: + self._data = data + self.chunks = chunks + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> Any: + return self._data.dtype + + def __getitem__(self, key: Any) -> Any: + return self._data[key] + + +def test_malformed_discovered_parts_are_ignored() -> None: + """A foreign object's unusable `chunks` falls back to one whole-array part. + + Discovery parses external input, so an attribute that does not describe a + partitioning of the shape means "none I understand", not an error. + """ + data = reference() + for bogus in (((3, 3), (5,), (4,)), (3, 2), "nope", (3.5, 2, 2)): + wrapped = LazyArray(ForeignArray(data, bogus)) + assert len(list(wrapped.parts())) == 1 + np.testing.assert_array_equal(np.asarray(wrapped.lazy[1:3].result()), data[1:3]) + + +def test_discovered_parts_come_from_the_source_vocabulary() -> None: + """`read_chunk_sizes` wins over `chunks`, and both are read as parts.""" + data = reference() + wrapped = LazyArray(ForeignArray(data, PART_SHAPE)) + assert [part.base_coords for part in wrapped.parts()][:3] == [(0, 0, 0), (0, 0, 1), (0, 1, 0)] + assert len(list(wrapped.parts())) == 3 * 3 * 2 + + +# --------------------------------------------------------------------------- +# Boxes +# --------------------------------------------------------------------------- + +# (id, build, expected is_box, expected bounding_box). The bounds are storage +# intervals of the wrapped (7, 5, 4) array, computed by hand. +BOX_CASES: list[tuple[str, Callable[[LazyArray], LazyArray], bool, Any]] = [ + ("identity", lambda a: a, True, ((0, 7), (0, 5), (0, 4))), + ("basic-slice", lambda a: a.lazy[1:6, :, 1:3], True, ((1, 6), (0, 5), (1, 3))), + # Stride 2 over axis 1 touches 0, 2, 4; the hull is the closed span. + ("strided", lambda a: a.lazy[::3, ::2, :], True, ((0, 7), (0, 5), (0, 4))), + ("int-drop", lambda a: a.lazy[2, :, -1], True, ((2, 3), (0, 5), (3, 4))), + ("all-scalars", lambda a: a.lazy[0, 1, 2], True, ((0, 1), (1, 2), (2, 3))), + ("negative-and-open", lambda a: a.lazy[-2:], True, ((5, 7), (0, 5), (0, 4))), + ( + "oindex", + lambda a: a.lazy.oindex[[4, 0, 0], :, [3, 1]], + False, + ((0, 5), (0, 5), (1, 4)), + ), + ( + "vindex", + lambda a: a.lazy.vindex[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])], + False, + ((0, 7), (0, 5), (0, 3)), + ), + ("mask", lambda a: a.lazy.vindex[MASK], False, ((0, 7), (0, 5), (0, 4))), + # Composition preserves the category in both directions. + ("box-of-box", lambda a: a.lazy[1:6].lazy[:, 1:3], True, ((1, 6), (1, 3), (0, 4))), + ( + "box-after-fancy", + lambda a: a.lazy.oindex[[4, 0, 2], :, :].lazy[0:2], + False, + ((0, 5), (0, 5), (0, 4)), + ), + ("empty", lambda a: a.lazy[2:2], True, None), + ( + "empty-fancy", + lambda a: a.lazy.oindex[np.array([], dtype=np.intp), :, :], + False, + None, + ), +] + + +@pytest.mark.parametrize( + ("build", "expected_is_box", "expected_bounds"), + [case[1:] for case in BOX_CASES], + ids=[case[0] for case in BOX_CASES], +) +def test_is_box_and_bounding_box( + source: LazyArray, + build: Callable[[LazyArray], LazyArray], + expected_is_box: bool, + expected_bounds: Any, +) -> None: + """The box/query taxonomy, and the hull every selection has either way.""" + view = build(source) + assert view.is_box is expected_is_box + assert view.bounding_box() == expected_bounds + + +def test_a_unit_stride_box_is_dense_in_its_bounding_box() -> None: + """Stride 1 everywhere: the hull is exactly what the view selects.""" + data = reference() + view = make_source("numpy-uniform-parts").lazy[1:6, :, 1:3] + assert view.is_box + assert view.strides() == (1, 1, 1) + bounds = view.bounding_box() + assert bounds is not None + np.testing.assert_array_equal( + np.asarray(view.result()), + data[tuple(slice(lo, hi) for lo, hi in bounds)], + ) + + +def test_a_strided_box_is_sparse_in_its_bounding_box() -> None: + """Stride > 1: the hull is a superset, and `strides()` is what says by how much.""" + data = reference() + view = make_source("numpy-uniform-parts").lazy[1:6, ::2, :] + assert view.is_box + assert view.strides() == (1, 2, 1) + bounds = view.bounding_box() + assert bounds is not None + assert bounds == ((1, 6), (0, 5), (0, 4)) + + hull = data[tuple(slice(lo, hi) for lo, hi in bounds)] + assert hull.size == 5 * 5 * 4 + assert view.size == 5 * 3 * 4 + # A consumer that slabbed the hull and threw the rest away would over-read. + assert hull.size > view.size + # Applying the strides to the hull recovers the selection exactly. + np.testing.assert_array_equal( + np.asarray(view.result()), + hull[tuple(slice(None, None, step) for step in view.strides() or ())], + ) + + +def test_strides_are_none_for_a_query() -> None: + view = make_source("numpy-uniform-parts").lazy.oindex[[5, 1], :, :] + assert not view.is_box + assert view.strides() is None + + +def test_an_integer_indexed_dimension_has_stride_one() -> None: + view = make_source("numpy-uniform-parts").lazy[2, ::3, :] + assert view.strides() == (1, 3, 1) + assert view.bounding_box() == ((2, 3), (0, 4), (0, 4)) + + +def test_a_query_bounding_box_is_only_a_hull() -> None: + """For a fancy selection the box is a superset, and `is_box` says so.""" + view = make_source("numpy-uniform-parts").lazy.oindex[[5, 1], :, :] + assert not view.is_box + assert view.bounding_box() == ((1, 6), (0, 5), (0, 4)) + # The hull spans 5 rows; the selection touches 2 of them. + assert view.shape[0] == 2 + + +# --------------------------------------------------------------------------- +# Parts +# --------------------------------------------------------------------------- + + +class _ReadMustNotRun: + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + raise AssertionError("prepared-plan validation must happen before any read") + + +def test_prepared_part_validation_allocates_boolean_coverage_bitmap( + monkeypatch: pytest.MonkeyPatch, +) -> None: + view = LazyArray.from_numpy(reference()).with_parts(PART_SHAPE).lazy[1:6, ::2, 1:] + parts = tuple(view.parts()) + allocations: list[tuple[tuple[int, ...], np.dtype[Any]]] = [] + real_zeros = np.zeros + + def recording_zeros(shape: Any, *args: Any, **kwargs: Any) -> np.ndarray[Any, Any]: + result = real_zeros(shape, *args, **kwargs) + allocations.append((tuple(shape), result.dtype)) + return result + + monkeypatch.setattr(lazy_array_module.np, "zeros", recording_zeros) + + _validate_prepared_parts(parts, view.shape) + + assert allocations == [(view.shape, np.dtype(np.bool_))] + + +@pytest.mark.parametrize( + ("data", "part_shape", "build", "expected"), + [ + pytest.param( + np.arange(8), + (3,), + lambda array: array.lazy[1:7:2], + np.array([1, 3, 5]), + id="basic-reordered-parts", + ), + pytest.param( + np.arange(8), + (3,), + lambda array: array.lazy[3], + np.array(3), + id="scalar", + ), + pytest.param( + np.arange(20).reshape(4, 5), + (2, 3), + lambda array: array.lazy.oindex[[3, 1, 1], [4, 0]], + np.array([[19, 15], [9, 5], [9, 5]]), + id="orthogonal-fancy", + ), + pytest.param( + np.arange(20).reshape(4, 5), + (2, 3), + lambda array: array.lazy.vindex[[3, 1, 1], [4, 0, 4]], + np.array([19, 5, 9]), + id="correlated-fancy", + ), + pytest.param( + np.arange(8), + (3,), + lambda array: array.lazy[2:2], + np.array([], dtype=np.int64), + id="empty", + ), + ], +) +def test_result_accepts_prepared_parts_from_the_same_view( + monkeypatch: pytest.MonkeyPatch, + data: np.ndarray[Any, Any], + part_shape: tuple[int, ...], + build: Callable[[LazyArray], LazyArray], + expected: np.ndarray[Any, Any], +) -> None: + view = build(LazyArray.from_numpy(data).with_parts(part_shape)) + parts = tuple(reversed(tuple(view.parts()))) + + def unexpected_replan(self: LazyArray) -> Any: + raise AssertionError("result(parts=...) must not construct another partition plan") + + monkeypatch.setattr(LazyArray, "parts", unexpected_replan) + + np.testing.assert_array_equal(view.result(parts=parts), expected) + + +def test_result_rejects_prepared_parts_owned_by_another_view() -> None: + data = reference() + base = LazyArray.from_numpy(data).with_reader(_ReadMustNotRun()).with_parts(PART_SHAPE) + view = base.lazy[1:6, ::2, 1:] + owned_parts = tuple(view.parts()) + foreign_parts = tuple(base.lazy[1:6, ::2, 1:].parts()) + mixed_parts = (owned_parts[0], *foreign_parts[1:]) + + with pytest.raises(ValueError, match="prepared parts do not belong to this view"): + view.result(parts=mixed_parts) + + +def test_result_rejects_prepared_parts_that_do_not_tile_the_view() -> None: + data = reference() + view = ( + LazyArray.from_numpy(data) + .with_reader(_ReadMustNotRun()) + .with_parts(PART_SHAPE) + .lazy[1:6, ::2, 1:] + ) + parts = tuple(view.parts()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=parts[:-1]) + + +def test_result_rejects_prepared_parts_with_a_duplicate_and_omission() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, _second = tuple(view.parts()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(first, first)) + + +def test_result_rejects_complete_prepared_parts_plus_a_duplicate() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, second = tuple(view.parts()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(first, second, first)) + + +def test_result_rejects_overlapping_prepared_parts() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, second = tuple(view.parts()) + overlapping = replace(second, out_selection=(slice(2, 6),)) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(first, overlapping)) + + +def test_result_rejects_wrong_rank_prepared_parts() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, second = tuple(view.parts()) + wrong_rank = replace(first, out_selection=()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(wrong_rank, second)) + + +def test_result_rejects_empty_prepared_parts_for_a_nonempty_view() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=()) + + +def test_result_accepts_empty_prepared_parts_for_an_empty_view() -> None: + view = ( + LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)).lazy[0:0] + ) + + np.testing.assert_array_equal(view.result(parts=()), np.array([], dtype=np.int64)) + + +@pytest.mark.parametrize("flavor", FLAVORS) +@pytest.mark.parametrize( + "build", + [ + lambda a: a, + lambda a: a.lazy[1:6, :, 1:], + lambda a: a.lazy.oindex[[4, 0, 0], :, [3, 1]], + lambda a: a.lazy.vindex[..., np.array([1, 4, 0]), np.array([2, 0, 1])], + # A reversing view drives the negative-stride branches of + # `_intersect_dimension_map` and chunk projection, which were + # written defensively long before anything could reach them. + lambda a: a.lazy[::-1, ::-2, :], + lambda a: a.lazy[5:1:-1, :, ::-1], + ], + ids=["identity", "basic", "oindex", "vindex", "reversed", "reversed-bounded"], +) +def test_parts_tile_the_view_exactly_and_disjointly( + flavor: str, build: Callable[[LazyArray], LazyArray] +) -> None: + """Assembling the parts reproduces `result()`; the placements cover with no overlap.""" + view = build(make_source(flavor)) + expected = np.asarray(view.result()) + + assembled = np.zeros(view.shape, dtype=view.dtype) + hits = np.zeros(view.shape, dtype=np.int64) + for part in view.parts(): + assembled[part.out_selection] = np.asarray(part.view.result()) + # `np.add.at` accumulates per element; `+= 1` on a fancy index would + # count a repeated position once and hide a real overlap. + np.add.at(hits, part.out_selection, 1) + + np.testing.assert_array_equal(assembled, expected) + np.testing.assert_array_equal(hits, np.ones(view.shape, dtype=np.int64)) + + +def _transform_point(transform: IndexTransform, point: tuple[int, ...]) -> tuple[int, ...]: + """Evaluate a transform pointwise for projection placement assertions.""" + result: list[int] = [] + for output_map in transform.output: + if isinstance(output_map, ConstantMap): + result.append(output_map.offset) + elif isinstance(output_map, DimensionMap): + result.append(output_map.offset + output_map.stride * point[output_map.input_dimension]) + else: + index = tuple( + 0 + if output_map.index_array.shape[axis] == 1 + else point[axis] - transform.domain.inclusive_min[axis] + for axis in range(output_map.index_array.ndim) + ) + result.append( + output_map.offset + output_map.stride * int(output_map.index_array[index]) + ) + return tuple(result) + + +@pytest.mark.parametrize( + "build", + [ + lambda array: array.lazy.oindex[[6, 0, 2], :, [3, 1]], + lambda array: array.lazy.vindex[..., np.array([4, 0, 4]), np.array([3, 1, 1])], + ], + ids=["orthogonal", "vectorized"], +) +def test_partition_exposes_projection_as_its_placement_authority( + build: Callable[[LazyArray], LazyArray], +) -> None: + """A part's NumPy placement addresses exactly its cell-transform range.""" + view = build(LazyArray(reference()).with_parts(PART_SHAPE)) + assembled = np.zeros(view.shape, dtype=view.dtype) + + for part in view.parts(): + projection = part.projection + assert isinstance(projection, ChunkProjection) + assert part.view.transform == projection.chunk_transform.translate( + tuple(lo for lo, _ in part.box) + ) + assert part.base_coords == projection.chunk_coords + assert part.box == tuple( + zip( + projection.chunk_domain.inclusive_min, + projection.chunk_domain.exclusive_max, + strict=True, + ) + ) + + expected_hits = np.zeros(view.shape, dtype=np.int8) + cell_domain = projection.cell_transform.domain + for positional_point in np.ndindex(*cell_domain.shape): + cell_point = tuple( + coordinate + origin + for coordinate, origin in zip( + positional_point, cell_domain.inclusive_min, strict=True + ) + ) + expected_hits[_transform_point(projection.cell_transform, cell_point)] = 1 + actual_hits = np.zeros(view.shape, dtype=np.int8) + actual_hits[part.out_selection] = 1 + np.testing.assert_array_equal(actual_hits, expected_hits) + + assembled[part.out_selection] = np.asarray(part.view.result()) + + np.testing.assert_array_equal(assembled, np.asarray(view.result())) + + +def test_nonfirst_partition_transform_directly_addresses_its_array() -> None: + source = np.arange(8) + part = list(LazyArray.from_numpy(source).with_parts((4,)).parts())[1] + + assert part.box == ((4, 8),) + assert part.view.transform.apply((0,)) == (4,) + assert part.view.array[part.view.transform.apply((0,))] == 4 + assert part.view.result()[0] == 4 + assert part.projection.chunk_transform.apply((0,)) == (0,) + + +def test_partition_token_encodes_its_public_global_transform() -> None: + source = np.arange(8) + base = LazyArray.from_numpy(source) + partition_view = list(base.with_parts((4,)).parts())[1].view + direct_view = base.lazy[4:8] + + assert partition_view.__dask_tokenize__() == direct_view.__dask_tokenize__() + + +def test_parts_resolve_independently_and_concurrently() -> None: + """Each part's `array` is a standalone `LazyArray` with no shared mutable state.""" + view = make_source("zarr").lazy[1:7, :, 1:].with_parts((2, 2, 2)) + parts = list(view.parts()) + assert len(parts) > 1 + + with ThreadPoolExecutor(max_workers=4) as pool: + values = list(pool.map(lambda part: np.asarray(part.view.result()), parts)) + + assembled = np.zeros(view.shape, dtype=view.dtype) + for part, value in zip(parts, values, strict=True): + assembled[part.out_selection] = value + np.testing.assert_array_equal(assembled, np.asarray(view.result())) + + +def test_parts_report_completeness() -> None: + """`is_complete` distinguishes a fully-covered box from a partial one.""" + array = make_source("numpy-uniform-parts") + assert all(part.is_complete for part in array.parts()) + # Boxes along axis 2 are [0, 3) and [3, 4); dropping column 0 leaves the + # first partially covered and the second whole. + trimmed = {part.base_coords[2]: part.is_complete for part in array.lazy[:, :, 1:].parts()} + assert trimmed == {0: False, 1: True} + # A fancy axis is always reported incomplete. + assert not any(part.is_complete for part in array.lazy.oindex[[4, 0, 0], :, :].parts()) + + +def test_partition_boxes_are_global_and_tile_the_base() -> None: + """Both the selected hull and the whole partition box use global coordinates.""" + view = make_source("numpy-uniform-parts").lazy[1:6, :, 1:] + parts = {part.base_coords: part for part in view.parts()} + + # The reviewer's repro: two parts of the same view now expose distinct + # source-global selected hulls as well as distinct whole partition boxes. + first, second = parts[0, 0, 0], parts[0, 1, 0] + assert first.view.bounding_box() == ((1, 3), (0, 2), (1, 3)) + assert second.view.bounding_box() == ((1, 3), (2, 4), (1, 3)) + assert first.box != second.box + assert first.box == ((0, 3), (0, 2), (0, 3)) + assert second.box == ((0, 3), (2, 4), (0, 3)) + + # Every box is the base partitioning's own box for those coordinates, and + # the touched boxes tile the region the view reads without overlapping. + grids = dimension_grids_from_chunks(PART_SHAPE, SHAPE) + for coords, part in parts.items(): + expected = tuple( + (grid.chunk_offset(c), grid.chunk_offset(c) + grid.data_size(c)) + for grid, c in zip(grids, coords, strict=True) + ) + assert part.box == expected + covered = np.zeros(SHAPE, dtype=np.int64) + for part in parts.values(): + covered[tuple(slice(lo, hi) for lo, hi in part.box)] += 1 + assert covered.max() == 1 + # The view reads rows 1..5 and columns 1.., so every box it touches + # intersects that region and no box outside it is visited. + assert covered[1:6, :, 1:].sum() > 0 + assert covered[6:, :, :].sum() == 0 + + +def test_partition_box_of_a_whole_array_part() -> None: + part = next(iter(make_source("numpy-whole").parts())) + assert part.box == tuple((0, extent) for extent in SHAPE) + + +def test_an_unpartitioned_wrapper_has_a_single_whole_array_part() -> None: + view = make_source("numpy-whole") + parts = list(view.parts()) + assert len(parts) == 1 + assert parts[0].base_coords == (0, 0, 0) + assert parts[0].view.shape == SHAPE + assert parts[0].is_complete + np.testing.assert_array_equal(np.asarray(parts[0].view.result()), reference()) + + +def test_with_parts_keeps_the_view_and_the_base() -> None: + view = make_source("zarr").lazy[1:6, ::2] + repartitioned = view.with_parts((2, 1, 4)) + assert repartitioned.shape == view.shape + assert repartitioned.array is view.array + assert repartitioned.transform == view.transform + # A different partitioning really is a different set of boxes. + assert [part.base_coords for part in repartitioned.parts()] != [ + part.base_coords for part in view.parts() + ] + np.testing.assert_array_equal(np.asarray(repartitioned.result()), np.asarray(view.result())) + + +def test_with_parts_none_forces_one_shot_resolution() -> None: + view = make_source("zarr").lazy.oindex[[4, 0, 0], :, :] + whole = view.unpartitioned() + assert len(list(whole.parts())) == 1 + np.testing.assert_array_equal(np.asarray(whole.result()), np.asarray(view.result())) + + +@pytest.mark.parametrize( + ("parts", "match"), + [ + ((3,), "one entry per dimension"), + ((3, (2, 2), 4), "not a mixture"), + (((3, 3), (2, 2, 1), (3, 1)), "sum to 6, but the array extent is 7"), + ((3, 0, 3), "chunk shape entries must be positive"), + # A float or a None belongs to neither convention; saying "not a + # mixture" would send the reader looking for the wrong mistake. + ((3.5, 2, 2), r"3\.5 at dimension 0 is neither"), + ((None, 5, 4), "None at dimension 0 is neither"), + ((3.5, 2.5, 2.5), r"3\.5 at dimension 0, 2\.5 at dimension 1, .* are neither"), + (((1.5, 5.5), (5,), (4,)), "per-axis chunk sizes must be integers; dimension 0"), + ], +) +def test_with_parts_validates_strictly(parts: Any, match: str) -> None: + """`with_parts` is our own API, so a malformed partitioning raises.""" + with pytest.raises(ValueError, match=match): + repartition(make_source("numpy-whole"), parts) + + +# --------------------------------------------------------------------------- +# Protocols +# --------------------------------------------------------------------------- + + +def test_dask_token_is_deterministic_and_discriminating() -> None: + """Same data and same view token alike; a different selection differs.""" + data = reference() + base = LazyArray(data) + assert base.__dask_tokenize__() == LazyArray(reference()).__dask_tokenize__() + + tokens = { + "base": base.__dask_tokenize__(), + "view": base.lazy[1:3].__dask_tokenize__(), + "other view": base.lazy[2:4].__dask_tokenize__(), + "other data": LazyArray(data + 1).__dask_tokenize__(), + } + assert len({repr(token) for token in tokens.values()}) == len(tokens) + # Equivalent transforms reached different ways still token alike. + assert base.lazy[1:5].lazy[0:2].__dask_tokenize__() == base.lazy[1:3].__dask_tokenize__() + + +def test_reader_and_partitioning_do_not_change_dask_identity() -> None: + base = LazyArray(reference()) + token = base.__dask_tokenize__() + assert base.with_reader(numpy_reader).__dask_tokenize__() == token + assert base.with_reader(basic_reader).__dask_tokenize__() == token + assert base.with_parts((2, 2, 2)).__dask_tokenize__() == token + + +@pytest.mark.parametrize("reader", [basic_reader, numpy_reader, DelegatingReader(numpy_reader)]) +def test_reader_survives_pickle(reader: Reader) -> None: + view = LazyArray(reference()).with_reader(reader).lazy[1:5, ::2] + restored = pickle.loads(pickle.dumps(view)) + assert type(restored.reader) is type(reader) + np.testing.assert_array_equal(restored.result(), view.result()) + + +def test_iteration_yields_eager_slices(source: LazyArray) -> None: + rows = list(source.lazy[2:5]) + assert len(rows) == 3 + for row, expected in zip(rows, reference()[2:5], strict=True): + np.testing.assert_array_equal(np.asarray(row), expected) + + +def test_iteration_over_a_zero_dimensional_view_is_rejected() -> None: + with pytest.raises(TypeError, match="iteration over a 0-d array"): + iter(make_source("numpy-uniform-parts").lazy[0, 0, 0]) + + +def test_len_of_a_zero_dimensional_view_is_rejected() -> None: + with pytest.raises(TypeError, match="len\\(\\) of unsized object"): + len(make_source("numpy-uniform-parts").lazy[0, 0, 0]) + + +@pytest.mark.parametrize( + ("convert", "selection"), + [ + (bool, (1, 1, 1)), + (int, (1, 1, 1)), + (float, (1, 1, 1)), + (operator.index, (1, 1, 1)), + (bool, (1, 1, slice(0, 1))), + ], + ids=["bool-0d", "int-0d", "float-0d", "index-0d", "bool-size-1"], +) +def test_scalar_conversions_match_numpy(convert: Any, selection: Any) -> None: + """Size-1 conversions delegate to NumPy, values and all.""" + data = reference() + view = make_source("numpy-uniform-parts").lazy[selection] + assert convert(view) == convert(data[selection]) + + +@pytest.mark.parametrize( + ("convert", "selection", "error"), + [ + (bool, (slice(0, 2), 0, 0), ValueError), + (bool, (slice(0, 0), 0, 0), ValueError), + (int, (slice(0, 1), 0, 0), TypeError), + (float, (slice(0, 2), 0, 0), TypeError), + (operator.index, (slice(0, 1), 0, 0), TypeError), + ], + ids=["bool-many", "bool-empty", "int-1d", "float-many", "index-1d"], +) +def test_scalar_conversions_raise_what_numpy_raises( + convert: Any, selection: Any, error: type[Exception] +) -> None: + data = reference() + view = make_source("numpy-uniform-parts").lazy[selection] + with pytest.raises(error): + convert(view) + with pytest.raises(error): + convert(data[selection]) + + +def test_pickle_round_trip() -> None: + """A wrapper over a picklable base survives a round trip, view and parts intact.""" + view = LazyArray(reference()).with_parts((2, 2, 2)).lazy[1:6, ::2].lazy.oindex[[3, 0, 0], :, :] + restored = pickle.loads(pickle.dumps(view)) + assert restored.shape == view.shape + assert restored.__dask_tokenize__() == view.__dask_tokenize__() + np.testing.assert_array_equal(np.asarray(restored.result()), np.asarray(view.result())) + + +# --------------------------------------------------------------------------- +# dask interop +# --------------------------------------------------------------------------- + + +def test_dask_from_array_roundtrip() -> None: + """A `LazyArray` is a drop-in dask source — no translation ceremony.""" + da = pytest.importorskip("dask.array") + source = make_source("zarr") + + lazy = da.from_array(source) + np.testing.assert_array_equal(lazy.compute(), reference()) + + # dask chooses its own blocks; the wrapper reads each of them through its + # own parts, so the two partitionings need not agree. + blocked = da.from_array(source, chunks=(4, 3, 3)) + assert blocked.chunks == ((4, 3), (3, 2), (3, 1)) + np.testing.assert_array_equal(blocked[2:, ::2].compute(), reference()[2:, ::2]) + + +# --------------------------------------------------------------------------- +# Errors +# --------------------------------------------------------------------------- + + +def test_boolean_scalar_is_rejected() -> None: + with pytest.raises(IndexError, match="boolean scalars are not valid indices"): + make_source("numpy-uniform-parts").lazy[True] + + +@pytest.mark.parametrize( + ("mode", "selection", "expected"), + [ + pytest.param("basic", IndexLike(2), np.array(2), id="basic-scalar"), + pytest.param( + "basic", + slice(IndexLike(1), IndexLike(7), IndexLike(2)), + np.array([1, 3, 5]), + id="basic-slice-components", + ), + pytest.param("orthogonal", IndexLike(2), np.array(2), id="orthogonal-scalar"), + pytest.param("vectorized", IndexLike(2), np.array(2), id="vectorized-scalar"), + ], +) +def test_positional_selectors_support_the_index_protocol( + mode: str, selection: Any, expected: np.ndarray[Any, Any] +) -> None: + source = LazyArray.from_numpy(np.arange(8)) + if mode == "basic": + view = source.lazy[selection] + else: + view = getattr(source.lazy, "oindex" if mode == "orthogonal" else "vindex")[selection] + + result = np.asarray(view.result()) + assert result.shape == expected.shape + np.testing.assert_array_equal(result, expected) + + +def test_positional_selector_rejects_int_only_objects() -> None: + with pytest.raises(IndexError, match="unsupported selection type"): + LazyArray.from_numpy(np.arange(8)).lazy[IntOnly()] + + +def test_positional_selector_propagates_malformed_index_protocol() -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + LazyArray.from_numpy(np.arange(8)).lazy[BadIndex()] + + +def test_positional_slice_propagates_malformed_index_protocol() -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + LazyArray.from_numpy(np.arange(8)).lazy[:: BadIndex()] + + +def test_protocol_objects_inside_an_index_array_remain_invalid() -> None: + selection = np.array([IndexLike(2)], dtype=object) + with pytest.raises(IndexError, match="integer or boolean"): + LazyArray.from_numpy(np.arange(8)).lazy.oindex[selection] + + +def test_mask_shape_must_match_the_view() -> None: + array = make_source("numpy-uniform-parts") + with pytest.raises(IndexError, match="boolean index has shape"): + array.lazy.vindex[np.ones((2, 2, 2), dtype=bool)] + + +def test_scalar_index_out_of_bounds() -> None: + with pytest.raises(IndexError, match="index 7 is out of bounds for axis 0 with size 7"): + make_source("numpy-uniform-parts").lazy[7] + + +def test_scalar_index_out_of_bounds_in_a_view() -> None: + """Bounds are the *view's*, not the wrapped array's.""" + array = make_source("numpy-uniform-parts").lazy[1:4] + with pytest.raises(IndexError, match="index 3 is out of bounds for axis 0 with size 3"): + array.lazy[3] + + +def test_index_array_out_of_bounds() -> None: + array = make_source("numpy-uniform-parts") + with pytest.raises(IndexError, match="index 99 is out of bounds for axis 0 with size 7"): + array.lazy.oindex[[0, 99], :, :] + + +def test_too_many_indices() -> None: + with pytest.raises(IndexError, match="too many indices"): + make_source("numpy-uniform-parts").lazy[0, 0, 0, 0] + + +def test_copy_false_conversion_is_rejected() -> None: + array = make_source("numpy-uniform-parts") + with pytest.raises(ValueError, match="cannot be converted to a NumPy array without a copy"): + np.array(array, copy=False) + + +# --------------------------------------------------------------------------- +# Negative steps +# --------------------------------------------------------------------------- + + +def test_reversed_box_reports_a_positive_stride(source: LazyArray) -> None: + """A reversal is still a box; `strides()` is magnitudes, so it matches the forward twin.""" + reversed_view = source.lazy[::-2] + forward = source.lazy[::2] + assert reversed_view.is_box + assert reversed_view.strides() == forward.strides() == (2, 1, 1) + assert reversed_view.bounding_box() == ((0, 7), (0, 5), (0, 4)) + + +def test_a_reversed_view_is_re_based_to_origin_zero() -> None: + """The literal domain of a reversal is negative; the positional dialect hides it.""" + view = make_source("numpy-whole").lazy[::-1] + # The algebra's own answer keeps the source frame. + assert IndexTransform.from_shape(SHAPE)[::-1].domain.inclusive_min[0] == -6 + # The wrapper re-bases, so positions start at 0 as NumPy expects. + assert view.transform.domain.inclusive_min == (0, 0, 0) + assert view.shape == SHAPE + np.testing.assert_array_equal(np.asarray(view.result()), reference()[::-1]) + + +def test_zero_step_is_rejected() -> None: + with pytest.raises(ValueError, match="step cannot be zero"): + make_source("numpy-whole").lazy[::0] + + +def test_reversed_positional_interval_is_empty_not_an_error() -> None: + """NumPy's rule at the boundary; the literal layer keeps TensorStore's.""" + view = make_source("numpy-uniform-parts").lazy[2:5:-1] + assert view.shape == (0, 5, 4) + np.testing.assert_array_equal(np.asarray(view.result()), reference()[2:5:-1]) + # Literal coordinates, on the other hand, call it a direction error. + with pytest.raises(IndexError, match="valid interval"): + IndexTransform.from_shape(SHAPE)[2:5:-1] + + +def test_negative_step_over_a_fancy_axis_reverses_the_coordinates(source: LazyArray) -> None: + """Reversing a gathered axis materializes, rather than attaching a stride.""" + view = source.lazy.oindex[[3, 1, 2], :, :].lazy[::-1] + expected = outer(reference(), ([3, 1, 2], slice(None), slice(None)))[::-1] + np.testing.assert_array_equal(np.asarray(view.result()), expected) + m = view.transform.output[0] + assert isinstance(m, ArrayMap) + np.testing.assert_array_equal(m.index_array.reshape(-1), np.array([2, 1, 3])) + + +# --------------------------------------------------------------------------- +# Minimal sources +# --------------------------------------------------------------------------- + + +class MinimalSource: + """The floor of the wrapped-array protocol: `shape`, `dtype`, `__getitem__`.""" + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self._data = data + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> Any: + return self._data.dtype + + def __getitem__(self, key: Any) -> Any: + return self._data[key] + + +class RecordingSource(MinimalSource): + """A minimal source that records every attempted data read.""" + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + super().__init__(data) + self.reads: list[Any] = [] + + def __getitem__(self, key: Any) -> Any: + self.reads.append(key) + return super().__getitem__(key) + + +@pytest.mark.parametrize( + "build", + [ + lambda a: a.lazy[:, 2:2, :], + lambda a: a.lazy.vindex[np.array([[6], [3], [0]]), -4].lazy[0, 0:0], + ], + ids=["ordinary", "unreferenced-axis"], +) +def test_an_empty_view_does_not_read_its_source( + build: Callable[[LazyArray], LazyArray], +) -> None: + source = RecordingSource(reference()) + result = build(LazyArray(source)).result() + + assert result.size == 0 + assert source.reads == [] + + +# --------------------------------------------------------------------------- +# Materializing +# --------------------------------------------------------------------------- + + +class NumpyBackedSource: + """A duck array that stores its data in NumPy and returns views from reads. + + Not an `np.ndarray`, so nothing about the source can be compared against the + result's memory — but its blocks are NumPy views of storage the caller must + not be handed. The `BASIC` source this package invites people to wrap. + """ + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self.data = data + + @property + def shape(self) -> tuple[int, ...]: + return self.data.shape + + @property + def dtype(self) -> Any: + return self.data.dtype + + def __getitem__(self, selection: Any) -> Any: + return self.data[selection] + + +@pytest.mark.parametrize("parts", [None, (2, 2, 2), SHAPE]) +@pytest.mark.parametrize("wrap", [lambda d: d, NumpyBackedSource], ids=["ndarray", "duck"]) +@pytest.mark.parametrize( + ("build", "description"), + [ + (lambda a: a.lazy[1:3, :, :], "a basic slice"), + (lambda a: a.lazy[:, :, :], "the whole array"), + (lambda a: a.lazy[::-1, :, :], "a reversal"), + (lambda a: a.lazy.oindex[[2, 0], :, :], "a gather"), + ], +) +def test_materializing_never_hands_back_the_wrapped_array( + parts: Any, + wrap: Callable[[np.ndarray[Any, Any]], Any], + build: Callable[[LazyArray], LazyArray], + description: str, +) -> None: + """Writing to a materialized result must never reach the source. + + An unpartitioned read of a basic selection can be answered with a *view* of + the wrapped array, and NumPy 2 hands whatever `__array__` returns straight to + the caller. Every route out of the wrapper detaches, so the answer does not + depend on how the read happened to be divided. + + Run over both a raw `ndarray` and a duck array that merely stores its data in + NumPy: the second is the case where the source cannot be compared against the + result, so detaching has to decide from the result's own buffer instead. + """ + data = reference() + view = build(repartition(LazyArray(wrap(data)), parts)) + + for materialize in ( + lambda v: v.result(), + lambda v: np.array(v, copy=True), + lambda v: np.asarray(v), + lambda v: np.array(v), + ): + before = data.copy() + materialized = np.asarray(materialize(view)) + assert not np.shares_memory(materialized, data), description + materialized[...] = -1 + np.testing.assert_array_equal(data, before, err_msg=description) + + +def test_an_eager_getitem_never_hands_back_the_wrapped_array() -> None: + data = reference() + block = LazyArray(data)[1:3] + block[...] = -1 + np.testing.assert_array_equal(data, reference()) + + +def test_result_refuses_to_return_a_partly_written_buffer( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A partition walk that leaves a gap must raise, not return process memory. + + `result()` scatters into an uninitialized buffer, which is only safe because + the parts tile the view. This is the guard that turns any future break of + that contract into a failure instead of into plausible-looking numbers. + """ + view = LazyArray(reference()).with_parts(PART_SHAPE).lazy[:, 1:, :] + complete = LazyArray.parts + + def drop_one(self: LazyArray) -> Any: + return list(complete(self))[:-1] + + monkeypatch.setattr(LazyArray, "parts", drop_one) + with pytest.raises(AssertionError, match="partition walk addressed"): + view.result() + + +def test_result_refuses_a_partition_of_the_wrong_rank(monkeypatch: pytest.MonkeyPatch) -> None: + """A part addressing fewer axes than the view has is caught by name.""" + view = LazyArray(reference()).with_parts(PART_SHAPE).lazy[:, 1:, :] + complete = LazyArray.parts + + def truncate(self: LazyArray) -> Any: + return [replace(part, out_selection=part.out_selection[:-1]) for part in complete(self)] + + monkeypatch.setattr(LazyArray, "parts", truncate) + with pytest.raises(AssertionError, match="of the view's 3 dimensions"): + view.result() + + +class DuckBlock: + """An array-like meeting exactly the documented `BASIC` floor and no more. + + `shape`, `dtype`, and a `__getitem__` that understands integers and slices. + Anything else — an integer array, `take`, `reshape` — raises, and indexing it + yields another one of itself, so a block that comes back from it is as + limited as the source was. + """ + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self._data = data + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> Any: + return self._data.dtype + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: + return np.array(self._data, dtype=dtype, copy=True if copy is None else copy) + + def __getitem__(self, key: Any) -> DuckBlock: + selectors = key if isinstance(key, tuple) else (key,) + for selector in selectors: + if not isinstance(selector, (int, np.integer, slice)): + raise TypeError(f"basic indexing only, got {selector!r}") + return DuckBlock(self._data[key]) + + +@pytest.mark.parametrize( + ("build", "oracle"), + [ + (lambda a: a.lazy[1:5, ::2, :], lambda r: r[1:5, ::2, :]), + ( + lambda a: a.lazy.oindex[[4, 0, 0], :, :], + lambda r: r[np.ix_([4, 0, 0], range(5), range(4))], + ), + (lambda a: a.lazy.vindex[[4, 0], [1, 1]], lambda r: r[[4, 0], [1, 1]]), + (lambda a: a.lazy[::-1, :, :], lambda r: r[::-1, :, :]), + ], + ids=["basic", "oindex", "vindex", "reversal"], +) +@pytest.mark.parametrize("parts", [None, PART_SHAPE]) +def test_a_source_meeting_only_the_basic_floor_resolves_any_selection( + build: Callable[[LazyArray], LazyArray], oracle: Callable[[Any], Any], parts: Any +) -> None: + """The floor is a promise about the source; its blocks are coerced, not trusted.""" + expected = np.asarray(oracle(reference())) + view = build(repartition(LazyArray(DuckBlock(reference())), parts)) + assert view.shape == expected.shape + np.testing.assert_array_equal(np.asarray(view.result()), expected) + + +def test_the_duck_block_double_refuses_a_fancy_key() -> None: + """A negative control: the floor test only means something if the double bites.""" + with pytest.raises(TypeError, match="basic indexing only"): + DuckBlock(reference())[np.array([1, 0])] + + +# --------------------------------------------------------------------------- +# Sources with their own opinions +# --------------------------------------------------------------------------- + + +@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") +def test_numpy_matrix_is_refused() -> None: + """`np.matrix` never reduces rank, so a view's shape could not be honored.""" + with pytest.raises(TypeError, match="numpy.matrix cannot be wrapped"): + LazyArray(np.matrix(np.arange(12).reshape(3, 4))) + + +@pytest.mark.parametrize("parts", [None, (2, 2), (1, 4), (3, 4)]) +def test_a_masked_source_keeps_its_mask_under_every_partitioning(parts: Any) -> None: + data = np.ma.masked_greater(np.arange(12).reshape(3, 4), 7) + got = repartition(LazyArray(data), parts).lazy[:, 1:].result() + expected = data[:, 1:] + assert isinstance(got, np.ma.MaskedArray), parts + np.testing.assert_array_equal(np.ma.getmaskarray(got), np.ma.getmaskarray(expected)) + np.testing.assert_array_equal(np.ma.filled(got, 0), np.ma.filled(expected, 0)) + + +@pytest.mark.parametrize("parts", [None, (2, 2), (3, 4)]) +def test_a_masked_source_keeps_its_mask_when_the_view_is_empty(parts: Any) -> None: + """An empty result is still a result, and its type must not depend on the parts. + + An empty view is answered without reading the source at all, and that + shortcut reached for the array namespace's own `empty` — which knows nothing + about masks — so an unpartitioned empty view came back a plain array while + the same view partitioned came back masked. No cells either way, so nothing + about the values changed; the caller just got a different type depending on + how the read had been divided. + """ + data = np.ma.masked_greater(np.arange(12).reshape(3, 4), 7) + got = repartition(LazyArray(data), parts).lazy[:, 2:2].result() + assert isinstance(got, np.ma.MaskedArray), parts + assert np.asarray(got).shape == (3, 0), parts + + +def test_a_large_array_without_dask_refuses_to_claim_equality( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Above the digest limit the fallback must miss a cache rather than lie. + + Two arrays differing in one element used to token identically, because the + fallback described the shape and dtype and gave up on the contents. + """ + import sys + + monkeypatch.setitem(sys.modules, "dask.base", None) + big = np.zeros(1 << 19, dtype=np.int64) + other = big.copy() + other[0] = 1 + + assert LazyArray(big).__dask_tokenize__() != LazyArray(other).__dask_tokenize__() + assert LazyArray(big).__dask_tokenize__() != LazyArray(big).__dask_tokenize__() + + # Below the limit the contents are digested, so equal data still tokens alike. + small = np.zeros(8, dtype=np.int64) + assert LazyArray(small).__dask_tokenize__() == LazyArray(small.copy()).__dask_tokenize__() + + +# --------------------------------------------------------------------------- +# Completeness and partition spellings +# --------------------------------------------------------------------------- + + +def test_a_reversing_view_covers_its_parts() -> None: + """A reversal reads every cell of every box, back to front.""" + data = np.arange(48).reshape(8, 6) + forward = LazyArray(data).with_parts((2, 2)).lazy[:, :] + reversed_view = LazyArray(data).with_parts((2, 2)).lazy[::-1, ::-1] + assert [part.is_complete for part in reversed_view.parts()] == [ + part.is_complete for part in forward.parts() + ] + assert all(part.is_complete for part in reversed_view.parts()) + + +def test_a_strided_reversal_is_still_incomplete() -> None: + data = np.arange(48).reshape(8, 6) + view = LazyArray(data).with_parts((2, 2)).lazy[::-2, :] + assert not any(part.is_complete for part in view.parts()) + + +@pytest.mark.parametrize("parts", [((0,), (3,)), ((), (3,)), (1, 1), ((0, 0), (3,))]) +def test_a_zero_length_axis_accepts_every_spelling_of_no_chunks(parts: Any) -> None: + """`(0,)`, `(0, 0)`, `()` and a uniform shape all describe an axis with no cells.""" + data = np.zeros((0, 3)) + view = repartition(LazyArray(data), parts) + assert view.result().shape == (0, 3) + assert list(view.parts()) == [] + + +def test_a_zero_chunk_on_a_nonempty_axis_is_still_rejected() -> None: + with pytest.raises(ValueError, match="chunk sizes must be positive"): + LazyArray(np.zeros((4, 3))).with_parts_per_axis(((0, 4), (3,))) + + +@pytest.mark.parametrize( + "selection", + [ + (slice(None, None, -1), slice(None), slice(None)), + (slice(3, 1, -1), slice(None), slice(None)), + (slice(None, None, -2), slice(None, None, -1), slice(None)), + ], + ids=["reversed", "reversed-partial", "reversed-strided"], +) +def test_the_coverage_count_agrees_with_numpy_for_reversed_selections( + selection: tuple[Any, ...], +) -> None: + """The safety net behind `result()`'s coverage assertion, checked on its own. + + `_out_selection_cell_count` sizes a partition's `out_selection` without + materializing it, and `result()` trusts that count to decide whether the + walk covered the view. Nothing pinned it for a reversed slice, so dropping + its `start <= stop` guard — or wrapping the subtraction in `abs()` — left + the suite green. A net nobody tests only matters once something else breaks, + which is exactly when it needs to be right. + """ + data = reference() + view = LazyArray(data).with_parts((2, 2, 2)).lazy[selection] + out_shape = view.shape + for part in view.parts(): + counted = _out_selection_cell_count(part.out_selection, out_shape) + assert counted == np.empty(out_shape)[part.out_selection].size + + +@pytest.mark.parametrize( + ("selection", "out_shape", "expected"), + [ + (((slice(2, 5)),), (10,), 3), + # A backwards interval selects nothing. The fast path subtracts, which + # would make this negative and let an incomplete walk sum to the view's + # own size — so the count falls back to `range` whenever the interval is + # not a forward, in-bounds one. + (((slice(5, 2)),), (10,), 0), + # Counts from the end, to index 8 — past the stop, so nothing. + (((slice(-2, 5)),), (10,), 0), + ((slice(5, 2), slice(0, 3)), (10, 10), 0), + ], + ids=["forward", "backwards", "negative-start", "backwards-in-a-pair"], +) +def test_the_coverage_count_matches_numpy_for_intervals_the_fast_path_declines( + selection: tuple[Any, ...], out_shape: tuple[int, ...], expected: int +) -> None: + """The guard on `result()`'s safety net, exercised where the walk cannot reach it. + + A partition walk only ever produces concrete forward in-bounds intervals, so + the guard that keeps everything else off the subtraction fast path is not + reachable through `parts()` at all — which is why removing it left the whole + suite green. It is the net's own contract, so it is checked directly. + """ + counted = _out_selection_cell_count(selection, out_shape) + assert counted == np.empty(out_shape)[selection].size + assert counted == expected + + +def test_a_zero_dimensional_index_array_drops_its_axis_like_a_scalar() -> None: + """`a[np.array(2), :]` is `a[2, :]` in NumPy, and now here too. + + Only Python and NumPy integers counted as scalars, so a 0-d array fell + through to the fancy path and was widened into a length-1 index array — + keeping an axis NumPy drops. That was a third answer, agreeing with neither + NumPy nor eager zarr, which rejects it. + """ + data = np.arange(20).reshape(4, 5) + for mode, expected in ( + ("oindex", data[np.array(2), :]), + ("vindex", data[np.array(2), np.array(3)]), + ): + view = ( + LazyArray(data).lazy.oindex[np.array(2), slice(None)] + if mode == "oindex" + else LazyArray(data).lazy.vindex[np.array(2), np.array(3)] + ) + assert view.shape == expected.shape, mode + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=mode) + + +def test_a_multidimensional_array_in_an_orthogonal_selection_is_refused() -> None: + """The rule belongs to the selection, so the message speaks its vocabulary. + + Left to the engine, this surfaced as a rank complaint about an `index_array` + the caller never wrote — the transform layer's words for a mistake made two + layers above it. + """ + with pytest.raises(IndexError, match="must be 1-dimensional"): + LazyArray(np.arange(20).reshape(4, 5)).lazy.oindex[[[0, 1], [2, 3]], slice(None)] + + +def test_with_parts_rejects_a_bare_integer() -> None: + """Both partitioning methods document ValueError for malformed input.""" + view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + with pytest.raises(ValueError, match="one entry per dimension"): + view.with_parts(3) # type: ignore[arg-type] + with pytest.raises(ValueError, match="one entry per dimension"): + view.with_parts_per_axis(3) # type: ignore[arg-type] + + +def test_fancy_composition_over_an_empty_axis() -> None: + """Regression: composing fancy steps over an empty axis stays unpinned. + + The empty-domain branch of `compose` produces index arrays that are + singleton on every non-empty axis; pinning one to an axis it merely + broadcasts along made a later basic step index a size-1 axis positionally + and raise, deep inside a legal chain. + """ + base = np.empty((3, 0, 6), dtype=np.int64) + view = LazyArray(base).lazy.oindex[[2, 1], :, [5, 0, 3]] + assert view.shape == (2, 0, 3) + composed = view.lazy.oindex[[1, 0], :, [2, 2]] + assert composed.shape == (2, 0, 2) + scalar = composed.lazy.vindex[..., np.array(1)] + assert scalar.shape == (2, 0) + assert np.asarray(scalar.result()).shape == (2, 0) diff --git a/packages/zarr-indexing/tests/test_lazy_array_stateful.py b/packages/zarr-indexing/tests/test_lazy_array_stateful.py new file mode 100644 index 0000000000..4f5dadc1e4 --- /dev/null +++ b/packages/zarr-indexing/tests/test_lazy_array_stateful.py @@ -0,0 +1,114 @@ +"""This package's own use of the state machine it exports. + +`ChainedIndexingStateMachine` composes indexing steps onto a `LazyArray` and +checks each step against NumPy — see +`zarr_indexing.testing.stateful` for what the invariants assert and why. + +Two sources: a NumPy array, which exercises both built-in readers, and a real +zarr array, whose partitioning is discovered from the store rather than +declared. The zarr case runs a smaller budget: it reads through a store, and it +exercises the same code paths. + +This replaces a seeded `_random_chain` sweep in `test_lazy_array` that read +chained selections through `parts()`. That sweep did reach the states it was +meant to, but a rank-0 correlated view was absorbed by a reshape in `result()` +and mirrored into the sweep rather than read as a failure; asserting the +documented assembly literally makes that impossible to paper over. +`test_lazy_array` keeps its `result()`-based sweep, which is the deterministic +cross-flavor coverage this does not attempt. +""" + +from __future__ import annotations + +from typing import Any, ClassVar + +import numpy as np +import pytest +from hypothesis import settings + +from zarr_indexing import LazyArray, ReadContext +from zarr_indexing.reader import basic_reader, numpy_reader +from zarr_indexing.testing import ( + DEFAULT_SETTINGS, + ChainedIndexingStateMachine, + state_machine_test, + stateful, +) + + +class NumpyIndexing(ChainedIndexingStateMachine): + readers = (numpy_reader,) + + +TestNumpyIndexing = state_machine_test(NumpyIndexing) + + +class UnhashableReader: + __hash__ = None + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + basic_reader.read_into(source, context, out) + + def __eq__(self, other: object) -> bool: + return isinstance(other, UnhashableReader) + + +def test_reader_set_deduplicates_by_identity_without_hashing() -> None: + first = UnhashableReader() + second = UnhashableReader() + + readers = stateful._reader_set(LazyArray(np.arange(3)), (first, first, second)) + + assert readers[0] is basic_reader + assert readers[1] is first + assert readers[2] is second + assert len(readers) == 3 + + +class OneDimensionalIndexing(ChainedIndexingStateMachine): + """The same chains over a rank-1 source. + + The sorted one-dimensional fancy path in `chunk_resolution` is entered only + when both the input and output ranks are 1, and the output rank is the + *source's* — so the rank-3 default walls that path off from the machine + entirely, and from every downstream project told to subclass it. That path + is where reordering and duplicate coordinates are partitioned, which is the + corruption class this whole harness exists to catch. + """ + + data = np.arange(30, dtype=np.int64) + partitionings: ClassVar[tuple[Any, ...]] = (None, (4,), (30,), ((7, 8, 15),)) + + +TestOneDimensionalIndexing = state_machine_test(OneDimensionalIndexing) + + +class SingletonAxisIndexing(ChainedIndexingStateMachine): + """A source with an extent-1 axis, which the code must not read as a broadcast one. + + An index array's axis is a singleton either because the map broadcasts over + it or because the domain is genuinely one cell wide there, and the two are + told apart by the domain rather than the array. Nothing generated the second + kind. + """ + + data = np.arange(2 * 1 * 3, dtype=np.int64).reshape(2, 1, 3) + partitionings: ClassVar[tuple[Any, ...]] = (None, (1, 1, 1), (2, 1, 2)) + + +TestSingletonAxisIndexing = state_machine_test(SingletonAxisIndexing) + + +class ZarrIndexing(ChainedIndexingStateMachine): + """The same chains against a zarr array through the universal basic reader.""" + + def make_source(self, data: Any) -> Any: + zarr = pytest.importorskip("zarr") + array = zarr.create_array({}, shape=data.shape, chunks=(3, 2, 3), dtype=data.dtype) + array[:] = data + return array + + +TestZarrIndexing = state_machine_test( + ZarrIndexing, config=settings(DEFAULT_SETTINGS, max_examples=50) +) diff --git a/packages/zarr-indexing/tests/test_messages.py b/packages/zarr-indexing/tests/test_messages.py new file mode 100644 index 0000000000..2ebd41a263 --- /dev/null +++ b/packages/zarr-indexing/tests/test_messages.py @@ -0,0 +1,133 @@ +"""Message-layer tests beyond the vendored conformance corpus. + +The corpus (see `test_conformance.py`) covers the desugaring matrix and error +codes. These tests pin behaviors the corpus does not: `normalize` idempotence, +`parse_ndsel`, 64-bit boundary handling, and schema-valid-but-redundant maps. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from zarr_indexing.messages import NdselError, normalize_ndsel, parse_ndsel + +_MESSAGES = [ + {"kind": "point", "coords": [4, 7]}, + {"kind": "box", "inclusive_min": [0, 0], "exclusive_max": [3, 4]}, + {"kind": "box", "inclusive_min": [["-inf"], 0], "exclusive_max": [["+inf"], 4]}, + {"kind": "slice", "start": [5], "stop": [10], "step": [2]}, + {"kind": "points", "coords": [[1, 10], [2, 20]]}, + { + "kind": "transform", + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "output": [{"offset": 7}, {"input_dimension": 0, "stride": 2}, {"index_array": [1, 2, 3]}], + }, +] + + +@pytest.mark.parametrize("message", _MESSAGES) +def test_normalize_is_idempotent(message: dict[str, Any]) -> None: + once = normalize_ndsel(message) + twice = normalize_ndsel({"kind": "transform", **once}) + assert twice == once + + +@pytest.mark.parametrize("message", _MESSAGES) +def test_parse_returns_message_unchanged(message: dict[str, Any]) -> None: + assert parse_ndsel(message) == message + + +def test_parse_rejects_invalid() -> None: + with pytest.raises(NdselError) as excinfo: + parse_ndsel({"kind": "slice", "start": [0]}) + assert excinfo.value.reason == "invalid_json" + + +def test_constant_map_drops_redundant_stride() -> None: + # A constant map (no input_dimension, no index_array) is schema-valid even + # with a stray stride; it canonicalizes to offset-only. + result = normalize_ndsel( + {"kind": "transform", "input_rank": 0, "output": [{"offset": 5, "stride": 9}]} + ) + assert result["output"] == [{"offset": 5}] + + +def test_i64_min_and_max_round_trip() -> None: + i64_min, i64_max = -(2**63), 2**63 - 1 + result = normalize_ndsel({"kind": "point", "coords": [i64_min, i64_max]}) + assert result["output"] == [{"offset": i64_min}, {"offset": i64_max}] + + +def test_i64_overflow_rejected() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "point", "coords": [2**63]}) + assert excinfo.value.reason == "invalid_json" + + +def test_bool_in_output_offset_rejected() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "transform", "input_rank": 0, "output": [{"offset": True}]}) + assert excinfo.value.reason == "invalid_json" + + +def test_sentinel_not_allowed_in_plain_integer_position() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "point", "coords": ["+inf"]}) + assert excinfo.value.reason == "invalid_json" + + +def test_not_an_object_rejected() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel([1, 2, 3]) + assert excinfo.value.reason == "invalid_json" + + +def test_empty_string_kind_is_unknown_kind() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": ""}) + assert excinfo.value.reason == "unknown_kind" + + +class TestNegativeStep: + """ndsel 1.0-draft.2 section 5.3: one desugaring rule, both signs.""" + + def test_full_reverse(self) -> None: + """The spec's own worked example: reversing a length-20 axis.""" + body = normalize_ndsel({"kind": "slice", "start": [19], "stop": [-1], "step": [-1]}) + assert body["input_inclusive_min"] == [-19] + assert body["input_exclusive_max"] == [1] + assert body["output"] == [{"offset": 0, "stride": -1, "input_dimension": 0}] + + def test_trunc_origin_for_a_negative_step(self) -> None: + """`trunc(15 / -2) == -7`; `floor` would give -8.""" + body = normalize_ndsel({"kind": "slice", "start": [15], "stop": [5], "step": [-2]}) + assert body["input_inclusive_min"] == [-7] + assert body["input_exclusive_max"] == [-2] + assert body["output"] == [{"offset": 1, "stride": -2, "input_dimension": 0}] + + def test_empty_is_legal_at_any_coordinate(self) -> None: + body = normalize_ndsel({"kind": "slice", "start": [5], "stop": [5], "step": [-1]}) + assert body["input_inclusive_min"] == body["input_exclusive_max"] == [-5] + + @pytest.mark.parametrize( + "message", + [ + {"kind": "slice", "start": [9], "stop": [0]}, + {"kind": "slice", "start": [9], "stop": [0], "step": [2]}, + {"kind": "slice", "start": [5], "stop": [6], "step": [-1]}, + ], + ids=["unit-step", "positive-step", "negative-step"], + ) + def test_a_reversed_interval_is_an_error(self, message: dict[str, object]) -> None: + """Not clamped to empty: travelling the wrong way is a mistake, either sign.""" + with pytest.raises(NdselError) as excinfo: + normalize_ndsel(message) + assert excinfo.value.reason == "bounds_out_of_order" + + def test_zero_step_still_errors(self) -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "slice", "start": [0], "stop": [4], "step": [0]}) + assert excinfo.value.reason == "step_zero" diff --git a/packages/zarr-indexing/tests/test_ndsel_tensorstore.py b/packages/zarr-indexing/tests/test_ndsel_tensorstore.py new file mode 100644 index 0000000000..ab9465c8d1 --- /dev/null +++ b/packages/zarr-indexing/tests/test_ndsel_tensorstore.py @@ -0,0 +1,51 @@ +"""Cross-check canonical ndsel bodies against a real TensorStore. + +A normalized ndsel `transform` body is, field-for-field, a TensorStore +`IndexTransform` (minus the `kind` discriminator, which the canonical body never +carries). This test loads a handful of finite-bound canonical bodies into +`tensorstore.IndexTransform(json=...)` and confirms that TensorStore's own +`to_json()` re-loads, through our engine layer, into an equivalent transform. + +Skipped when tensorstore is not installed. Run it explicitly with: + + uv run --with tensorstore pytest \ + packages/zarr-indexing/tests/test_ndsel_tensorstore.py -q +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from zarr_indexing.transform import IndexTransform + +ts = pytest.importorskip("tensorstore") + + +def _canonical_transforms() -> list[IndexTransform]: + base = IndexTransform.from_shape((10, 20)) + return [ + base, # identity + base[2:8:2, :], # strided DimensionMap + identity + base[3, :], # integer index -> ConstantMap + DimensionMap + base.oindex[np.array([1, 5, 9]), :], # orthogonal index_array + IndexTransform.from_shape((10, 20, 30)).vindex[ + np.array([1, 3]), np.array([2, 4]), : + ], # correlated index_arrays + residual slice + ] + + +@pytest.mark.parametrize("transform", _canonical_transforms()) +def test_body_loads_in_tensorstore_and_round_trips(transform: IndexTransform) -> None: + body = transform.to_json() + + # (1) The canonical body loads directly as a TensorStore IndexTransform. + ts_transform = ts.IndexTransform(json=body) + + # (2) TensorStore's own JSON re-loads, through our engine, to an equivalent + # transform. Comparing via our canonical form normalizes away + # representational choices (index_array_bounds, default omissions) that + # both sides make differently but that denote the same selection. + ts_json = ts_transform.to_json() + reloaded = IndexTransform.from_json(ts_json) + assert reloaded.to_json() == transform.to_json() diff --git a/packages/zarr-indexing/tests/test_output_map.py b/packages/zarr-indexing/tests/test_output_map.py new file mode 100644 index 0000000000..d1e21efaa7 --- /dev/null +++ b/packages/zarr-indexing/tests/test_output_map.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +import pickle + +import numpy as np +import pytest + +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap + + +class TestConstantMap: + def test_construction(self) -> None: + m = ConstantMap(offset=42) + assert m.offset == 42 + + def test_default_offset(self) -> None: + m = ConstantMap() + assert m.offset == 0 + + def test_frozen(self) -> None: + m = ConstantMap(offset=5) + assert isinstance(m, ConstantMap) + + +class TestDimensionMap: + def test_construction(self) -> None: + m = DimensionMap(input_dimension=3, offset=5, stride=2) + assert m.input_dimension == 3 + assert m.offset == 5 + assert m.stride == 2 + + def test_defaults(self) -> None: + m = DimensionMap(input_dimension=0) + assert m.offset == 0 + assert m.stride == 1 + + def test_frozen(self) -> None: + m = DimensionMap(input_dimension=0) + assert isinstance(m, DimensionMap) + + +class TestArrayMap: + def test_construction(self) -> None: + arr = np.array([1, 3, 5], dtype=np.intp) + m = ArrayMap(index_array=arr, offset=10, stride=2) + assert m.offset == 10 + assert m.stride == 2 + np.testing.assert_array_equal(m.index_array, arr) + + def test_defaults(self) -> None: + arr = np.array([0, 1], dtype=np.intp) + m = ArrayMap(index_array=arr) + assert m.offset == 0 + assert m.stride == 1 + + def test_frozen(self) -> None: + arr = np.array([0], dtype=np.intp) + m = ArrayMap(index_array=arr) + assert isinstance(m, ArrayMap) + + def test_owns_index_array_and_keeps_hash_stable(self) -> None: + arr = np.array([1, 3, 5], dtype=np.intp) + m = ArrayMap(index_array=arr) + lookup = {m: "value"} + + arr[:] = 9 + + np.testing.assert_array_equal(m.index_array, [1, 3, 5]) + assert lookup[m] == "value" + + def test_pickle_round_trip_keeps_index_array_read_only(self) -> None: + restored = pickle.loads(pickle.dumps(ArrayMap(index_array=np.array([1, 3, 5])))) + + assert not restored.index_array.flags.writeable + with pytest.raises(ValueError, match="read-only"): + restored.index_array[0] = 9 + + def test_index_array_cannot_be_made_writeable(self) -> None: + m = ArrayMap(index_array=np.array([1, 3, 5])) + + with pytest.raises(ValueError): + m.index_array.flags.writeable = True + + def test_equal_array_maps_have_equal_hashes_across_integer_dtypes(self) -> None: + left = ArrayMap(np.array([1, 2], dtype=np.int32)) + right = ArrayMap(np.array([1, 2], dtype=np.int64)) + assert left == right + assert hash(left) == hash(right) + assert left.index_array.dtype == np.dtype(np.intp) + + def test_rejects_non_integer_index_array(self) -> None: + with pytest.raises(TypeError, match="index_array must have an integer dtype"): + ArrayMap(np.array([1.5, 2.0], dtype=np.float64)) + + def test_rejects_unsigned_index_array_value_outside_intp(self) -> None: + outside_intp = np.array([np.iinfo(np.uint64).max], dtype=np.uint64) + + with pytest.raises(OverflowError, match="outside np.intp range"): + ArrayMap(outside_intp) diff --git a/packages/zarr-indexing/tests/test_reader.py b/packages/zarr-indexing/tests/test_reader.py new file mode 100644 index 0000000000..11241a316c --- /dev/null +++ b/packages/zarr-indexing/tests/test_reader.py @@ -0,0 +1,514 @@ +from __future__ import annotations + +import math +from typing import TYPE_CHECKING, Any, get_type_hints + +import numpy as np +import numpy.typing as npt +import pytest + +import zarr_indexing.reader as reader_module +from zarr_indexing import ( + ArrayMap, + ChunkProjection, + ConstantMap, + DimensionMap, + IndexDomain, + IndexTransform, + LazyArray, + ReadContext, + plan_chunks, +) +from zarr_indexing.grid import dimension_grids_from_chunks +from zarr_indexing.reader import basic_reader, numpy_reader, unit_step_reader + +if TYPE_CHECKING: + from collections.abc import Callable + + +class BasicOnlySource: + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self.data = data + self.keys: list[tuple[Any, ...]] = [] + + @property + def shape(self) -> tuple[int, ...]: + return self.data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self.data.dtype + + def __getitem__(self, key: tuple[Any, ...]) -> np.ndarray[Any, Any]: + assert all(isinstance(item, slice) and (item.step or 1) > 0 for item in key) + self.keys.append(key) + return self.data[key] + + +class UnitStepOnlySource(BasicOnlySource): + """A source that rejects everything but ascending unit-step slices.""" + + def __getitem__(self, key: tuple[Any, ...]) -> np.ndarray[Any, Any]: + assert all( + isinstance(item, slice) and item.step == 1 and 0 <= item.start <= item.stop <= size + for item, size in zip(key, self.data.shape, strict=True) + ) + self.keys.append(key) + return self.data[key] + + +SOURCE = np.arange(6 * 7 * 8).reshape(6, 7, 8) +BASE = IndexTransform.from_shape(SOURCE.shape) + + +SUCCESSFUL_CONTRACT_CASES = ( + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[3], + (3,), + np.zeros((1, 0), dtype=np.intp), + np.array([[3]], dtype=np.intp), + np.array(3), + lambda array: array.lazy[3], + id="constant", + ), + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[1:8:2], + (3,), + np.array([[0], [1], [2], [3]], dtype=np.intp), + np.array([[1], [3], [5], [7]], dtype=np.intp), + np.array([1, 3, 5, 7]), + lambda array: array.lazy[1:8:2], + id="positive-affine", + ), + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[::-2], + (3,), + np.array([[-3], [-2], [-1], [0]], dtype=np.intp), + np.array([[7], [5], [3], [1]], dtype=np.intp), + np.array([7, 5, 3, 1]), + lambda array: array.lazy[::-2], + id="negative-affine", + ), + pytest.param( + np.arange(8), + IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=2, stride=0),), + ), + (3,), + np.array([[0], [1], [2]], dtype=np.intp), + np.array([[2], [2], [2]], dtype=np.intp), + np.array([2, 2, 2]), + lambda array: array.lazy.oindex[[2, 2, 2]], + id="zero-affine", + ), + pytest.param( + np.arange(20).reshape(4, 5), + IndexTransform.from_shape((4, 5)).oindex[[3, 1, 1], [4, 0]], + (2, 3), + np.array([[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]], dtype=np.intp), + np.array([[3, 4], [3, 0], [1, 4], [1, 0], [1, 4], [1, 0]], dtype=np.intp), + np.array([[19, 15], [9, 5], [9, 5]]), + lambda array: array.lazy.oindex[[3, 1, 1], [4, 0]], + id="orthogonal-array", + ), + pytest.param( + np.arange(20).reshape(4, 5), + IndexTransform.from_shape((4, 5)).vindex[[3, 1, 1], [4, 0, 4]], + (2, 3), + np.array([[0], [1], [2]], dtype=np.intp), + np.array([[3, 4], [1, 0], [1, 4]], dtype=np.intp), + np.array([19, 5, 9]), + lambda array: array.lazy.vindex[[3, 1, 1], [4, 0, 4]], + id="correlated-array", + ), + pytest.param( + np.arange(8), + IndexTransform( + domain=IndexDomain((4,), (7,)), + output=(DimensionMap(input_dimension=0, offset=-3, stride=1),), + ), + (3,), + np.array([[4], [5], [6]], dtype=np.intp), + np.array([[1], [2], [3]], dtype=np.intp), + np.array([1, 2, 3]), + None, + id="non-zero-origin", + ), + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[2:2], + (3,), + np.empty((0, 1), dtype=np.intp), + np.empty((0, 1), dtype=np.intp), + np.array([], dtype=np.intp), + lambda array: array.lazy[2:2], + id="empty", + ), +) + + +@pytest.mark.parametrize( + ( + "source_data", + "transform", + "chunk_shape", + "request_coordinates", + "storage_coordinates", + "expected_values", + "lazy_selection", + ), + SUCCESSFUL_CONTRACT_CASES, +) +def test_successful_transform_contract_across_planning_readers_and_lazy_array( + source_data: np.ndarray[Any, Any], + transform: IndexTransform, + chunk_shape: tuple[int, ...], + request_coordinates: npt.NDArray[np.intp], + storage_coordinates: npt.NDArray[np.intp], + expected_values: np.ndarray[Any, Any], + lazy_selection: Callable[[LazyArray], LazyArray] | None, +) -> None: + """One literal matrix keeps transform, planning, readers, and wrappers aligned.""" + np.testing.assert_array_equal(transform.apply_many(request_coordinates), storage_coordinates) + + grids = dimension_grids_from_chunks(chunk_shape, source_data.shape) + reconstructed_pairs = [ + ( + tuple(projection.cell_transform.apply(cell_coordinate)), + tuple( + local_coordinate + chunk_origin + for local_coordinate, chunk_origin in zip( + projection.chunk_transform.apply(cell_coordinate), + projection.chunk_domain.inclusive_min, + strict=True, + ) + ), + ) + for projection in plan_chunks(transform, grids) + for cell_coordinate in _domain_coordinates(projection.cell_transform.domain) + ] + expected_pairs = list( + zip( + map(tuple, request_coordinates.tolist()), + map(tuple, storage_coordinates.tolist()), + strict=True, + ) + ) + assert sorted(reconstructed_pairs) == sorted(expected_pairs) + + for reader, source in ( + (basic_reader, BasicOnlySource(source_data)), + (numpy_reader, source_data), + (unit_step_reader, UnitStepOnlySource(source_data)), + ): + out = np.empty(transform.domain.shape, dtype=source_data.dtype) + assert reader.read_into(source, ReadContext(transform), out) is None + np.testing.assert_array_equal(out, expected_values) + + if lazy_selection is not None: + view = lazy_selection(LazyArray.from_numpy(source_data).with_parts(chunk_shape)) + np.testing.assert_array_equal(view.result(), expected_values) + + +def _domain_coordinates(domain: IndexDomain) -> list[tuple[int, ...]]: + return [ + tuple( + position + origin for position, origin in zip(index, domain.inclusive_min, strict=True) + ) + for index in np.ndindex(*domain.shape) + ] + + +def test_read_context_public_annotations_resolve() -> None: + assert get_type_hints(ReadContext)["projection"] == ChunkProjection | None + + +READER_CASES = ( + pytest.param( + SOURCE, + BASE[1:6:2, 2, ::-2], + np.array( + [ + [79, 77, 75, 73], + [191, 189, 187, 185], + [303, 301, 299, 297], + ] + ), + id="strided-reversed-nonzero-origin", + ), + pytest.param( + SOURCE, + BASE.oindex[[5, 1, 1], slice(1, 6), [7, 2]], + np.array( + [ + [[295, 290], [303, 298], [311, 306], [319, 314], [327, 322]], + [[71, 66], [79, 74], [87, 82], [95, 90], [103, 98]], + [[71, 66], [79, 74], [87, 82], [95, 90], [103, 98]], + ] + ), + id="orthogonal-nonzero-origin", + ), + pytest.param( + SOURCE, + BASE.vindex[np.array([[5], [1]]), np.array([[2, 4, 0]])], + np.array( + [ + [ + [296, 297, 298, 299, 300, 301, 302, 303], + [312, 313, 314, 315, 316, 317, 318, 319], + [280, 281, 282, 283, 284, 285, 286, 287], + ], + [ + [72, 73, 74, 75, 76, 77, 78, 79], + [88, 89, 90, 91, 92, 93, 94, 95], + [56, 57, 58, 59, 60, 61, 62, 63], + ], + ] + ), + id="correlated-broadcast", + ), + pytest.param( + SOURCE, + BASE.vindex[[5, 1], [2, 2]], + np.array( + [ + [296, 297, 298, 299, 300, 301, 302, 303], + [72, 73, 74, 75, 76, 77, 78, 79], + ] + ), + id="correlated-vector", + ), + pytest.param( + SOURCE, + BASE[:, 0:0, :], + np.empty((6, 0, 8), dtype=SOURCE.dtype), + id="empty", + ), + pytest.param(SOURCE, BASE[2, 3, 4], np.array(140), id="scalar"), + pytest.param( + np.arange(8), + IndexTransform( + domain=IndexDomain((4,), (7,)), + output=(DimensionMap(input_dimension=0, offset=2, stride=0),), + ), + np.array([2, 2, 2]), + id="zero-stride-nonzero-origin", + ), +) + + +@pytest.mark.parametrize(("source_data", "transform", "expected"), READER_CASES) +@pytest.mark.parametrize("reader_name", ["basic", "numpy", "unit-step"]) +def test_builtin_readers_match_the_transform( + source_data: np.ndarray[Any, Any], + transform: IndexTransform, + expected: np.ndarray[Any, Any], + reader_name: str, +) -> None: + out = np.empty(transform.domain.shape, dtype=source_data.dtype) + if reader_name == "basic": + source = BasicOnlySource(source_data) + result = basic_reader.read_into(source, ReadContext(transform), out) + assert len(source.keys) == 1 + elif reader_name == "unit-step": + source = UnitStepOnlySource(source_data) + result = unit_step_reader.read_into(source, ReadContext(transform), out) + assert len(source.keys) == 1 + else: + result = numpy_reader.read_into(source_data, ReadContext(transform), out) + assert result is None + np.testing.assert_array_equal(out, expected) + + +@pytest.mark.parametrize("reader_name", ["basic", "numpy", "unit-step"]) +def test_builtin_readers_share_transform_affine_overflow(reader_name: str) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + + with pytest.raises(OverflowError, match="outside np.intp"): + transform.apply_many(np.array([[0]], dtype=np.intp)) + + out = np.empty(transform.domain.shape, dtype=np.intp) + if reader_name == "basic": + with pytest.raises(OverflowError, match="outside np.intp"): + basic_reader.read_into(BasicOnlySource(np.arange(1)), ReadContext(transform), out) + elif reader_name == "unit-step": + with pytest.raises(OverflowError, match="outside np.intp"): + unit_step_reader.read_into( + UnitStepOnlySource(np.arange(1)), ReadContext(transform), out + ) + else: + with pytest.raises(OverflowError, match="outside np.intp"): + numpy_reader.read_into(np.arange(1), ReadContext(transform), out) + + +def test_empty_domain_composed_fancy_transform_reads_as_empty() -> None: + """An ArrayMap composed over an empty domain resolves like any other map. + + The composed map is legitimately empty along the vanished axis; the + resolvers used to fail reshaping it instead of noticing that an empty + domain selects nothing. + """ + source_data = np.arange(6).reshape(2, 3) + view = LazyArray.from_numpy(source_data).lazy.oindex[slice(0, 0), np.array([2, 1, 2, 0])] + transform = view.lazy.oindex[slice(None), np.array([1, 3, 1])].transform + assert transform.domain.shape == (0, 3) + + for reader, source in ( + (basic_reader, BasicOnlySource(source_data)), + (numpy_reader, source_data), + (unit_step_reader, UnitStepOnlySource(source_data)), + ): + out = np.empty(transform.domain.shape, dtype=source_data.dtype) + assert reader.read_into(source, ReadContext(transform), out) is None + + +def test_unit_step_reader_reads_through_lazy_array() -> None: + """The full dialect resolves through a source that only accepts unit-step slices. + + `UnitStepOnlySource` asserts the shape of every key it receives, so each + selection here also proves no strided, descending, or non-slice key + reached the source — partitioned and unpartitioned alike. + """ + selections: tuple[Callable[[LazyArray], LazyArray], ...] = ( + lambda v: v.lazy[1:5, ::2, ::-1], + lambda v: v.lazy[5:1:-2, None, 3, ::3], + lambda v: v.lazy.oindex[[3, 0, 3], ::-2, [7, 7]], + lambda v: v.lazy.vindex[np.array([[0, 5]]), np.array([[6], [0]]), 2], + lambda v: v.lazy[2:2, :, ::-1], + lambda v: v.lazy[::5, 6, 1:8:4], + ) + for select in selections: + for parts in (None, (2, 3, 8), (6, 7, 1)): + source = UnitStepOnlySource(SOURCE) + view = LazyArray(source).with_reader(unit_step_reader) + if parts is not None: + view = view.with_parts(parts) + expected = select(LazyArray.from_numpy(SOURCE)).result() + np.testing.assert_array_equal(select(view).result(), expected) + # An empty view allocates without reading; every other one must read. + assert (len(source.keys) > 0) == (expected.size > 0) + + +def test_constant_outside_intp_has_transform_planner_reader_error_parity() -> None: + outside_intp = int(np.iinfo(np.intp).max) + 1 + transform = IndexTransform( + domain=IndexDomain((), ()), + output=(ConstantMap(offset=outside_intp),), + ) + + with pytest.raises(OverflowError, match="outside np.intp range"): + transform.apply_many(np.zeros((1, 0), dtype=np.intp)) + + grids = dimension_grids_from_chunks((1,), (1,)) + with pytest.raises(OverflowError, match="outside np.intp range"): + list(plan_chunks(transform, grids)) + + for reader, source in ( + (basic_reader, BasicOnlySource(np.arange(1))), + (numpy_reader, np.arange(1)), + ): + with pytest.raises(OverflowError, match="outside np.intp range"): + reader.read_into(source, ReadContext(transform), np.empty((), dtype=np.intp)) + + +def test_numpy_reader_narrows_basic_slab_before_gather( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = np.arange(1_000_000).reshape(1000, 1000) + transform = IndexTransform.from_shape(source.shape).oindex[:10, [0, 999]] + seen: list[tuple[int, ...]] = [] + real_take = reader_module._take # pyright: ignore[reportPrivateUsage] + + def recording_take(array: Any, indices: npt.NDArray[np.intp], axis: int) -> Any: + seen.append(tuple(int(value) for value in array.shape)) + return real_take(array, indices, axis) + + monkeypatch.setattr(reader_module, "_take", recording_take) + out = np.empty(transform.domain.shape, dtype=source.dtype) + assert numpy_reader.read_into(source, ReadContext(transform), out) is None + assert out.shape == (10, 2) + np.testing.assert_array_equal( + out, + np.array( + [ + [0, 999], + [1000, 1999], + [2000, 2999], + [3000, 3999], + [4000, 4999], + [5000, 5999], + [6000, 6999], + [7000, 7999], + [8000, 8999], + [9000, 9999], + ] + ), + ) + assert seen + assert all(math.prod(shape) <= 20_000 for shape in seen), seen + + +def test_numpy_reader_preserves_a_mask_in_the_supplied_buffer() -> None: + source = np.ma.masked_greater(np.arange(12).reshape(3, 4), 7) + transform = IndexTransform.from_shape(source.shape)[:, 1:] + out = np.ma.masked_all(transform.domain.shape, dtype=source.dtype) + assert numpy_reader.read_into(source, ReadContext(transform), out) is None + np.testing.assert_array_equal(np.ma.getmaskarray(out), np.ma.getmaskarray(source[:, 1:])) + np.testing.assert_array_equal(np.ma.filled(out, 0), np.ma.filled(source[:, 1:], 0)) + + +# --------------------------------------------------------------------------- +# Diagonal gathers — output maps sharing an input axis +# --------------------------------------------------------------------------- + + +def test_reading_a_diagonal_gather_transform() -> None: + """Two index arrays bound to the same input axis resolve pointwise. + + No selection dialect produces this transform — it is the hand-built + diagonal-extraction form — but the reader resolves it through the same + pointwise path as a correlated gather. + """ + data = np.arange(30).reshape(5, 6) + rows = np.array([4, 0, 2]) + cols = np.array([1, 5, 2]) + transform = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=( + ArrayMap(index_array=rows), + ArrayMap(index_array=cols), + ), + ) + + out = np.empty((3,), dtype=data.dtype) + basic_reader.read_into(data, ReadContext(transform), out) + np.testing.assert_array_equal(out, data[rows, cols]) + + out = np.empty((3,), dtype=data.dtype) + numpy_reader.read_into(data, ReadContext(transform), out) + np.testing.assert_array_equal(out, data[rows, cols]) + + +def test_reading_a_diagonal_gather_with_a_residual_slice_axis() -> None: + data = np.arange(60).reshape(5, 6, 2) + rows = np.array([[4], [0], [2]]) + cols = np.array([[1], [5], [2]]) + transform = IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=( + ArrayMap(index_array=rows), + ArrayMap(index_array=cols), + DimensionMap(input_dimension=1), + ), + ) + + out = np.empty((3, 2), dtype=data.dtype) + basic_reader.read_into(data, ReadContext(transform), out) + np.testing.assert_array_equal(out, data[rows[:, 0], cols[:, 0], :]) diff --git a/packages/zarr-indexing/tests/test_tensorstore_parity.py b/packages/zarr-indexing/tests/test_tensorstore_parity.py new file mode 100644 index 0000000000..9f4123fc02 --- /dev/null +++ b/packages/zarr-indexing/tests/test_tensorstore_parity.py @@ -0,0 +1,435 @@ +"""TensorStore-parity oracle tests for IndexTransform semantics. + +Every case in this module was executed against tensorstore 0.1.84 (see the +lazy-indexing design notes): the expected domains, values, and error conditions +are TensorStore's observed behavior, which zarr's lazy indexing matches by +design. Core rules pinned here: + +- **Domain preservation**: a step-1 slice keeps the literal coordinates of the + selected interval (`a[2:10]` has domain `[2, 10)`); nothing re-zeros + implicitly. Re-zeroing is explicit via `translate_to`. +- **Strided-domain rule**: for step ``k``, ``origin = trunc(start/k)`` (rounded + toward zero), ``shape = ceil((stop - start)/k)``, and coordinate + ``origin + i`` maps to base cell ``start + i*k``. +- **Strict containment**: non-empty slice intervals must lie within the domain + — no clamping, no negative-wrapping; empty intervals are valid anywhere; + reversed non-empty bounds are an error, not an empty result. +- **Fancy-dim rule**: index-array dims get fresh explicit ``[0, n)`` domains; + index-array values are absolute domain coordinates. +- **Translate rules**: ``translate_by``/``translate_to`` shift the input domain + while preserving which cells are addressed. +""" + +from __future__ import annotations + +from typing import ClassVar + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import IndexTransform + + +def _identity(lo: int, hi: int) -> IndexTransform: + """Identity transform over the 1-D domain [lo, hi).""" + return IndexTransform.identity(IndexDomain(inclusive_min=(lo,), exclusive_max=(hi,))) + + +def _a() -> IndexTransform: + """The oracle's base fixture: identity over [0, 12).""" + return _identity(0, 12) + + +def _w() -> IndexTransform: + """The oracle's translated fixture: identity over [-10, 2), cell c -> base c + 10.""" + return _a().translate_domain_by((-10,)) + + +def _dim(t: IndexTransform) -> DimensionMap: + m = t.output[0] + assert isinstance(m, DimensionMap) + return m + + +def _base_cells(t: IndexTransform) -> list[int]: + """The base cells a 1-D single-DimensionMap transform addresses, in order.""" + m = _dim(t) + lo, hi = t.domain.inclusive_min[0], t.domain.exclusive_max[0] + return [m.offset + m.stride * c for c in range(lo, hi)] + + +class TestDomainPreservation: + """Oracle section 1-2: step-1 slices keep literal coordinates.""" + + def test_slice_preserves_domain(self) -> None: + t = _a()[2:10] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((2,), (10,)) + assert _base_cells(t) == list(range(2, 10)) + + def test_integer_on_preserved_domain_is_a_coordinate(self) -> None: + v = _a()[2:10] + assert isinstance(v[3].output[0], ConstantMap) + assert v[3].output[0].offset == 3 # coordinate 3 = base cell 3 + assert v[2].output[0].offset == 2 + assert v[9].output[0].offset == 9 + + @pytest.mark.parametrize("bad", [0, -1, 10]) + def test_out_of_domain_integer_raises(self, bad: int) -> None: + with pytest.raises(BoundsCheckError, match=r"valid indices \[2, 10\)"): + _a()[2:10][bad] + + def test_slice_of_slice_is_literal(self) -> None: + v = _a()[2:10] + t = v[3:7] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((3,), (7,)) + assert _base_cells(t) == [3, 4, 5, 6] + + def test_ellipsis_preserves_domain(self) -> None: + v = _a()[2:10] + t = v[...] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((2,), (10,)) + + +class TestNegativeOriginDomain: + """Oracle section 3: on domain [-10, 2), -1 is just another index.""" + + def test_translated_domain(self) -> None: + w = _w() + assert (w.domain.inclusive_min, w.domain.exclusive_max) == ((-10,), (2,)) + assert _base_cells(w) == list(range(12)) + + @pytest.mark.parametrize(("coord", "base"), [(-5, 5), (-10, 0), (-1, 9), (1, 11)]) + def test_negative_coordinates_address_cells(self, coord: int, base: int) -> None: + t = _w()[coord] + assert isinstance(t.output[0], ConstantMap) + assert t.output[0].offset == base + + @pytest.mark.parametrize("bad", [-11, 2]) + def test_out_of_domain_raises(self, bad: int) -> None: + with pytest.raises(BoundsCheckError, match=r"valid indices \[-10, 2\)"): + _w()[bad] + + def test_negative_slice_bounds_are_coordinates(self) -> None: + t = _w()[-5:] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((-5,), (2,)) + assert _base_cells(t) == [5, 6, 7, 8, 9, 10, 11] + t2 = _w()[-5:-2] + assert (t2.domain.inclusive_min, t2.domain.exclusive_max) == ((-5,), (-2,)) + assert _base_cells(t2) == [5, 6, 7] + + +class TestStridedDomains: + """Oracle section 5: origin = trunc(start/step), coord origin+i -> start + i*step.""" + + # (slice, expected (lo, hi), expected base cells) — verbatim oracle rows. + CASES: ClassVar[list[tuple[slice, tuple[int, int], list[int]]]] = [ + (slice(1, 10, 3), (0, 3), [1, 4, 7]), + (slice(None, None, 2), (0, 6), [0, 2, 4, 6, 8, 10]), + (slice(2, 11, 3), (0, 3), [2, 5, 8]), + (slice(0, 12, 4), (0, 3), [0, 4, 8]), + (slice(5, 12, 2), (2, 6), [5, 7, 9, 11]), + (slice(6, 12, 2), (3, 6), [6, 8, 10]), + (slice(7, 12, 3), (2, 4), [7, 10]), + ] + + @pytest.mark.parametrize(("sel", "dom", "cells"), CASES) + def test_strided_domain_and_cells( + self, sel: slice, dom: tuple[int, int], cells: list[int] + ) -> None: + t = _a()[sel] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == dom + assert _base_cells(t) == cells + + def test_strided_on_negative_origin(self) -> None: + # w[-9:2:2] -> domain [-4, 2), base cells 1,3,5,7,9,11 + t = _w()[-9:2:2] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == (-4, 2) + assert _base_cells(t) == [1, 3, 5, 7, 9, 11] + # w[::2] -> domain [-5, 1), base cells 0,2,4,6,8,10 + t2 = _w()[::2] + assert (t2.domain.inclusive_min[0], t2.domain.exclusive_max[0]) == (-5, 1) + assert _base_cells(t2) == [0, 2, 4, 6, 8, 10] + + def test_strided_composition(self) -> None: + s = _a()[1:10:3] # domain [0, 3), cells 1,4,7 + assert [s[k].output[0].offset for k in range(3)] == [1, 4, 7] + t = s[1:3] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == (1, 3) + assert _base_cells(t) == [4, 7] + t2 = _a()[::2][1:4] + assert (t2.domain.inclusive_min[0], t2.domain.exclusive_max[0]) == (1, 4) + assert _base_cells(t2) == [2, 4, 6] + t3 = _a()[::2][::2] + assert (t3.domain.inclusive_min[0], t3.domain.exclusive_max[0]) == (0, 3) + assert _base_cells(t3) == [0, 4, 8] + + @pytest.mark.parametrize("bad", [-2, -1, 3, 4]) + def test_strided_bounds(self, bad: int) -> None: + with pytest.raises(BoundsCheckError, match=r"valid indices \[0, 3\)"): + _a()[1:10:3][bad] + + +class TestStrictContainment: + """Oracle section 11: no clamping, no wrapping; empty intervals valid anywhere.""" + + @pytest.mark.parametrize( + "sel", + [ + slice(5, 100), + slice(-3, None), + slice(-3, -1), + slice(0, 13), + slice(12, 14), + slice(100, 200), + ], + ) + def test_uncontained_interval_raises(self, sel: slice) -> None: + with pytest.raises(BoundsCheckError, match="not contained"): + _a()[sel] + + def test_uncontained_on_negative_origin(self) -> None: + with pytest.raises(BoundsCheckError, match="not contained"): + _w()[-20:] + + @pytest.mark.parametrize( + ("sel", "pos"), [(slice(5, 5), 5), (slice(0, 0), 0), (slice(13, 13), 13)] + ) + def test_empty_interval_valid_anywhere(self, sel: slice, pos: int) -> None: + t = _a()[sel] + assert t.domain.shape == (0,) + assert t.domain.inclusive_min[0] == pos + + @pytest.mark.parametrize("sel", [slice(5, 2), slice(100, 50)]) + def test_reversed_bounds_raise(self, sel: slice) -> None: + with pytest.raises(IndexError, match="valid.*interval|interval"): + _a()[sel] + + +class TestNegativeStep: + """Section 1 of the negative-step study: one desugaring rule, both signs. + + Every expectation below is TensorStore 0.1.84's recorded output (study + sections 1.3-1.5), which an exhaustive 32,980-case sweep found zero + disagreements with. + """ + + # (domain, slice, expected domain, expected offset, expected stride, cells) + RECORDED: ClassVar[list[tuple[tuple[int, int], slice, tuple[int, int], int, int]]] = [ + ((0, 20), slice(15, 5, -1), (-15, -5), 0, -1), + ((0, 20), slice(15, 5, -2), (-7, -2), 1, -2), + ((0, 20), slice(15, 4, -2), (-7, -1), 1, -2), + ((0, 20), slice(None, None, -1), (-19, 1), 0, -1), + ((0, 20), slice(None, None, -2), (-9, 1), 1, -2), + ((0, 20), slice(5, None, -1), (-5, 1), 0, -1), + ((0, 20), slice(None, 5, -1), (-19, -5), 0, -1), + ((0, 20), slice(5, 5, -1), (-5, -5), 0, -1), + ((0, 20), slice(5, 4, -1), (-5, -4), 0, -1), + ((0, 20), slice(5, 4, -3), (-1, 0), 2, -3), + ((0, 20), slice(15, 5, -4), (-3, 0), 3, -4), + ((0, 20), slice(15, 5, -7), (-2, 0), 1, -7), + ((5, 25), slice(None, None, -2), (-12, -2), 0, -2), + ((-10, 10), slice(-1, -6, -2), (0, 3), -1, -2), + ((-10, 10), slice(-2, -9, -3), (0, 3), -2, -3), + ] + + @pytest.mark.parametrize( + ("domain", "sel", "expected_domain", "offset", "stride"), + RECORDED, + ids=[f"{d}{s}" for d, s, _, _, _ in RECORDED], + ) + def test_recorded_desugaring( + self, + domain: tuple[int, int], + sel: slice, + expected_domain: tuple[int, int], + offset: int, + stride: int, + ) -> None: + t = _identity(*domain)[sel] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == expected_domain + m = _dim(t) + assert (m.offset, m.stride) == (offset, stride) + + @pytest.mark.parametrize( + ("domain", "sel", "cells"), + [ + ((0, 20), slice(15, 5, -1), list(range(15, 5, -1))), + ((0, 20), slice(15, 5, -2), [15, 13, 11, 9, 7]), + ((0, 20), slice(None, None, -1), list(range(19, -1, -1))), + ((0, 20), slice(15, 5, -7), [15, 8]), + ((5, 25), slice(None, None, -2), list(range(24, 4, -2))), + ((-10, 10), slice(-1, -6, -2), [-1, -3, -5]), + ((-10, 10), slice(-2, -9, -3), [-2, -5, -8]), + ], + ) + def test_recorded_cells(self, domain: tuple[int, int], sel: slice, cells: list[int]) -> None: + assert _base_cells(_identity(*domain)[sel]) == cells + + def test_trunc_not_floor_or_ceil(self) -> None: + """The three rows of study section 1.2 that discriminate the rounding.""" + # floor would give -8 here, trunc gives -7. + assert _identity(0, 20)[15:5:-2].domain.inclusive_min[0] == -7 + # ceil would give 1 for both of these; trunc gives 0. + assert _identity(-10, 10)[-1:-6:-2].domain.inclusive_min[0] == 0 + assert _identity(-10, 10)[-2:-9:-3].domain.inclusive_min[0] == 0 + + @pytest.mark.parametrize("sel", [slice(5, 15, -1), slice(5, 6, -1)]) + def test_inverted_interval_raises(self, sel: slice) -> None: + with pytest.raises(IndexError, match="valid.*interval"): + _identity(0, 20)[sel] + + @pytest.mark.parametrize("sel", [slice(20, 0, -1), slice(20, 19, -1), slice(15, -5, -1)]) + def test_uncontained_interval_raises(self, sel: slice) -> None: + with pytest.raises(BoundsCheckError, match="not contained"): + _identity(0, 20)[sel] + + def test_zero_step_raises(self) -> None: + with pytest.raises(IndexError, match="step must not be zero"): + _identity(0, 20)[15:5:0] + + def test_empty_interval_legal_outside_the_domain(self) -> None: + t = _identity(0, 20)[25:25:-1] + assert t.domain.shape == (0,) + assert t.domain.inclusive_min[0] == -25 + + @pytest.mark.parametrize( + ("domain", "first", "second", "expected_domain", "offset", "stride", "cells"), + [ + # Study section 1.5, recorded verbatim. Each row applies `second` + # to the view `first` produced — strides multiply, and a double + # reverse recovers the identity. + ( + (0, 20), + slice(0, 20, 2), + slice(None, None, -1), + (-9, 1), + 0, + -2, + list(range(18, -2, -2)), + ), + ((0, 20), slice(0, 20, 2), slice(None, None, -2), (-4, 1), 2, -4, [18, 14, 10, 6, 2]), + ( + (0, 20), + slice(None, None, -1), + slice(None, None, -1), + (0, 20), + 0, + 1, + list(range(20)), + ), + ( + (0, 20), + slice(None, None, -1), + slice(None, None, 2), + (-9, 1), + 1, + -2, + list(range(19, -1, -2)), + ), + ( + (-10, 10), + slice(None, None, -1), + slice(None, None, -3), + (-3, 4), + -1, + 3, + [-10, -7, -4, -1, 2, 5, 8], + ), + ], + ids=[ + "strided-then-reverse", + "strided-then-reverse-by-two", + "double-reverse-is-identity", + "reverse-then-strided", + "reverse-then-strided-on-negative-origin", + ], + ) + def test_recorded_composition( + self, + domain: tuple[int, int], + first: slice, + second: slice, + expected_domain: tuple[int, int], + offset: int, + stride: int, + cells: list[int], + ) -> None: + t = _identity(*domain)[first][second] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == expected_domain + m = _dim(t) + assert (m.offset, m.stride) == (offset, stride) + assert _base_cells(t) == cells + + def test_negative_step_over_an_index_array_reverses_it(self) -> None: + """Study section 1.5: a reversing step materializes, it does not stride. + + Recorded: `oindex[[3, 1, 2]]` then `[2:-1:-1]` gives index array + `[[2], [1], [3]]` over domain `[-2, 1)`. + """ + base = IndexTransform.identity(IndexDomain(inclusive_min=(0, 0), exclusive_max=(4, 5))) + gathered = base.oindex[np.array([3, 1, 2]), slice(None)] + reversed_view = gathered[2:-1:-1, :] + + assert reversed_view.domain.inclusive_min[0] == -2 + assert reversed_view.domain.exclusive_max[0] == 1 + m = reversed_view.output[0] + assert isinstance(m, ArrayMap) + np.testing.assert_array_equal(m.index_array.reshape(-1), np.array([2, 1, 3])) + + +class TestTranslate: + """Oracle sections 4 and 12: translate_by / translate_to preserve the cell mapping.""" + + def test_translate_to_zero(self) -> None: + t = _a()[2:10].translate_domain_to((0,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((0,), (8,)) + assert _base_cells(t) == list(range(2, 10)) + + def test_translate_to_offset(self) -> None: + t = _a().translate_domain_to((5,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((5,), (17,)) + assert _base_cells(t) == list(range(12)) + + def test_translate_by_composes_with_stride(self) -> None: + # a[::2].translate_by[5] -> domain [5, 11), base = 2*(coord-5) + t = _a()[::2].translate_domain_by((5,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((5,), (11,)) + assert _base_cells(t) == [0, 2, 4, 6, 8, 10] + assert t[5].output[0].offset == 0 + assert t[10].output[0].offset == 10 + with pytest.raises(BoundsCheckError, match=r"valid indices \[5, 11\)"): + t[0] + + def test_translate_strided_to(self) -> None: + t = _a()[1:10:3].translate_domain_to((100,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((100,), (103,)) + assert _base_cells(t) == [1, 4, 7] + + +class TestFancyDims: + """Oracle section 7: fancy dims get fresh [0, n); values are absolute coordinates.""" + + def test_index_array_values_are_coordinates(self) -> None: + v = _a()[2:10] + t = v.oindex[(np.array([3, 5], dtype=np.intp),)] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((0,), (2,)) + m = t.output[0] + assert isinstance(m, ArrayMap) + storage = m.offset + m.stride * m.index_array + np.testing.assert_array_equal(np.asarray(storage).ravel(), [3, 5]) + + def test_index_array_on_negative_origin(self) -> None: + t = _w().oindex[(np.array([-10, -1], dtype=np.intp),)] + m = t.output[0] + assert isinstance(m, ArrayMap) + storage = m.offset + m.stride * m.index_array + np.testing.assert_array_equal(np.asarray(storage).ravel(), [0, 9]) + + def test_index_array_out_of_domain_raises(self) -> None: + v = _a()[2:10] + for bad in ([0, 3], [-1, 3], [3, 10]): + with pytest.raises(BoundsCheckError): + v.oindex[(np.array(bad, dtype=np.intp),)] diff --git a/packages/zarr-indexing/tests/test_transform.py b/packages/zarr-indexing/tests/test_transform.py new file mode 100644 index 0000000000..a13eaf6e28 --- /dev/null +++ b/packages/zarr-indexing/tests/test_transform.py @@ -0,0 +1,1250 @@ +from __future__ import annotations + +from typing import cast + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.lazy_array import LazyArray +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import ( + IndexTransform, +) + + +class IndexLike: + """A scalar integer selector implemented only through `__index__`.""" + + def __init__(self, value: int) -> None: + self.value = value + + def __index__(self) -> int: + return self.value + + +class IntOnly: + def __int__(self) -> int: + return 2 + + +class BadIndex: + """An `__index__` that lies: the protocol requires an integer.""" + + def __index__(self) -> int: + return cast("int", 2.5) + + +class TestIndexTransformConstruction: + def test_from_shape(self) -> None: + t = IndexTransform.from_shape((10, 20)) + assert t.input_rank == 2 + assert t.output_rank == 2 + assert t.domain.shape == (10, 20) + assert t.domain.origin == (0, 0) + for i, m in enumerate(t.output): + assert isinstance(m, DimensionMap) + assert m.input_dimension == i + assert m.offset == 0 + assert m.stride == 1 + + def test_identity(self) -> None: + domain = IndexDomain(inclusive_min=(5,), exclusive_max=(15,)) + t = IndexTransform.identity(domain) + assert t.input_rank == 1 + assert t.output_rank == 1 + assert t.domain == domain + assert isinstance(t.output[0], DimensionMap) + assert t.output[0].input_dimension == 0 + + def test_from_shape_0d(self) -> None: + t = IndexTransform.from_shape(()) + assert t.input_rank == 0 + assert t.output_rank == 0 + assert t.domain.shape == () + + def test_custom_output_maps(self) -> None: + domain = IndexDomain.from_shape((10,)) + maps = (ConstantMap(offset=42), DimensionMap(input_dimension=0, offset=5, stride=2)) + t = IndexTransform(domain=domain, output=maps) + assert t.input_rank == 1 + assert t.output_rank == 2 + + def test_validation_input_dimension_out_of_range(self) -> None: + domain = IndexDomain.from_shape((10,)) + maps = (DimensionMap(input_dimension=5),) + with pytest.raises(ValueError, match="input_dimension"): + IndexTransform(domain=domain, output=maps) + + +class TestIndexTransformApply: + @pytest.mark.parametrize( + ("transform", "points", "expected"), + [ + pytest.param( + IndexTransform.identity(IndexDomain((-2, 5), (1, 8))), + np.array([-2, 7], dtype=np.int64), + np.array([-2, 7], dtype=np.intp), + id="identity-negative-and-nonzero-origins", + ), + pytest.param( + IndexTransform( + domain=IndexDomain((3,), (6,)), + output=( + ConstantMap(41), + DimensionMap(0, offset=10, stride=-2), + ), + ), + np.array([[3], [5]], dtype=np.int16), + np.array([[41, 4], [41, 0]], dtype=np.intp), + id="constant-and-negative-stride", + ), + pytest.param( + IndexTransform( + domain=IndexDomain((-2, 5), (1, 8)), + output=( + ArrayMap( + np.array([[7], [11], [13]], dtype=np.intp), + offset=-1, + stride=2, + ), + ), + ), + np.array( + [ + [[-2, 5], [-1, 7]], + [[0, 6], [-2, 6]], + ], + dtype=np.intp, + ), + np.array([[[13], [21]], [[25], [13]]], dtype=np.intp), + id="array-map-singleton-broadcast-multidimensional-batch", + ), + pytest.param( + IndexTransform(IndexDomain((), ()), (ConstantMap(42),)), + np.empty((2, 0), dtype=np.intp), + np.array([[42], [42]], dtype=np.intp), + id="rank-zero-input", + ), + pytest.param( + IndexTransform(IndexDomain((-1,), (2,)), ()), + np.array([[-1], [1]], dtype=np.intp), + np.empty((2, 0), dtype=np.intp), + id="rank-zero-output", + ), + pytest.param( + IndexTransform.identity(IndexDomain.from_shape((2,))), + np.empty((0, 1), dtype=np.intp), + np.empty((0, 1), dtype=np.intp), + id="empty-batch", + ), + ], + ) + def test_apply_many_maps_integer_point_batches( + self, + transform: IndexTransform, + points: np.ndarray, + expected: np.ndarray, + ) -> None: + result = transform.apply_many(points) + + np.testing.assert_array_equal(result, expected) + assert result.dtype == np.dtype(np.intp) + assert result.flags.owndata + + def test_apply_maps_one_point(self) -> None: + transform = IndexTransform( + IndexDomain((-2, 4), (1, 7)), + ( + DimensionMap(1, offset=3, stride=-1), + DimensionMap(0, offset=2, stride=2), + ), + ) + + assert transform.apply((-1, 6)) == (-3, 0) + + def test_apply_rejects_a_point_with_the_wrong_rank(self) -> None: + with pytest.raises(ValueError, match=r"point must have shape \(2,\), got \(1,\)"): + IndexTransform.from_shape((2, 3)).apply((1,)) + + def test_apply_rejects_an_explicitly_floating_rank_zero_point(self) -> None: + transform = IndexTransform(IndexDomain((), ()), ()) + with pytest.raises(TypeError, match="integer dtype"): + transform.apply(np.array([], dtype=np.float64)) + + @pytest.mark.parametrize( + "points", + [ + pytest.param(np.array(1, dtype=np.intp), id="no-coordinate-axis"), + pytest.param(np.zeros((4, 3), dtype=np.intp), id="wrong-trailing-size"), + ], + ) + def test_apply_many_rejects_an_invalid_coordinate_axis(self, points: np.ndarray) -> None: + with pytest.raises(ValueError, match="trailing coordinate axis"): + IndexTransform.from_shape((2, 3)).apply_many(points) + + @pytest.mark.parametrize( + "points", + [ + pytest.param(np.array([[True]], dtype=np.bool_), id="bool"), + pytest.param(np.array([[1.0]], dtype=np.float64), id="float"), + pytest.param(np.array([["1"]], dtype=np.str_), id="string"), + pytest.param(np.array([[1]], dtype=object), id="object"), + ], + ) + def test_apply_many_rejects_non_integer_coordinates(self, points: np.ndarray) -> None: + with pytest.raises(TypeError, match="integer dtype"): + IndexTransform.from_shape((2,)).apply_many(points) + + def test_apply_many_reports_the_first_out_of_bounds_coordinate(self) -> None: + transform = IndexTransform.identity(IndexDomain((-2, 10), (2, 13))) + points = np.array( + [ + [[-2, 10], [-1, 20]], + [[9, 11], [0, 12]], + ], + dtype=np.intp, + ) + + with pytest.raises(BoundsCheckError) as error: + transform.apply_many(points) + + assert str(error.value) == ( + "point at batch position (0, 1) has input dimension 1 coordinate 20 outside [10, 13)" + ) + + def test_apply_reports_a_single_point_error_without_batch_vocabulary(self) -> None: + transform = IndexTransform.identity(IndexDomain((-10,), (10,))) + + with pytest.raises(BoundsCheckError) as error: + transform.apply((11,)) + + assert str(error.value) == ( + "coordinate 11 on input dimension 0 is outside the domain [-10, 10)" + ) + assert error.value.__cause__ is None + assert error.value.__suppress_context__ + + @pytest.mark.parametrize( + "beyond_intp", + [ + pytest.param(int(np.iinfo(np.intp).max) + 1, id="first-uint64-coordinate"), + pytest.param(int(np.iinfo(np.uint64).max), id="maximum-uint64-coordinate"), + ], + ) + def test_apply_many_maps_large_literal_coordinates_exactly(self, beyond_intp: int) -> None: + transform = IndexTransform( + IndexDomain((beyond_intp,), (beyond_intp + 1,)), + (DimensionMap(0, offset=-beyond_intp),), + ) + + result = transform.apply_many(np.array([[beyond_intp]], dtype=np.uint64)) + + np.testing.assert_array_equal(result, np.array([[0]], dtype=np.intp)) + assert result.dtype == np.dtype(np.intp) + assert result.flags.owndata + + @pytest.mark.parametrize( + ("transform", "points"), + [ + pytest.param( + IndexTransform( + IndexDomain.from_shape((1,)), + (ConstantMap(np.iinfo(np.intp).max + 1),), + ), + [[0]], + id="constant", + ), + pytest.param( + IndexTransform( + IndexDomain.from_shape((2,)), + (DimensionMap(0, offset=np.iinfo(np.intp).max),), + ), + [[1]], + id="dimension", + ), + pytest.param( + IndexTransform( + IndexDomain.from_shape((1,)), + ( + ArrayMap( + np.array([1], dtype=np.intp), + offset=np.iinfo(np.intp).max, + ), + ), + ), + [[0]], + id="array", + ), + pytest.param( + IndexTransform.identity( + IndexDomain( + (int(np.iinfo(np.intp).max) + 1,), + (int(np.iinfo(np.intp).max) + 2,), + ) + ), + np.array([[int(np.iinfo(np.intp).max) + 1]], dtype=np.uint64), + id="large-input-identity", + ), + ], + ) + def test_apply_many_rejects_mapped_coordinates_outside_intp( + self, transform: IndexTransform, points: list[list[int]] | np.ndarray + ) -> None: + with pytest.raises(OverflowError, match="output coordinate.*np.intp"): + transform.apply_many(points) + + def test_apply_many_rejects_affine_coordinate_overflow(self) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + with pytest.raises(OverflowError, match="outside np.intp"): + transform.apply_many(np.array([[0]], dtype=np.intp)) + + def test_apply_rejects_affine_coordinate_overflow(self) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + with pytest.raises(OverflowError, match="outside np.intp"): + transform.apply((0,)) + + +class TestIndexTransformInverted: + @pytest.mark.parametrize( + ("transform", "points"), + [ + pytest.param( + IndexTransform( + IndexDomain((-3, 4), (1, 7)), + ( + DimensionMap(1, offset=10), + DimensionMap(0, offset=2, stride=-1), + ), + ), + np.array([[-3, 4], [0, 6]], dtype=np.intp), + id="permutation-translation-reversal-nonzero-origin", + ), + pytest.param( + IndexTransform( + IndexDomain((5, -2), (8, -1)), + (DimensionMap(0, offset=3), ConstantMap(99)), + ), + np.array([[5, -2], [7, -2]], dtype=np.intp), + id="constant-and-unreferenced-singleton", + ), + pytest.param( + IndexTransform(IndexDomain((), ()), ()), + np.empty((1, 0), dtype=np.intp), + id="rank-zero", + ), + ], + ) + def test_inverted_round_trips_points( + self, transform: IndexTransform, points: np.ndarray + ) -> None: + inverse = transform.inverted() + mapped = transform.apply_many(points) + + np.testing.assert_array_equal(inverse.apply_many(mapped), points) + assert inverse.apply(transform.apply(tuple(points[0]))) == tuple(points[0]) + assert inverse.inverted() == transform + + def test_inverted_rejects_unequal_ranks(self) -> None: + transform = IndexTransform(IndexDomain.from_shape((2,)), (ConstantMap(1), ConstantMap(2))) + with pytest.raises(ValueError, match="input rank must equal output rank"): + transform.inverted() + + def test_inverted_rejects_an_array_map(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2,)), + (ArrayMap(np.array([1, 0], dtype=np.intp)),), + ) + with pytest.raises(ValueError, match="ArrayMap"): + transform.inverted() + + def test_inverted_rejects_a_non_unit_stride(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2,)), + (DimensionMap(0, stride=2),), + ) + with pytest.raises(ValueError, match=r"stride must be \+1 or -1"): + transform.inverted() + + def test_inverted_rejects_a_repeated_input_dimension(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2, 1)), + (DimensionMap(0), DimensionMap(0, offset=5)), + ) + with pytest.raises(ValueError, match="referenced more than once"): + transform.inverted() + + def test_inverted_rejects_an_unreferenced_non_singleton_dimension(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2, 2)), + (DimensionMap(0), ConstantMap(7)), + ) + with pytest.raises(ValueError, match="unreferenced input dimension 1.*extent 2"): + transform.inverted() + + def test_inverted_rejects_input_labels_that_cannot_be_preserved(self) -> None: + transform = IndexTransform.identity(IndexDomain((0,), (2,), labels=("row",))) + with pytest.raises(ValueError, match="input labels cannot be represented"): + transform.inverted() + + +class TestIndexTransformBasicIndexing: + def test_slice_identity(self) -> None: + """slice(None) on identity transform is a no-op.""" + t = IndexTransform.from_shape((10, 20)) + result = t[slice(None), slice(None)] + assert result.domain.shape == (10, 20) + assert result.input_rank == 2 + assert result.output_rank == 2 + + def test_slice_narrows(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[2:8, 5:15] + # Domains are preserved (TensorStore): the slice keeps its literal + # coordinates, so the map stays the identity (out = in). + assert result.domain.shape == (6, 10) + assert result.domain.origin == (2, 5) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + assert result.output[0].input_dimension == 0 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].offset == 0 + assert result.output[1].input_dimension == 1 + + def test_strided_slice(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t[::2] + assert result.domain.shape == (5,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 2 + + def test_strided_slice_with_start(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t[1:9:3] + # indices: 1, 4, 7 -> 3 elements + assert result.domain.shape == (3,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 1 + assert result.output[0].stride == 3 + + def test_int_drops_dimension(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[3] + assert result.input_rank == 1 + assert result.output_rank == 2 + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 3 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 0 + + def test_int_middle_dimension(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + result = t[:, 5, :] + assert result.input_rank == 2 + assert result.output_rank == 3 + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].input_dimension == 0 + assert isinstance(result.output[1], ConstantMap) + assert result.output[1].offset == 5 + assert isinstance(result.output[2], DimensionMap) + assert result.output[2].input_dimension == 1 + + def test_ellipsis(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + result = t[2:8, ...] + assert result.input_rank == 3 + assert result.domain.shape == (6, 20, 30) + + def test_newaxis(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[np.newaxis, :, :] + assert result.input_rank == 3 + assert result.domain.shape == (1, 10, 20) + assert result.output_rank == 2 + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].input_dimension == 1 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 2 + + def test_int_out_of_bounds(self) -> None: + t = IndexTransform.from_shape((10,)) + with pytest.raises(IndexError): + t[10] + + def test_negative_int_is_literal(self) -> None: + """Negative indices are literal coordinates (TensorStore convention), + not 'from the end' like NumPy.""" + t = IndexTransform.from_shape((10,)) + with pytest.raises(IndexError): + t[-1] # -1 is out of bounds for domain [0, 10) + + def test_negative_int_valid_with_negative_origin(self) -> None: + """Negative index is valid if the domain includes negative coordinates.""" + domain = IndexDomain(inclusive_min=(-5,), exclusive_max=(5,)) + t = IndexTransform.identity(domain) + result = t[-3] + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == -3 + + def test_composition_of_slices(self) -> None: + """Slicing a sliced transform re-selects in literal domain coordinates.""" + t = IndexTransform.from_shape((100,)) + result = t[10:50][15:30] + assert result.domain.shape == (15,) + assert result.domain.origin == (15,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + + def test_composition_of_strides(self) -> None: + t = IndexTransform.from_shape((100,)) + result = t[::2][::3] + # t[::2] -> shape (50,), offset=0, stride=2 + # [::3] -> shape ceil(50/3)=17, offset=0, stride=2*3=6 + assert result.domain.shape == (17,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].stride == 6 + + def test_bare_int(self) -> None: + """Non-tuple selection.""" + t = IndexTransform.from_shape((10, 20)) + result = t[3] + assert result.input_rank == 1 + + def test_bare_slice(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[2:8] + assert result.domain.shape == (6, 20) + + @pytest.mark.parametrize( + ("mode", "selection", "expected_selection"), + [ + pytest.param("basic", IndexLike(2), 2, id="basic-scalar"), + pytest.param( + "basic", + slice(IndexLike(1), IndexLike(7), IndexLike(2)), + slice(1, 7, 2), + id="basic-slice-components", + ), + pytest.param("oindex", IndexLike(2), 2, id="orthogonal-scalar"), + pytest.param("vindex", IndexLike(2), 2, id="vectorized-scalar"), + ], + ) + def test_literal_selectors_support_the_index_protocol( + self, mode: str, selection: object, expected_selection: object + ) -> None: + transform = IndexTransform.from_shape((8,)) + if mode == "basic": + result = transform[selection] + expected = transform[expected_selection] + else: + result = getattr(transform, mode)[selection] + expected = getattr(transform, mode)[expected_selection] + + assert result == expected + + def test_literal_selector_rejects_int_only_objects(self) -> None: + with pytest.raises(IndexError, match="unsupported selection type"): + IndexTransform.from_shape((8,))[IntOnly()] + + def test_literal_selector_propagates_malformed_index_protocol(self) -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + IndexTransform.from_shape((8,))[BadIndex()] + + def test_literal_slice_propagates_malformed_index_protocol(self) -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + IndexTransform.from_shape((8,))[:: BadIndex()] + + +class TestBasicIndexingOnArrayMaps: + """When a transform already has ArrayMap outputs, basic indexing must + apply the corresponding operation to the index_array's axes.""" + + def test_int_on_array_map_drops_axis(self) -> None: + """Integer index on a dimension referenced by an ArrayMap should + index into the array on that axis.""" + arr = np.array([[10, 20], [30, 40], [50, 60]], dtype=np.intp) + # 2D input domain (3, 2), one ArrayMap output + t = IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(index_array=arr),), + ) + # Index with int on dim 0 -> pick row 1 -> arr[1, :] = [30, 40] + result = t[1] + assert result.input_rank == 1 + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, np.array([30, 40])) + + def test_slice_on_array_map(self) -> None: + """Slice on a dimension referenced by an ArrayMap should slice the array.""" + arr = np.array([10, 20, 30, 40, 50], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ArrayMap(index_array=arr),), + ) + result = t[1:4] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, np.array([20, 30, 40])) + + def test_strided_slice_on_array_map(self) -> None: + """Strided slice on ArrayMap should stride the array.""" + arr = np.array([10, 20, 30, 40, 50], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ArrayMap(index_array=arr),), + ) + result = t[::2] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, np.array([10, 30, 50])) + + def test_newaxis_on_array_map(self) -> None: + """Newaxis should insert an axis in the index_array.""" + arr = np.array([10, 20, 30], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=arr),), + ) + result = t[np.newaxis, :] + assert result.input_rank == 2 + assert result.domain.shape == (1, 3) + assert isinstance(result.output[0], ArrayMap) + assert result.output[0].index_array.shape == (1, 3) + np.testing.assert_array_equal(result.output[0].index_array, np.array([[10, 20, 30]])) + + def test_int_drops_one_of_two_array_dims(self) -> None: + """2D array map, int on dim 0, slice on dim 1.""" + arr = np.array([[10, 20, 30], [40, 50, 60]], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=(ArrayMap(index_array=arr),), + ) + result = t[0, 1:3] + assert result.input_rank == 1 + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + # arr[0, 1:3] = [20, 30] + np.testing.assert_array_equal(result.output[0].index_array, np.array([20, 30])) + + +class TestIndexTransformOindex: + def test_oindex_int_array(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.oindex[idx, :] + assert result.input_rank == 2 + assert result.domain.shape == (3, 20) + assert isinstance(result.output[0], ArrayMap) + # Full input rank: the array varies along its own axis (0), singleton on 1. + assert result.output[0].index_array.shape == (3, 1) + np.testing.assert_array_equal(result.output[0].index_array, idx.reshape(3, 1)) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 1 + + def test_oindex_bool_array(self) -> None: + t = IndexTransform.from_shape((5,)) + mask = np.array([True, False, True, False, True]) + result = t.oindex[mask] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal( + result.output[0].index_array, np.array([0, 2, 4], dtype=np.intp) + ) + + def test_oindex_mixed(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx = np.array([2, 4], dtype=np.intp) + result = t.oindex[idx, 5:15] + assert result.input_rank == 2 + assert result.domain.shape == (2, 10) + # fancy dim: fresh zero-origin; slice dim: preserved literal coords + assert result.domain.origin == (0, 5) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].offset == 0 + + def test_oindex_multiple_arrays(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + idx0 = np.array([1, 3], dtype=np.intp) + idx1 = np.array([5, 10, 15], dtype=np.intp) + result = t.oindex[idx0, :, idx1] + assert result.input_rank == 3 + assert result.domain.shape == (2, 20, 3) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], DimensionMap) + assert isinstance(result.output[2], ArrayMap) + + def test_oindex_multiple_arrays_preserves_independent_axes(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.oindex[np.array([1, 3]), np.array([2, 4, 6])] + assert result.domain.shape == (2, 3) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + assert result.output[0].index_array.shape == (2, 1) + assert result.output[1].index_array.shape == (1, 3) + + +class TestIndexTransformVindex: + def test_vindex_single_array(self) -> None: + t = IndexTransform.from_shape((10,)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.vindex[idx] + assert result.input_rank == 1 + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, idx) + + def test_vindex_broadcast(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx0 = np.array([[1, 2], [3, 4]], dtype=np.intp) + idx1 = np.array([[10, 11], [12, 13]], dtype=np.intp) + result = t.vindex[idx0, idx1] + assert result.input_rank == 2 + assert result.domain.shape == (2, 2) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, idx0) + np.testing.assert_array_equal(result.output[1].index_array, idx1) + + def test_vindex_with_slice(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.vindex[idx, :, :] + assert result.input_rank == 3 + assert result.domain.shape == (3, 20, 30) + assert isinstance(result.output[0], ArrayMap) + + def test_vindex_bool_mask(self) -> None: + t = IndexTransform.from_shape((5,)) + mask = np.array([True, False, True, False, True]) + result = t.vindex[mask] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + + def test_vindex_multidimensional_boolean_list_mask(self) -> None: + result = IndexTransform.from_shape((2, 3)).vindex[ + [[True, False, True], [False, True, False]] + ] + + assert result.domain.shape == (3,) + np.testing.assert_array_equal( + result.apply_many(np.array([[0], [1], [2]], dtype=np.intp)), + np.array([[0, 0], [0, 2], [1, 1]], dtype=np.intp), + ) + + def test_vindex_broadcast_different_shapes(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx0 = np.array([1, 2, 3], dtype=np.intp) + idx1 = np.array([[10], [11]], dtype=np.intp) + result = t.vindex[idx0, idx1] + assert result.input_rank == 2 + assert result.domain.shape == (2, 3) + + def test_vindex_multiple_arrays_preserves_shared_axes(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.vindex[np.array([1, 3]), np.array([2, 4])] + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + assert result.output[0].index_array.shape == (2,) + assert result.output[1].index_array.shape == (2,) + + +@pytest.mark.parametrize("mode", ["oindex", "vindex"]) +def test_direct_advanced_index_rejects_float_arrays(mode: str) -> None: + helper = getattr(IndexTransform.from_shape((5,)), mode) + with pytest.raises(IndexError, match="integer or boolean"): + helper[np.array([1.9, 3.2])] + + +@pytest.mark.parametrize("mode", ["oindex", "vindex"]) +def test_direct_advanced_index_rejects_wrong_length_boolean_mask(mode: str) -> None: + helper = getattr(IndexTransform.from_shape((5,)), mode) + with pytest.raises(IndexError, match="boolean index.*dimension 5"): + helper[np.array([True, False])] + + +class TestSelectionToTransform: + def test_basic_slice(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.select((slice(2, 8), slice(5, 15)), "basic") + assert result.domain.shape == (6, 10) + assert result.domain.origin == (2, 5) # preserved literal coordinates + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + + def test_basic_int(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.select((3, slice(None)), "basic") + assert result.input_rank == 1 + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 3 + + def test_basic_ellipsis(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.select(Ellipsis, "basic") + assert result.domain.shape == (10, 20) + + def test_orthogonal(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.select((idx, slice(None)), "orthogonal") + assert result.domain.shape == (3, 20) + assert isinstance(result.output[0], ArrayMap) + + def test_vectorized(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx0 = np.array([1, 3], dtype=np.intp) + idx1 = np.array([5, 7], dtype=np.intp) + result = t.select((idx0, idx1), "vectorized") + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + + def test_composition_with_non_identity(self) -> None: + """Indexing a sliced transform uses literal domain coordinates. + + The slice [10:50] preserves its domain, so a follow-up [15:30] + re-selects coordinates 15..29 of the base (TensorStore semantics), and + the composed map stays the identity (out = in). + """ + t = IndexTransform.from_shape((100,))[10:50] + result = t.select(slice(15, 30), "basic") + assert (result.domain.inclusive_min, result.domain.exclusive_max) == ((15,), (30,)) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + + +class TestIndexTransformIntersect: + def test_constant_inside(self) -> None: + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + result = t.intersect(IndexDomain(inclusive_min=(0,), exclusive_max=(10,))) + assert result is not None + restricted, surviving = result + assert isinstance(restricted.output[0], ConstantMap) + assert restricted.output[0].offset == 5 + assert surviving is None + + def test_constant_outside(self) -> None: + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + result = t.intersect(IndexDomain(inclusive_min=(10,), exclusive_max=(20,))) + assert result is None + + def test_dimension_partial(self) -> None: + """DimensionMap over [0,10) intersected with [5,15) narrows input to [5,10).""" + t = IndexTransform.from_shape((10,)) + result = t.intersect(IndexDomain(inclusive_min=(5,), exclusive_max=(15,))) + assert result is not None + restricted, surviving = result + assert restricted.domain.inclusive_min == (5,) + assert restricted.domain.exclusive_max == (10,) + assert surviving is None + + def test_dimension_no_overlap(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t.intersect(IndexDomain(inclusive_min=(20,), exclusive_max=(30,))) + assert result is None + + def test_dimension_strided(self) -> None: + """stride=2, offset=1 over [0,5): storage 1,3,5,7,9. Chunk [4,8).""" + t = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(DimensionMap(input_dimension=0, offset=1, stride=2),), + ) + result = t.intersect(IndexDomain(inclusive_min=(4,), exclusive_max=(8,))) + assert result is not None + restricted, _surviving = result + # input 2->5, input 3->7. Both in [4,8). + assert restricted.domain.inclusive_min == (2,) + assert restricted.domain.exclusive_max == (4,) + + @pytest.mark.parametrize( + ("input_domain", "output_domain", "output_map", "expected"), + [ + ( + (2**53, 2**53 + 3), + (2**53 + 1, 2**53 + 2), + DimensionMap(input_dimension=0), + (2**53 + 1, 2**53 + 2), + ), + ( + (-(2**53) - 2, -(2**53) + 1), + (-(2**53) - 1, -(2**53)), + DimensionMap(input_dimension=0), + (-(2**53) - 1, -(2**53)), + ), + ( + (-(2**53) - 2, -(2**53) + 1), + (2**53 + 1, 2**53 + 2), + DimensionMap(input_dimension=0, stride=-1), + (-(2**53) - 1, -(2**53)), + ), + ( + (2**53, 2**53 + 3), + (-(2**53) - 2, -(2**53) - 1), + DimensionMap(input_dimension=0, stride=-1), + (2**53 + 2, 2**53 + 3), + ), + ], + ids=[ + "positive-coordinates-positive-stride", + "negative-coordinates-positive-stride", + "positive-coordinates-negative-stride", + "negative-coordinates-negative-stride", + ], + ) + def test_dimension_intersection_is_exact_above_float_precision( + self, + input_domain: tuple[int, int], + output_domain: tuple[int, int], + output_map: DimensionMap, + expected: tuple[int, int], + ) -> None: + transform = IndexTransform( + domain=IndexDomain((input_domain[0],), (input_domain[1],)), + output=(output_map,), + ) + + result = transform.intersect(IndexDomain((output_domain[0],), (output_domain[1],))) + + assert result is not None + restricted, _surviving = result + assert restricted.domain == IndexDomain((expected[0],), (expected[1],)) + + def test_dimension_intersection_accepts_unbounded_python_integer_precision(self) -> None: + huge = 10**400 + transform = IndexTransform( + domain=IndexDomain((huge,), (huge + 2,)), + output=(DimensionMap(input_dimension=0),), + ) + + result = transform.intersect(IndexDomain((huge + 1,), (huge + 2,))) + + assert result is not None + restricted, _surviving = result + assert restricted.domain == IndexDomain((huge + 1,), (huge + 2,)) + + def test_array_partial(self) -> None: + arr = np.array([3, 8, 15, 22], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ArrayMap(index_array=arr),), + ) + result = t.intersect(IndexDomain(inclusive_min=(5,), exclusive_max=(20,))) + assert result is not None + restricted, surviving = result + assert isinstance(restricted.output[0], ArrayMap) + np.testing.assert_array_equal(restricted.output[0].index_array, np.array([8, 15])) + assert surviving is not None + np.testing.assert_array_equal(surviving, np.array([1, 2])) + + def test_array_none_inside(self) -> None: + arr = np.array([1, 2, 3], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=arr),), + ) + assert t.intersect(IndexDomain(inclusive_min=(10,), exclusive_max=(20,))) is None + + def test_2d_mixed(self) -> None: + """2D: ConstantMap on dim 0, DimensionMap on dim 1.""" + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=( + ConstantMap(offset=5), + DimensionMap(input_dimension=0, offset=0, stride=1), + ), + ) + chunk = IndexDomain(inclusive_min=(0, 5), exclusive_max=(10, 15)) + result = t.intersect(chunk) + assert result is not None + restricted, _ = result + assert isinstance(restricted.output[0], ConstantMap) + assert restricted.output[0].offset == 5 + assert isinstance(restricted.output[1], DimensionMap) + assert restricted.domain.inclusive_min == (5,) + assert restricted.domain.exclusive_max == (10,) + + +class TestIndexTransformTranslate: + def test_translate_constant(self) -> None: + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + result = t.translate((-5,)) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 0 + + def test_translate_dimension(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t.translate((-3,)) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == -3 + assert result.output[0].stride == 1 + + def test_translate_array(self) -> None: + arr = np.array([5, 10], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(index_array=arr, offset=3),), + ) + result = t.translate((-3,)) + assert isinstance(result.output[0], ArrayMap) + assert result.output[0].offset == 0 + np.testing.assert_array_equal(result.output[0].index_array, arr) + + def test_translate_2d(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.translate((-5, -10)) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == -5 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].offset == -10 + + +class TestArrayMapDependencyAxes: + """`ArrayMap.dependency_axes` derives the input axes an array varies on + from its (full-rank) shape: non-singleton axes vary, singleton axes do not.""" + + def test_orthogonal_single_axis(self) -> None: + t = IndexTransform.from_shape((10, 20)).oindex[np.array([1, 3]), np.array([2, 4, 6])] + m0, m1 = t.output[0], t.output[1] + assert isinstance(m0, ArrayMap) + assert isinstance(m1, ArrayMap) + assert m0.dependency_axes == (0,) + assert m1.dependency_axes == (1,) + + def test_vectorized_shares_axes(self) -> None: + t = IndexTransform.from_shape((10, 20)).vindex[np.array([1, 3]), np.array([2, 4])] + m0, m1 = t.output[0], t.output[1] + assert isinstance(m0, ArrayMap) + assert isinstance(m1, ArrayMap) + assert m0.dependency_axes == (0,) + assert m1.dependency_axes == (0,) + + def test_scalar_array_has_no_dependency(self) -> None: + assert ArrayMap(np.ones((1, 1), dtype=np.intp)).dependency_axes == () + + def test_zero_length_axis_has_no_dependency(self) -> None: + """An axis of size 0 carries no dependency either: it selects nothing, so + the array does not vary along it any more than along a singleton.""" + assert ArrayMap(np.zeros((0, 4), dtype=np.intp)).dependency_axes == (1,) + assert ArrayMap(np.zeros((3, 0), dtype=np.intp)).dependency_axes == (0,) + assert ArrayMap(np.zeros((0, 1), dtype=np.intp)).dependency_axes == () + + def test_zero_length_axis_does_not_make_a_map_correlated(self) -> None: + """An empty orthogonal selection is legal, so it must classify as one.""" + m = ArrayMap(index_array=np.zeros((0, 4), dtype=np.intp)) + assert m.dependent_axis == 1 + + +class TestIntersectArrayMapClassification: + """`_intersect` must distinguish orthogonal (outer-product) ArrayMaps from + correlated (vectorized) ones by their dependency axes, keep surviving arrays + at full input rank, and preserve residual (slice) dimensions.""" + + def test_orthogonal_outer_product_keeps_full_rank(self) -> None: + """Two arrays on distinct axes narrow independently and stay full rank; + out_indices is a per-output-dim dict of surviving positions.""" + t = IndexTransform.from_shape((10, 10)).oindex[np.array([1, 3, 8]), np.array([2, 6, 9])] + # Chunk covering storage [0,5) x [0,5): rows 1,3 survive (out pos 0,1), + # cols 2 survives (out pos 0). + chunk = IndexDomain(inclusive_min=(0, 0), exclusive_max=(5, 5)) + result = t.intersect(chunk) + assert result is not None + restricted, out_indices = result + assert isinstance(restricted.output[0], ArrayMap) + assert isinstance(restricted.output[1], ArrayMap) + # Full input rank preserved (not raveled to 1-D). + assert restricted.output[0].index_array.ndim == 2 + assert restricted.output[1].index_array.ndim == 2 + assert restricted.domain.ndim == 2 + assert isinstance(out_indices, dict) + np.testing.assert_array_equal(out_indices[0], np.array([0, 1])) + np.testing.assert_array_equal(out_indices[1], np.array([0])) + + def test_correlated_with_residual_slice_preserves_slice_dim(self) -> None: + """A vindex transform with two correlated arrays plus a residual slice + dim intersects without a rank error and keeps the DimensionMap.""" + t = IndexTransform.from_shape((4, 3, 5)).vindex[np.array([1, 3]), np.array([2, 0])] + # Chunk covering storage [0,2) x [2,3) x [0,5): only point (1,2,*) is in + # bounds on both array dims -> one surviving broadcast point. + chunk = IndexDomain(inclusive_min=(0, 2, 0), exclusive_max=(2, 3, 5)) + result = t.intersect(chunk) + assert result is not None + restricted, out_indices = result + # A DimensionMap for the residual slice dim survives (no post-init error). + assert any(isinstance(m, DimensionMap) for m in restricted.output) + assert out_indices is not None + + def test_length1_orthogonal_collapses_to_a_constant(self) -> None: + """A length-1 orthogonal array holds one coordinate: it is a ConstantMap. + + The length-1 axis stays in the domain, and the remaining genuine array + intersects orthogonally — a single survivor vector, not a joint gather. + """ + t = IndexTransform.from_shape((6, 6)).oindex[np.array([2]), np.array([1, 3, 5])] + assert isinstance(t.output[0], ConstantMap) + assert t.domain.shape == (1, 3) + chunk = IndexDomain(inclusive_min=(0, 0), exclusive_max=(6, 6)) + result = t.intersect(chunk) + assert result is not None + _restricted, out_indices = result + assert isinstance(out_indices, np.ndarray) + np.testing.assert_array_equal(out_indices, [0, 1, 2]) + + +class TestDerivedMapDependency: + """A map's `input_dimension` must describe the array it is built with. + + Three separate failures came from one stale value: a vectorized index applied + to an orthogonal map makes it correlated, but the old dependency was carried + onto the new array anyway. Readers fall back to that field when the shape + alone cannot say, so the wrong axis was believed much later — by a scatter + that filed positions under it, which is why the answer depended on how the + read was partitioned. + """ + + def test_a_vindex_over_a_fancy_view_is_marked_correlated(self) -> None: + base = np.arange(6) + view = ( + LazyArray(base) + .lazy.oindex[np.array([0, 1])] + .lazy.vindex[np.array([[0, 1, 0], [1, 0, 1]])] + ) + np.testing.assert_array_equal( + np.asarray(view.result()), base[[0, 1]][[[0, 1, 0], [1, 0, 1]]] + ) + + def test_the_same_view_resolves_alike_however_it_is_partitioned(self) -> None: + base = np.arange(36).reshape(6, 6) + + def build(array: LazyArray) -> LazyArray: + return array.lazy.oindex[np.array([-3, -6, -4]), -4].lazy.vindex[np.array([[-2, -3]])] + + unpartitioned = np.asarray(build(LazyArray(base)).result()) + partitioned = np.asarray(build(LazyArray(base).with_parts((3, 3))).result()) + np.testing.assert_array_equal(partitioned, unpartitioned) + np.testing.assert_array_equal(unpartitioned, np.array([[2, 20]])) + + def test_dependency_axes_are_read_from_the_shape(self) -> None: + """What a map varies over is its non-singleton axes — nothing else. + + The retired `input_dimension` field could contradict the array it rode + on; the shape cannot. + """ + t = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap(index_array=np.array([[0, 1, 2]], dtype=np.intp)), + ArrayMap(index_array=np.array([[0], [1]], dtype=np.intp)), + ), + ) + assert t.index_array_structure == "orthogonal" + + +def test_an_orthogonal_step_over_a_correlated_view_is_an_outer_product() -> None: + """`oindex` after `vindex` means the outer product, not a joint gather. + + The reindexing applied its index tuple positionally, which is NumPy's + *vectorized* rule, so two arrays collapsed into one axis and the result came + back a rank short of what was asked for. + """ + base = np.arange(14).reshape(7, 2) + view = LazyArray(base).lazy.vindex[ + np.array([[5, 5], [1, 2], [0, 4]]), np.array([[1, 1], [1, 0], [1, 0]]) + ] + result = np.asarray(view.lazy.oindex[np.array([1, 1, 0]), np.array([1, 1, 0, 1])].result()) + assert result.shape == (3, 4) + np.testing.assert_array_equal(result, np.array([[4, 4, 3, 4], [4, 4, 3, 4], [11, 11, 11, 11]])) + + +@pytest.mark.parametrize( + ("value", "description"), + [(1, "one below the lower bound"), (10, "the exclusive upper bound itself")], +) +def test_an_index_array_value_just_outside_the_domain_is_refused( + value: int, description: str +) -> None: + """The bound checks are probed at the boundary, not comfortably past it. + + Both were only ever exercised from well outside the domain, so relaxing + either by one — `lo - 1` instead of `lo` — went unnoticed while letting a + view read a cell it does not address. + """ + transform = IndexTransform.from_shape((12,))[2:10] + with pytest.raises(BoundsCheckError, match="out of bounds"): + transform.oindex[np.array([value, 3])] + + +def test_an_index_array_value_at_each_end_of_the_domain_is_accepted() -> None: + """The other side of the same boundary: the extremes themselves are in range.""" + transform = IndexTransform.from_shape((12,))[2:10] + array_map = transform.oindex[np.array([2, 9])].output[0] + assert isinstance(array_map, ArrayMap) + np.testing.assert_array_equal(array_map.index_array, np.array([2, 9])) + + +# --------------------------------------------------------------------------- +# Intersecting diagonal gathers +# --------------------------------------------------------------------------- + + +def test_intersecting_a_diagonal_gather_keeps_points_inside_the_domain() -> None: + """Index arrays sharing an input axis intersect pointwise, like vindex.""" + rows = np.array([4, 0, 2]) + cols = np.array([1, 5, 2]) + transform = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=( + ArrayMap(index_array=rows), + ArrayMap(index_array=cols), + ), + ) + + result = transform.intersect(IndexDomain(inclusive_min=(0, 0), exclusive_max=(3, 3))) + assert result is not None + restricted, survivors = result + # Only the point (2, 2) has both coordinates inside [0, 3) x [0, 3). + assert restricted.domain.shape == (1,) + assert isinstance(survivors, np.ndarray) + np.testing.assert_array_equal(survivors, [2]) + np.testing.assert_array_equal(restricted.apply((0,)), (2, 2)) + + assert transform.intersect(IndexDomain(inclusive_min=(0, 0), exclusive_max=(1, 1))) is None + + +def test_index_array_structure_classifies_the_three_shapes() -> None: + base = IndexTransform.from_shape((4, 6)) + assert (base[1:, ::2]).index_array_structure == "none" + assert (base.oindex[np.array([0, 2]), slice(None)]).index_array_structure == "orthogonal" + assert (base.vindex[np.array([0, 2]), np.array([1, 3])]).index_array_structure == "general" + diagonal = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=( + ArrayMap(index_array=np.array([0, 1])), + ArrayMap(index_array=np.array([2, 3])), + ), + ) + assert diagonal.index_array_structure == "general" diff --git a/packages/zarr-indexing/uv.lock b/packages/zarr-indexing/uv.lock new file mode 100644 index 0000000000..2687ba71d8 --- /dev/null +++ b/packages/zarr-indexing/uv.lock @@ -0,0 +1,769 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" + +[[package]] +name = "babel" +version = "2.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/b2/51899539b6ceeeb420d40ed3cd4b7a40519404f9baf3d4ac99dc413a834b/babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d", size = 9959554, upload-time = "2026-02-01T12:30:56.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, +] + +[[package]] +name = "backrefs" +version = "8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/56/4744bcd0c82184e80c52b0ac4076c261a8ffa1f1b343ff2f6e89ce0e1cef/backrefs-8.0.tar.gz", hash = "sha256:b556cd7d36c3a3a2f256b89590b176b8eddfb73bcfaee3a3ddd84ea66d21ce50", size = 7013081, upload-time = "2026-07-26T19:54:24.638Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/fd/9bf53b6a6f6f519ffaac765df2f2a25e5c2fc6d32cfd2b2747099e72c911/backrefs-8.0-py310-none-any.whl", hash = "sha256:4a627b817fd2dce43b79ab48da63613340509381cd8ce0897078a0bce79a2ab8", size = 380377, upload-time = "2026-07-26T19:54:17.457Z" }, + { url = "https://files.pythonhosted.org/packages/e1/29/4bd7ae72a2634da00379c2b3bcc5439e7c94620235c6afea8af15229a973/backrefs-8.0-py311-none-any.whl", hash = "sha256:f0c35cf0102ba6b6070c12a492be3c1c1d3f5839529784b9a9565d6d04569a01", size = 392169, upload-time = "2026-07-26T19:54:18.782Z" }, + { url = "https://files.pythonhosted.org/packages/29/13/232505664e8e2a0c7a2eb0c505cfade9d715538f89a5d62bc4c272968f62/backrefs-8.0-py312-none-any.whl", hash = "sha256:87f0fae8c5f207fe9f4b2887efc71d42f4900ac78faa1af08d675ef303692dc5", size = 398084, upload-time = "2026-07-26T19:54:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/8a/69/47a3dc20abc4fa5486655fde681bd55e63211b46c886d8c02223d6468431/backrefs-8.0-py313-none-any.whl", hash = "sha256:601ce68ca12385dbda06ce264406b4c4210cf5b79fd0fd627592365c92f29a88", size = 400040, upload-time = "2026-07-26T19:54:21.194Z" }, + { url = "https://files.pythonhosted.org/packages/1c/cf/e5f9b68a5b0e939a2fb933a66c20180d0c9241bf8927f7a47fa48c1675e9/backrefs-8.0-py314-none-any.whl", hash = "sha256:9ec96efa080938be92323e8e730e57718c9c88eb15ad70bbef4e1766df591408", size = 411903, upload-time = "2026-07-26T19:54:23.221Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bd/2a/23f34ec9d04624958e137efdc394888716353190e75f25dd22c7a2c7a8aa/charset_normalizer-3.4.9.tar.gz", hash = "sha256:673611bbd43f0810bec0b0f028ddeaaa501190339cac411f347ac76917c3ae7b", size = 152439, upload-time = "2026-07-07T14:34:58.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/4a/ecbd131485c07fcdfad54e28946d513e3da22ef3b4bd854dcafae54ec739/charset_normalizer-3.4.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:45b0cc4e3556cd875e09102988d1ab8356c998b596c9fced84547c8138b487a0", size = 319300, upload-time = "2026-07-07T14:33:15.666Z" }, + { url = "https://files.pythonhosted.org/packages/ec/96/5d9364e3342d69f3a045e1777bc47c85c383e6e9466d561b33fdb419d1f9/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b2aff1c7b3884512b9512c3eaadd9bab39fb45042ffaaa1dd08ff2b9f8109d9", size = 215802, upload-time = "2026-07-07T14:33:17.031Z" }, + { url = "https://files.pythonhosted.org/packages/4b/4c/5361f9aa7f2cb58d94f2ab831b3d493f69efb1d239654b4744e3c09527cb/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9104ed0bd76a429d46f9ec0dbc9b08ad1d2dcdf2b00a5a0daa1c145329b35b44", size = 237171, upload-time = "2026-07-07T14:33:18.576Z" }, + { url = "https://files.pythonhosted.org/packages/50/78/ce342ca4ff30b2eb49fe6d9578df85974f90c67d294113e94efdd9664cbd/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7b86a2b16095d250c6f58b3d9b2eee6f4147754344f3dab0922f7c9bf7d226c9", size = 233075, upload-time = "2026-07-07T14:33:20.084Z" }, + { url = "https://files.pythonhosted.org/packages/01/c4/4fa4c8b3097a11f3c5f09a35b72ed6855fb1d332469504962ab7bafcc702/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e226f6218febc71f6c1fc2fafb91c226f75bdc1d8fb12d66823716e891608fd", size = 224256, upload-time = "2026-07-07T14:33:21.747Z" }, + { url = "https://files.pythonhosted.org/packages/87/3a/ad914516df7e358a81aae018caa5e0470ba827fa6d763b1d2e87d920a5f6/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:90c44bc373b7687f6948b693cceaea1348ae0975d7474746559494468e3c1d84", size = 208784, upload-time = "2026-07-07T14:33:23.313Z" }, + { url = "https://files.pythonhosted.org/packages/d7/74/3c12f9755717dfe5c5c87da63f35d765fa0c00382ec26bf23f7fae34f2ba/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9cdef90ae47919cae358d8ab15797a800ed41da7aba5d72419fb510729e2ed4b", size = 219928, upload-time = "2026-07-07T14:33:24.814Z" }, + { url = "https://files.pythonhosted.org/packages/33/9a/895095b83e7907abd6d3d99aad3a38ad0d9686cc186cb0c94c24320fe63e/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:60f44ade2cf573dad7a277e6f8ca9a51a21dda572b13bd7d8539bb3cd5dbedde", size = 218489, upload-time = "2026-07-07T14:33:26.42Z" }, + { url = "https://files.pythonhosted.org/packages/a1/34/ef5c05f412f42520d7709b7d3784d19640839eb7366ded1755511585429f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a1786910334ed46ab1dd73222f2cd1e05c2c3bb39f6dddb4f8b36fc382058a39", size = 210267, upload-time = "2026-07-07T14:33:27.952Z" }, + { url = "https://files.pythonhosted.org/packages/83/dc/9b29fa4412b318bf3bfea985c35d67eb55e04b59a7c3f2237168b0e0be6f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:03d07803992c6c7bbc976327f34b18b6160327fc81cb82c9d504720ac0be3b62", size = 226030, upload-time = "2026-07-07T14:33:29.397Z" }, + { url = "https://files.pythonhosted.org/packages/0e/42/6dbc00b8cd16011691203e33570fa42ed5746599a2e878112d16eab403a3/charset_normalizer-3.4.9-cp312-cp312-win32.whl", hash = "sha256:78841cccf1af7b40f6f716338d50c0902dbe88d9f800b3c973b7a9a0a693a642", size = 151185, upload-time = "2026-07-07T14:33:30.781Z" }, + { url = "https://files.pythonhosted.org/packages/80/cc/f920afd1a23c58ccd53c1d36085a71893a4737ff5e66e0371efab6809850/charset_normalizer-3.4.9-cp312-cp312-win_amd64.whl", hash = "sha256:4b3dac63058cc36820b0dd072f89898604e2d39686fe05321729d00d8ac185a0", size = 162557, upload-time = "2026-07-07T14:33:32.176Z" }, + { url = "https://files.pythonhosted.org/packages/f0/e6/0386d43a261ff4e4b30c5857af7df877254b46bec7b9d1b74b6bf969a90b/charset_normalizer-3.4.9-cp312-cp312-win_arm64.whl", hash = "sha256:78fa18e436a1a0e58dbd7e02fc4473f3f32cceb12df9dfca542d075961c307d2", size = 152665, upload-time = "2026-07-07T14:33:33.711Z" }, + { url = "https://files.pythonhosted.org/packages/b2/06/97ec2aeae780b31d742b6352218b43841a6871e2564578ca522dce4a45c3/charset_normalizer-3.4.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:440eede837960000d74978f0eba527be106b5b9aee0daf779d395276ed0b0614", size = 317688, upload-time = "2026-07-07T14:33:35.408Z" }, + { url = "https://files.pythonhosted.org/packages/d0/39/8ff066c672434225f8d25f8b739f992af250944392173dcc88362681c9bf/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e764fd1e70b6a3e205a0e46f3051701f98a8cb3fad66eeb80e48bb502f8698", size = 214982, upload-time = "2026-07-07T14:33:36.996Z" }, + { url = "https://files.pythonhosted.org/packages/92/8f/3a47a3667c83c2df9483d91644c6c107de3bf8874aa1793da9d3012eb986/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e4fd89cc178bced6ad29cb3e6dd4aa63fa5017c3524dbd0b25998fb64a87cc8b", size = 236460, upload-time = "2026-07-07T14:33:38.536Z" }, + { url = "https://files.pythonhosted.org/packages/f1/60/b22cdbee7e4013dab8b0d7647fc6181120fbbbc8f7025c226d15bd5a47fc/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bd47ba7fc3ca94896759ea0109775132d3e7ab921fbf54038e1bab2e46c313c9", size = 232003, upload-time = "2026-07-07T14:33:40.059Z" }, + { url = "https://files.pythonhosted.org/packages/ea/f8/72eb13dcabe7257035cea8aefd922caad2f110d252bf9f67c4c2ca763aee/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84fd18bcc17526fc2b3c1af7d2b9217d32c9c04448c16ec693b9b4f1985c3d33", size = 223149, upload-time = "2026-07-07T14:33:41.631Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3e/faee8f9de92b14ee1198e9163252bb15efee7301b31256a3b6d9ebfdd0dd/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:5b10cd92fc5c498b35a8635df6d5a100207f88b63a4dc1de7ef9a548e1e2cd63", size = 207901, upload-time = "2026-07-07T14:33:43.209Z" }, + { url = "https://files.pythonhosted.org/packages/3a/25/45f30093ae27dd7b92a793b61882a38685f993700113ca36e0c9c14965e1/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a4fbdde9dd4a9ce5fd52c2b3a347bb50cc89483ef783f1cb00d408c13f7a96c0", size = 219176, upload-time = "2026-07-07T14:33:44.725Z" }, + { url = "https://files.pythonhosted.org/packages/48/18/c8f397329c35e32f6a837e488986f4ae03bd2abebc453b48714991630c2f/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:416c229f77e5ea25b3dfd4b582f8d73d7e43c22320302b9ab128a2d3a0b38efe", size = 217356, upload-time = "2026-07-07T14:33:46.192Z" }, + { url = "https://files.pythonhosted.org/packages/86/7e/5ce0bba863470fd1902d5e5843968951bddf38abe4742fc97116ef4598b3/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:75286256590a6320cf106a0d28970d3560aad9ee09aa7b34fb40524792436d35", size = 209614, upload-time = "2026-07-07T14:33:47.705Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ef/2473d3c4d869155be4af1191111d59c4d5c4e0173026f7e85b176e23bf65/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:69b157c5d3292bcd443faca052f3096f637f1e074b98212a933c074ae23dc3b8", size = 224991, upload-time = "2026-07-07T14:33:49.238Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a3/53ddae3db108a088156aa8ddfafd411ebbc1340f48c5573f697b27f69a39/charset_normalizer-3.4.9-cp313-cp313-win32.whl", hash = "sha256:51307f5c71007673a2bf8232ad973483d281e74cb99c8c5a990af1eefa6277d9", size = 150622, upload-time = "2026-07-07T14:33:50.711Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ef/6953a77c7cf2c2ff9998e6f575ab3e380119f100223381565a4f94c1f836/charset_normalizer-3.4.9-cp313-cp313-win_amd64.whl", hash = "sha256:fe2c7201c642b7c308f1675355ad7ff7b66acfe3541625efe5a3ad38f29d6115", size = 161947, upload-time = "2026-07-07T14:33:52.197Z" }, + { url = "https://files.pythonhosted.org/packages/6e/fb/d560d1d1555debbfe7849d9cac6145c1b537709d79576bf22557ed803b82/charset_normalizer-3.4.9-cp313-cp313-win_arm64.whl", hash = "sha256:611057cc5d5c0afc743ba8be6bd828c17e0aaa8643f9d0a9b9bb7dea80eb8012", size = 152594, upload-time = "2026-07-07T14:33:53.486Z" }, + { url = "https://files.pythonhosted.org/packages/7e/8d/496817fa0944239ecae662dd57ea765cfeaec6a735f9f025d4b7b72e7143/charset_normalizer-3.4.9-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0327fcd59a935777d83410750c50600ee9571af2846f71ce40f25b13da1ef380", size = 317253, upload-time = "2026-07-07T14:33:54.994Z" }, + { url = "https://files.pythonhosted.org/packages/2b/f9/ef4a69ea338ad3c0deceea0f5f7d2380ae8b52132b06d652cb0d2cd86706/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a79d9f4d8001473a30c163556b3c3bfebec837495a412dde78b51672f6134f9", size = 215898, upload-time = "2026-07-07T14:33:56.334Z" }, + { url = "https://files.pythonhosted.org/packages/8c/e7/5ddfd76fc061eb52de219658a4aa431cbacadf0a0219c8854f00da50d289/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:33bdcc2a32c0a0e861f60841a512c8acc658c87c2ac59d89e3a46dacf7d866e4", size = 236718, upload-time = "2026-07-07T14:33:57.9Z" }, + { url = "https://files.pythonhosted.org/packages/49/ba/768fa3f36048d81c477a0ce61f813bc1454d80917ccfe550abd9f44f5e24/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f840ed6d8ecba8255df8c42b87fadeda98ddfc6eeec05e2dc66e26d46dd6f58a", size = 232519, upload-time = "2026-07-07T14:33:59.811Z" }, + { url = "https://files.pythonhosted.org/packages/f4/c4/b3e049d2aa3766180c78507110543d9d50894cc97f57de543f1be521dcdc/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c25fe15c70c59eb7c5ce8c06a1f3fa1da0ecc5ea1e7a5922c40fd2fa9b0d5046", size = 223143, upload-time = "2026-07-07T14:34:01.517Z" }, + { url = "https://files.pythonhosted.org/packages/19/79/55c32d06d76ae4feafe053f061f3e3ab70bcf19f4007797ce8c3efda7830/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:f7fb7d750cfa0a070d2c24e831fd3481019a60dd317ea2b39acbcebc08b6ed81", size = 206742, upload-time = "2026-07-07T14:34:03.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/e0/47c079dd82d217c807479cd59ffd30af56307ea31c108b75758970459ad3/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d1c96a7a18b9690a4d46df09e3e3382406ae3213727cd1019ebade1c4a81917", size = 219191, upload-time = "2026-07-07T14:34:04.657Z" }, + { url = "https://files.pythonhosted.org/packages/42/ab/b9bc2e77d6b44a7e46ef62ec5cac1c9a6ba7b9135a5d560f002696ec9995/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a4cfde78a9f2880208d16a93b795726a3017d5977e08d1e162a7a31322479c41", size = 218328, upload-time = "2026-07-07T14:34:06.115Z" }, + { url = "https://files.pythonhosted.org/packages/f1/78/c9c71d599f5aa2d42bcdd35cbbd46d7f535351a57e40ff7d8e5a7e219401/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:d4d6fcde76f94f5cb9e43e9e9a61f16dacefd228cbbf6f1a09bd9b219a92f1a1", size = 207406, upload-time = "2026-07-07T14:34:07.554Z" }, + { url = "https://files.pythonhosted.org/packages/f6/39/c914445c321a845097ce4f6ac7de9a18228a77b766272125a1ce00d851eb/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:898f0e9068ca27d37f8e83a5b962821df851532e6c4a7d615c1c033f9da6eedf", size = 225157, upload-time = "2026-07-07T14:34:09.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f2/c0d4b8508565a36bc5c624e88ed297f5b0b1095011034d7f5b83a69908b5/charset_normalizer-3.4.9-cp314-cp314-win32.whl", hash = "sha256:c1c948747b03be832dceed96ca815cef7360de9aa19d37c730f8e3f6101aca48", size = 151095, upload-time = "2026-07-07T14:34:10.901Z" }, + { url = "https://files.pythonhosted.org/packages/49/fd/a1d26144398c67486422a72bf5812cda22cb4ccfcd95a290fb41ceb4b8e2/charset_normalizer-3.4.9-cp314-cp314-win_amd64.whl", hash = "sha256:16b65ea0f2465b6fb52aa22de5eca612aa964ddfec00a912e26f4656cbef890b", size = 162796, upload-time = "2026-07-07T14:34:12.47Z" }, + { url = "https://files.pythonhosted.org/packages/20/95/d75e82f8ce9fd323ebf059c16c9aadefb22a1ecde13b7840b35835e4886c/charset_normalizer-3.4.9-cp314-cp314-win_arm64.whl", hash = "sha256:40a126142a56b2dfc0aacbad1de8310cbf60da7656db0e6b16eebd48e3e93519", size = 153334, upload-time = "2026-07-07T14:34:14.044Z" }, + { url = "https://files.pythonhosted.org/packages/00/5e/17398df3a139985ba9d11ed072531986f408c8fca952835ef1ab1820c02b/charset_normalizer-3.4.9-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:609b3ba8fcc0fb5ab7af00719d0fb6ad0cb518e48e7712d12fd68f1327951198", size = 338848, upload-time = "2026-07-07T14:34:15.688Z" }, + { url = "https://files.pythonhosted.org/packages/cd/91/7253a32e86b7e1d1239b1b36ba6dd0f021a21107ab33054b53119cc083b9/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51447e9aa2684679af07ca5021c3db526e0284347ebf4ffcec1154c3350cfe32", size = 223022, upload-time = "2026-07-07T14:34:17.248Z" }, + { url = "https://files.pythonhosted.org/packages/cb/32/2e64bd2be10e89c61e57ebe6a93fd98ae88eb7ebe414b5121f22c96c69eb/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cc1b0fff8ead343dae06305f954eb8468ba0ec1a97881f42489d198e4ce3c632", size = 241590, upload-time = "2026-07-07T14:34:18.813Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ef/d96ec496cfea0c21db43b0ad03891308b02388d054cc902cf0e5a1ad6a88/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa36ec09ef71d158186bc79e359ff5fdd6e7996fe8ab638f00d6b93139ba4fcf", size = 239584, upload-time = "2026-07-07T14:34:20.52Z" }, + { url = "https://files.pythonhosted.org/packages/d4/ce/9af95f7876194bd7a14e3dfe4a4de2e0bff02666a3910d72beafd06cc297/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df115d4d83168fdf2cae48ef1ff6d1cb4c466364e30861b37121de0f3bf1b990", size = 230224, upload-time = "2026-07-07T14:34:22.189Z" }, + { url = "https://files.pythonhosted.org/packages/52/94/af74dde74a3996bd959c350709bfe50e297823d70a8c1cbd54b838880863/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f86c6358749bd4fda175388691e3ba8c46e24c5347d0afd20f9b7edfc9faf07d", size = 212667, upload-time = "2026-07-07T14:34:23.857Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f0/f1c4fe746c395922961b5916ed1d7d6e7d4c84851d19ed43cc89980ec953/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:32286a2c8d167e897177b673176c1e3e00d4057caf5d2b64eef9a3666b03018e", size = 227179, upload-time = "2026-07-07T14:34:25.586Z" }, + { url = "https://files.pythonhosted.org/packages/e4/56/6c745619ac397e8871e2bcd3cea1eec86b877488f33888b3aef5c3ed506e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:83aed2c10721ddd90f68140685391b50811a880af20654c59af6b6c66c40513c", size = 225372, upload-time = "2026-07-07T14:34:27.212Z" }, + { url = "https://files.pythonhosted.org/packages/78/ad/98aae8630ac71f16711968e38a5acfecce41b778bf2f0312851020f565a8/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cd6c3d4b783c556fa00bf540854e42f135e2f256abd29669fcd0da0f2dec79c2", size = 215222, upload-time = "2026-07-07T14:34:28.774Z" }, + { url = "https://files.pythonhosted.org/packages/f7/40/9593d54209765207a7f11073c06494c1721e4ca4a0a426c597679bf7f91e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ee2f2a527e3c1a6e6411eb4209642e138b544a2d72fe5d0d76daf77b24063534", size = 231958, upload-time = "2026-07-07T14:34:30.345Z" }, + { url = "https://files.pythonhosted.org/packages/b1/27/693ee5e8a18191eb38647360c51cd505013e2bd3b366aa43fd5344c21e3c/charset_normalizer-3.4.9-cp314-cp314t-win32.whl", hash = "sha256:0d861473f743244d349b50f850d10eb87aeb22bbdcc8e64f79273c94af5a8226", size = 155580, upload-time = "2026-07-07T14:34:31.884Z" }, + { url = "https://files.pythonhosted.org/packages/80/3f/bd97d3d9c613013d07cb7733d299385b41df37f0471310f5a73dc359f0b8/charset_normalizer-3.4.9-cp314-cp314t-win_amd64.whl", hash = "sha256:9b8e0f3107e2200b76f6054de99016eac3ee6762713587b36baaa7e4bd2ae177", size = 167620, upload-time = "2026-07-07T14:34:33.438Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c6/eee9dca4439b1061f76373f06ea855678cc4a64c1c3c90b50e479edbb8eb/charset_normalizer-3.4.9-cp314-cp314t-win_arm64.whl", hash = "sha256:19ac87f93086ce37b86e098888555c4b4bc48102279bae3350098c0ed664b501", size = 158037, upload-time = "2026-07-07T14:34:35.018Z" }, + { url = "https://files.pythonhosted.org/packages/98/2b/f97f1c193fb855c345d678f5077d6926034db0722df74c8f057020e05a25/charset_normalizer-3.4.9-py3-none-any.whl", hash = "sha256:68e5f26a1ad57ded6d1cfb85331d1c1a195314756471d97758c48498bb4dcdf5", size = 64538, upload-time = "2026-07-07T14:34:56.993Z" }, +] + +[[package]] +name = "click" +version = "8.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" }, +] + +[[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 = "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.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/e4/8d187ea29c2e30b3a09505c567513077d6117861bde1fbd997a167f262ec/griffelib-2.1.0.tar.gz", hash = "sha256:762a186d2c6fd6794d4ea20d428d597ffb857cb56b66421651cbba15bdd5e813", size = 216234, upload-time = "2026-06-19T12:05:42.278Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e4/d3/5268aeabf2ad82658c4e2ff3a060648d0f02f3926cb53247c0e4d0dab49e/griffelib-2.1.0-py3-none-any.whl", hash = "sha256:cc7b3d2d2865ad0b909fcc38086e3f554b5ea7acbaa7bbb7ecaa3f5dfb7d9f00", size = 142560, upload-time = "2026-06-19T12:05:38.742Z" }, +] + +[[package]] +name = "hypothesis" +version = "6.164.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/ac/7b76103bd74d8457e4de0c6a6c3a26ac6327016438bde125e0a3de83a5b8/hypothesis-6.164.0.tar.gz", hash = "sha256:5d63d263d8c71b571638c18d9591f6e34b836c60a12469e9d9105c1c785f00f1", size = 492022, upload-time = "2026-07-30T12:39:49.085Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/fe/d5b75a55892b33e72945f82efc71f645d29c0bfdb9f00727f7535a52edcc/hypothesis-6.164.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:14b861ac3353f8643b82a3ba76b8a0a54d2a06160c32b9a1f64a8ab41b179089", size = 771561, upload-time = "2026-07-30T12:39:00.404Z" }, + { url = "https://files.pythonhosted.org/packages/1c/b0/2f01e9efc7267446bad0e2a68f7472daa174a72553d213b16aefe44b2bda/hypothesis-6.164.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:3d8c8bb00a4b86ae90b9ad41f3e1c99d016ec3e64c0ff9d676a4bb7be4f56948", size = 767079, upload-time = "2026-07-30T12:39:23.123Z" }, + { url = "https://files.pythonhosted.org/packages/c3/26/d7bcd26b58e1df2bd39116b924b2a72676215d9650e68cbff9a629c3ce30/hypothesis-6.164.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e80e3ba8eaf37664eaa0f2625cef120b330b128a7df570210cf8be4f5ae65aaa", size = 1096364, upload-time = "2026-07-30T12:38:49.972Z" }, + { url = "https://files.pythonhosted.org/packages/9d/17/99fe7ea866935da83444c3ef7885a14fc7349d96ff61c6faebd37ef4edf2/hypothesis-6.164.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8cdf70f821e2d2f3a0bccaab29830aea8aefb63a77806e7e91246fb65a10c8d3", size = 1124963, upload-time = "2026-07-30T12:39:13.1Z" }, + { url = "https://files.pythonhosted.org/packages/38/e8/df08be6296cbc1271d44e81f8ff9dcd6267a07552fb768e0fdc166e93d40/hypothesis-6.164.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bcc3743e22b3cffa7267b4bc74d03628606e4a115495728e986a7be220987315", size = 1145886, upload-time = "2026-07-30T12:39:45.612Z" }, + { url = "https://files.pythonhosted.org/packages/4e/72/d5cf6fbfac40891d4281f630e16a6eb217ff56f97e350a06e0fd9322aa6a/hypothesis-6.164.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:730f09d4afcd8a918b3d589bfb6421e3b41c057aa57652a773ef4f512cc60836", size = 1101181, upload-time = "2026-07-30T12:39:05.194Z" }, + { url = "https://files.pythonhosted.org/packages/fb/ff/7ceb002329febffb678b65835ca6e9479a916325d088aadb0210d07f8252/hypothesis-6.164.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:9651cb48cb5a995295b442138d15d381547b935dcb0066fca7148a7955347400", size = 1137970, upload-time = "2026-07-30T12:39:16.076Z" }, + { url = "https://files.pythonhosted.org/packages/7c/8f/c12c697b73ca9ca24d8a913879e3e0a9db86479754c7221554247c701565/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:51d161d2655dd86143b370c577267b5b7b4c2e8fcb8a3f22c1a787572aad707c", size = 1270184, upload-time = "2026-07-30T12:38:54.436Z" }, + { url = "https://files.pythonhosted.org/packages/0e/2f/93f1c850c794fc9c80f5e61b3b20652126b865e6f57b348ae530446aadc7/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:e8a250552390128b57e3afe55035ce2c2cb1f6f0919817657854244f071bc5be", size = 1397987, upload-time = "2026-07-30T12:38:21.113Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b8/bab2546325e15e87c8518dfbca263c81dbc35d566c516d66c9da98a38b77/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:570cd51944e1cc3443847d8afa3d17fcf8aac475a1f744c9e7318a5ad7ef5c9f", size = 1270755, upload-time = "2026-07-30T12:38:51.571Z" }, + { url = "https://files.pythonhosted.org/packages/6a/4e/ea97dd39678a42dc5a24e3e2a64d3b950fad9fb1dcce8d7be5afb52a0335/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3a423e543055b3de5af7a7624c4285422541658367211fa293a3a57dd0ad01ba", size = 1312888, upload-time = "2026-07-30T12:38:30.847Z" }, + { url = "https://files.pythonhosted.org/packages/44/84/a6f2d5b12b23d65f16eb398750e430065f9d1f40f4418569e3b87ef58d23/hypothesis-6.164.0-cp310-abi3-win32.whl", hash = "sha256:f5e51490b2ce64c66138f24477d83c71b6224ab0ef65700da10187c464b54e94", size = 657401, upload-time = "2026-07-30T12:39:11.581Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d3/c5ee410daa594cac2d3fe1fbe5473f2390e35f4369e168a817e43341ce2f/hypothesis-6.164.0-cp310-abi3-win_amd64.whl", hash = "sha256:c9059dfbb039342b6590bbce207f90e0f9a80fdf45a404c68c2d3e598be78ab3", size = 663566, upload-time = "2026-07-30T12:39:30.27Z" }, + { url = "https://files.pythonhosted.org/packages/90/91/4942fe3f2f08b920368ed5a2937346259e843e382205513b4a0e70d2de9d/hypothesis-6.164.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:6bc3373fe550cf4d7cadb94ceaeb91e431e1418a96b7baa330487366eaa67d3c", size = 773152, upload-time = "2026-07-30T12:38:33.328Z" }, + { url = "https://files.pythonhosted.org/packages/eb/df/e66d052386a2b6c3e2f3eab32a02d7de3c9c59cd21d5dd58c08ecfa715f0/hypothesis-6.164.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2780297ca68929b153eff7effb2ebe67e9487d2fd9f49fa961007f8f2d236c9e", size = 764713, upload-time = "2026-07-30T12:38:48.59Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d5/5a50d14b8f04809e973c4dea884b367fef3663ff253c1205fa9e96229ef9/hypothesis-6.164.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b400bb4eb5a4a1e19cd5af3cc63817909e6b54b4603e04022bdba46860913d7", size = 1095160, upload-time = "2026-07-30T12:38:58.925Z" }, + { url = "https://files.pythonhosted.org/packages/58/01/781b19ce4382ec239c4dc6ec3bd9f195e69e5570f2814bbf04b5781ecb18/hypothesis-6.164.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7fca6632933fc506dd96926d9383483e4c0066c7ff62c748d059a3276da761e7", size = 1145199, upload-time = "2026-07-30T12:39:09.904Z" }, + { url = "https://files.pythonhosted.org/packages/e9/64/30e016863515ca01c1c738b05dd50491353d3ccae6432362e56e0c15d0da/hypothesis-6.164.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b9e1f6e89e5ec34735b727f3ce41d12e7f3b8efc162c91c8a225e10b54b504b4", size = 1267980, upload-time = "2026-07-30T12:38:18.733Z" }, + { url = "https://files.pythonhosted.org/packages/84/23/17eb8d67d59ecd3a820c905fbdf514e371dd7d01631e62a304cdd5793abe/hypothesis-6.164.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:51b0f967f608707b24ed37a298174ae6eec7899bfe3f271d1c3062c39ad66c06", size = 1312181, upload-time = "2026-07-30T12:38:36.056Z" }, + { url = "https://files.pythonhosted.org/packages/42/69/cff9f3cd9524252adda7c8e0e129dfc176e72f64fdf0bf1552d1ea43d78d/hypothesis-6.164.0-cp312-cp312-win_amd64.whl", hash = "sha256:5770df7d518bf867a9379e9081abd9e44db1d15473430e26a0946438c08c5926", size = 660690, upload-time = "2026-07-30T12:38:28.107Z" }, + { url = "https://files.pythonhosted.org/packages/ba/b4/729697380a22dc2ce8feae3c64b08bf3bd3c27e99c3706cb9bdac40c6fc8/hypothesis-6.164.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:29e7cb48974cb9fd87602e20625c890385793c6b56c18a957085a9c291f56ef8", size = 773046, upload-time = "2026-07-30T12:39:40.473Z" }, + { url = "https://files.pythonhosted.org/packages/38/35/72374f02d90dfda198afd8aac6b1e7d1184506f97e62ebcf3d2c1e5bf761/hypothesis-6.164.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1ff8c3819345be8dd15ee6588ee9383869a54c9a3d2232cce5e26b456424135d", size = 764659, upload-time = "2026-07-30T12:38:55.896Z" }, + { url = "https://files.pythonhosted.org/packages/6e/75/fb26388915d71e5949b98ccd0c9d95edcbe6b45d0370f177d43633d81ae2/hypothesis-6.164.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:33e88be13fac3ff7cb789a0b4cc43d99fb297db085f529fbb363188141c7d5bf", size = 1095078, upload-time = "2026-07-30T12:38:34.677Z" }, + { url = "https://files.pythonhosted.org/packages/be/63/f6da6e39667d39a1e44c5df82fbe6cff070c29aaffa9beb62a5322e7d8ae/hypothesis-6.164.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2e296d03a77355ce2e1c32e85a636b555edf0ddaaef277f98f1b84fe38a4595", size = 1145015, upload-time = "2026-07-30T12:39:26.487Z" }, + { url = "https://files.pythonhosted.org/packages/88/c7/55ba09727da3d9a60628c50e31e6083a36f403cb230f5e1a7bd1749a5c39/hypothesis-6.164.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:53698a1b246714539dd0ecc2d556cde613d74e9f7385ec4109e0651ab2d382d6", size = 1268027, upload-time = "2026-07-30T12:38:25.676Z" }, + { url = "https://files.pythonhosted.org/packages/ff/35/4789cade332f799b0e8f2f7ea0fe2aae6157a85e60f74497e316dd17a7e3/hypothesis-6.164.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:004c92c4b869f8e258f0641101b7743cae8420436f4465383f681c086ef95c9d", size = 1311895, upload-time = "2026-07-30T12:39:14.621Z" }, + { url = "https://files.pythonhosted.org/packages/12/8a/18d85e624f8631aec42daa8a2f07c6edcedb7385b2c0f375ba8a30cbd065/hypothesis-6.164.0-cp313-cp313-win_amd64.whl", hash = "sha256:4878f81fa92a580d3e16b53e64e01a9d9fe1dca5973783558493a003138dbd36", size = 660656, upload-time = "2026-07-30T12:38:37.696Z" }, + { url = "https://files.pythonhosted.org/packages/c7/06/3c144d427799c7c72befb0bb3b199d419a89b96e1002fd8f0cc94c84ffb7/hypothesis-6.164.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:9110010bdf6deb3ba9134f8ce8b683e8bb0fba108a351045c96d60c410eb6963", size = 773254, upload-time = "2026-07-30T12:38:38.919Z" }, + { url = "https://files.pythonhosted.org/packages/74/2d/b61a10d9e70df04aa7e8f34efef8e4afe364e8995c59f894e1c35b428214/hypothesis-6.164.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4df103e5d32b47d574c6e857d45361e2cba5a198d6dae4e4ee1bd248b3a2cbfa", size = 764786, upload-time = "2026-07-30T12:38:24.464Z" }, + { url = "https://files.pythonhosted.org/packages/99/68/7f80ac7bdffe78686135311c919534be411d4565c2a5ba38fd389880c553/hypothesis-6.164.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4abec95020960c0ed08e5be318d2bcdde79f2c6fc7785e368a9389d31d3e802a", size = 1095578, upload-time = "2026-07-30T12:38:57.422Z" }, + { url = "https://files.pythonhosted.org/packages/45/f9/97dcbac776bcf33cb4241b52111527821f707b60a84d03d0ea670b09a134/hypothesis-6.164.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9b106756cc9abd50ab1632541ea7b7223792d877a084726aa0304237d758181e", size = 1145207, upload-time = "2026-07-30T12:38:23.387Z" }, + { url = "https://files.pythonhosted.org/packages/a4/df/68184b6f71540435c895cf35ad1d67a3634a887c597ab38d3372c0d20186/hypothesis-6.164.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:11c4aab2ae6757fc4bc3bbf009487e24fd3490365817bbf40b9ec85a7e02fabb", size = 1268357, upload-time = "2026-07-30T12:38:52.946Z" }, + { url = "https://files.pythonhosted.org/packages/a0/76/6a6851dc8af89a5c0418937d38456417b2a1fc9db15c992b9cb43d53a7a3/hypothesis-6.164.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4713edecbc0969557ca135769a36d1e524c8e3b7a2b271de48d98fa29f681bf6", size = 1312183, upload-time = "2026-07-30T12:39:28.604Z" }, + { url = "https://files.pythonhosted.org/packages/2f/19/83adeb1f8f045bd8a1ab9822d0c3db28b337d37fff01d809fcd6e3ea70f8/hypothesis-6.164.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:e6882d316c390d33c55ec8f1675f35ab238d7c0473ccf8d235c69eaef6c621b9", size = 604771, upload-time = "2026-07-30T12:39:33.579Z" }, + { url = "https://files.pythonhosted.org/packages/0b/62/fcb48ebfbccdc5b695de175b9d1d344b3688782150f0603124bb70c0891b/hypothesis-6.164.0-cp314-cp314-win_amd64.whl", hash = "sha256:7c3357633b38bca8c927fd90d02b39a0a3f35f24cdbcfb2fb1dcf69a3f63bd85", size = 660570, upload-time = "2026-07-30T12:39:43.898Z" }, + { url = "https://files.pythonhosted.org/packages/42/61/5857da7db0435fa69df658a9eafba62eb8a1319454005ce2a0d97f6f9e4d/hypothesis-6.164.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:53152cb549f52d661c47768d0d12a192ef26a7a9758a7f13b8ec41e8e63d6325", size = 771839, upload-time = "2026-07-30T12:38:26.842Z" }, + { url = "https://files.pythonhosted.org/packages/6c/9c/22292a9dab1c544362d1759244132c7d71a9d9d5eda5d454ec735fba6bd3/hypothesis-6.164.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:cee7898ad84b63da6506ae48483bb36f319a25ea4c2b1d2df47d021cc4080c24", size = 763363, upload-time = "2026-07-30T12:38:20.042Z" }, + { url = "https://files.pythonhosted.org/packages/e8/29/cc0c6e9a065a32f93fe52dde746232f007d2cabf619d4e7b1b37bd34c424/hypothesis-6.164.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0def33f0d236e54144a5218997e4492925144d4615f25fdbb4ac8e47b7b709e6", size = 1094171, upload-time = "2026-07-30T12:39:35.158Z" }, + { url = "https://files.pythonhosted.org/packages/a7/59/37040d0776a29d4bc6d0ca9a50ca2755200007e4a8ddc27b010115b69c85/hypothesis-6.164.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:471fd80d70f2df606b1320276168bc2c6007a586124a1d81628264ccb9266f68", size = 1144089, upload-time = "2026-07-30T12:38:43.024Z" }, + { url = "https://files.pythonhosted.org/packages/fa/10/5235ed3c090a2f12fa15cc1d08e5a36cfa31bc0607c45199b0806e930ab4/hypothesis-6.164.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2eb285756aee62890fd08d6e97cf77651dfe7c093ceac094df52120a7a8dbe68", size = 1266595, upload-time = "2026-07-30T12:39:36.979Z" }, + { url = "https://files.pythonhosted.org/packages/7f/97/ffc4cee4dfdffe658e839d5f4df72ae3fa7bfea9401550b475d9700e0ee2/hypothesis-6.164.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:7c5215b5568968c35c6e124e5a4a8068f80419d6171414ddf735b49e1df1ab59", size = 1310998, upload-time = "2026-07-30T12:38:45.788Z" }, + { url = "https://files.pythonhosted.org/packages/dd/08/681d4a272cd2812151581c3328e41a80a34e420d676e419a25b4b9dc2291/hypothesis-6.164.0-cp314-cp314t-win_amd64.whl", hash = "sha256:a845e59fae87bb47a6fb84e0d5adb5679b3b55042fc3f8791da91486103cfbf0", size = 660724, upload-time = "2026-07-30T12:38:40.341Z" }, +] + +[[package]] +name = "idna" +version = "3.18" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[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.10.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/29/6f/da4c6aea59b3001f2e8c0ec7497475aadaf3b021c10cab5b2858f0f32b26/markdown-3.10.3.tar.gz", hash = "sha256:3589362618f743188b4d955b874402bc814f4f83f544dc207719f4baa7d9c45f", size = 372596, upload-time = "2026-07-30T19:05:29.005Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/69/4a5af2bc115a9a33fefe51709749de8262be3f9ba063d1753a837cdbc49c/markdown-3.10.3-py3-none-any.whl", hash = "sha256:fa6c92a00a4a3c98b22728c64a935ae1928250ae65058a6ded814d2cc29a4cea", size = 110757, upload-time = "2026-07-30T19:05:27.883Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[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.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/c0/f641843de3f612a6b48253f39244165acff36657a91cc903633d456ae1ac/mkdocs_autorefs-1.4.4.tar.gz", hash = "sha256:d54a284f27a7346b9c38f1f852177940c222da508e66edc816a0fa55fc6da197", size = 56588, upload-time = "2026-02-10T15:23:55.105Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/de/a3e710469772c6a89595fc52816da05c1e164b4c866a89e3cb82fb1b67c5/mkdocs_autorefs-1.4.4-py3-none-any.whl", hash = "sha256:834ef5408d827071ad1bc69e0f39704fa34c7fc05bc8e1c72b227dfdc5c76089", size = 25530, upload-time = "2026-02-10T15:23:53.817Z" }, +] + +[[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.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/b6/e858701499d57eee8b3fd8e78168083956c6683ddbe727b46758b19e1119/mkdocstrings_python-2.0.5.tar.gz", hash = "sha256:3a4d92556ad39637e88af94a5374213af9a8e3040c3824ceaed04b486c017594", size = 199578, upload-time = "2026-06-19T10:41:08.868Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/fc/10ab7e80650a9c9e8f4f1105f8c8e73567f88ed0c06ada589ab81d38687c/mkdocstrings_python-2.0.5-py3-none-any.whl", hash = "sha256:30c837bbff016549f659fcba6539ac351303f0fd7e713c89a040611072236e9d", size = 104951, upload-time = "2026-06-19T10:41:07.378Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/7b/14687aa674250e5e546f616f486b0d56d3631cd5b2415739141ce40bdcea/numpy-2.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2c889b56fe48b1018f764b0eec8df59ab654e9148aa91faa12596043500de277", size = 16801574, upload-time = "2026-07-04T17:06:12.423Z" }, + { url = "https://files.pythonhosted.org/packages/e1/19/cc5bb2a3f2913d27d6dbb2c78d25921fabaedc6741d4a5a615a11f3c5bf3/numpy-2.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab451b59c5643c570974c43aef780703ef1d3b4965d2be07afd530615a9358d1", size = 11772250, upload-time = "2026-07-04T17:06:15.726Z" }, + { url = "https://files.pythonhosted.org/packages/42/77/fdf34a71dd30f54979b18603bee915e0aaf825b07afe79acd60b04b691e2/numpy-2.5.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:78798bd5b9ad744056af8efa90e3b9ddaa53272a0848a483084a1cc0a13b2dc0", size = 5331516, upload-time = "2026-07-04T17:06:17.913Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e2/eb7efa015b4cce41e2517bf182a7fce0d7d5b9d9ed76a29bfa0f4fe4505c/numpy-2.5.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:2ae0ca40bcb22d6ba59c1dfd5446f49940b0f2d821fde133f10dda11f816b84e", size = 6664863, upload-time = "2026-07-04T17:06:20.02Z" }, + { url = "https://files.pythonhosted.org/packages/a9/4b/a2b32dd94ee9ffbeecb28152240042a3949db33b1c834d44090b80e1b3b8/numpy-2.5.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61ac47e772e6b8ea489e1d2f441a34c5c3ac17327e7ce294cbdf535795ad4e75", size = 15167977, upload-time = "2026-07-04T17:06:21.621Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a9/6e73d68500f80773f65f0654ea932019d6694329a0eb0ed0533de38df376/numpy-2.5.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:59fda5e192b570217ec2580c96f00e9a7e12ef6866a900eb089b62c1a32545ca", size = 16672469, upload-time = "2026-07-04T17:06:24.064Z" }, + { url = "https://files.pythonhosted.org/packages/24/7d/ad3e59015135f5261c95fd4cafeff159c955febd83a99a1d9250c4233815/numpy-2.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f7119ebff1a9829e9f431a4f9d28e703023bb6b9fe7c8f724467dbfc27c94ab3", size = 16527531, upload-time = "2026-07-04T17:06:26.69Z" }, + { url = "https://files.pythonhosted.org/packages/83/d0/a39b2fbcde9cb17a1dac678f254b33a6336298af9df338824c685425d5e8/numpy-2.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e824c2acf8862052246be5a44c15da1777940c60d010dd2aab897824d9c430f9", size = 18431940, upload-time = "2026-07-04T17:06:29.521Z" }, + { url = "https://files.pythonhosted.org/packages/04/12/cff070947791c1ed425ff76413189adbdc2fbe215eba7ce7fa454a03c7f8/numpy-2.5.1-cp312-cp312-win32.whl", hash = "sha256:08d60c810432eb83360958dea0999ac4cfb94531ea8efcbf0b7f277c2068aeb2", size = 6066764, upload-time = "2026-07-04T17:06:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/65/66/53f31807a48a750f9d748da273bc3fcedd12b27ff1f3e373bfec55ef2dc0/numpy-2.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:f7d60026c0bdb1380e83bfa7a0419c4577ee4b9a08880afcb6dadeb74c649fa2", size = 12430966, upload-time = "2026-07-04T17:06:34.926Z" }, + { url = "https://files.pythonhosted.org/packages/2b/2a/d1a88066b1c14186f5d3c0d18c94f17b064511982bab0578d49ee9d43c29/numpy-2.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:17a25e09640602e10bc8de0e6fa2b3fd68eedd84ba6d7842dc8f32f9ab87bd0b", size = 10350488, upload-time = "2026-07-04T17:06:37.785Z" }, + { url = "https://files.pythonhosted.org/packages/eb/07/ec2a3f0c91761581d4b7104a740791800025983f9a4dc4e73f91a99aeac4/numpy-2.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0bfebd8695f9863592fe744be833a258120b14a9f39da255e8aa8fade2c0ddd1", size = 16796419, upload-time = "2026-07-04T17:06:40.37Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ab/ddb499fc4f8780354395face5b65c7fd107bcd6e1d667a5f07d046956f6f/numpy-2.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:30b44a6b53a7ae63c54c089a8726e5563ed302716c5b7ccc85afade40b0e7ff6", size = 11765832, upload-time = "2026-07-04T17:06:42.768Z" }, + { url = "https://files.pythonhosted.org/packages/88/b3/3c28c558a09fc72100c646dac6d2fce8e834c471b0edca01a29996706117/numpy-2.5.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:6165343f81b56ef8f514f396989e529b61d9dc709b99421b07e9f3e698e2287d", size = 5325143, upload-time = "2026-07-04T17:06:45.466Z" }, + { url = "https://files.pythonhosted.org/packages/5e/0e/ce19b985bb15c596f4f05954e76cccc77c845083b3b8f938a6c68e523128/numpy-2.5.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4939237038ada79308dda3204ac6462df056b5672b2e25db1149cf873668b3e1", size = 6659749, upload-time = "2026-07-04T17:06:47.288Z" }, + { url = "https://files.pythonhosted.org/packages/2e/20/1ee6614d64332a1bba6411f38e68cb79eec1b2459e20a623777c5c5492a2/numpy-2.5.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c6759f538fb912fc46de0a6b1758ccf7b57bc7c7ebebc23974fdac3de8db0cd", size = 15164716, upload-time = "2026-07-04T17:06:49.494Z" }, + { url = "https://files.pythonhosted.org/packages/ed/a7/2bcd3fdbb87804755c35b729bf8709d62025c5f4cfd7d5b2415997097515/numpy-2.5.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9726558e8db4a5bf7929a70ae50f63abda4daf0efe810e3bfbab95976f75fc1a", size = 16661440, upload-time = "2026-07-04T17:06:52.061Z" }, + { url = "https://files.pythonhosted.org/packages/fc/d7/a41e3310c886fe457d36e670bbf24fae411aca8a7b6ad92a32afd924077c/numpy-2.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3935f3b419b244a02732676fa5317a9193cc596a4c0646db07e5b421229ac9f7", size = 16526305, upload-time = "2026-07-04T17:06:54.605Z" }, + { url = "https://files.pythonhosted.org/packages/53/75/4333a9a707c1edd3a4e1a0c58eca52c0f31e55089fa80db02b5565b24df7/numpy-2.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dc932a65ded7ce9013d120845a2514dcccb1a67bfc8deb8d37633762951904a6", size = 18423008, upload-time = "2026-07-04T17:06:57.54Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/e314a32b1c11a2ffe818ddad3a57b50b4b6e1b6c487192eb50cdef0415d0/numpy-2.5.1-cp313-cp313-win32.whl", hash = "sha256:4b4ff1608417eb7a59da7b967bbb798cacfe071d2caf526a24281cd562072ed9", size = 6063885, upload-time = "2026-07-04T17:07:00.14Z" }, + { url = "https://files.pythonhosted.org/packages/10/70/800b3fca480af32df9e8ea9f3d4a0c8feb4b32d7f195d174eabbda4829ad/numpy-2.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:6c3fe51bc6a16453d452997053454f309e8e0ed7b42d6b361ce4ac8c32913d74", size = 12425674, upload-time = "2026-07-04T17:07:02.387Z" }, + { url = "https://files.pythonhosted.org/packages/8b/0b/196350c122f50f6ca56846f2d71efd5e0d24b7b2e07355e019b2e2c7a11e/numpy-2.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:f7feb014281029e628ba2d5a007407443b06e418b6fe451d1e2adcbc8eba0107", size = 10350256, upload-time = "2026-07-04T17:07:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/db/f4/731b6085a83faf6ca843394cbd5e217280c214399f7e8b21b9f552af0ae2/numpy-2.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7c786fe9a5bbe360022e584c5a34cf6b54265c71bd7ec8ac3d8fec38968071f8", size = 16795063, upload-time = "2026-07-04T17:07:07.374Z" }, + { url = "https://files.pythonhosted.org/packages/bf/64/0e215f2048dd11a55bb989ed41b3585ef57452404e638d703a211a3e4157/numpy-2.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:32985c896d897419ef8da6917872d80b78ad0ea26d85b23245c7366ffde76d75", size = 11776652, upload-time = "2026-07-04T17:07:09.907Z" }, + { url = "https://files.pythonhosted.org/packages/b5/59/2b844c7a6e9deff69b404a66221e1542937734f65d5e6e39411876053862/numpy-2.5.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:efd736408cc97c79b9e6917338dfc8f06013b2274f992e96b1d9a81a71e2a2c2", size = 5335944, upload-time = "2026-07-04T17:07:12.227Z" }, + { url = "https://files.pythonhosted.org/packages/86/51/9bf7cb2cabcebc9e017e4ec7e6322b378317a542c08b4cb68479c1efc716/numpy-2.5.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:ab84dc6b074fa881cae55bea94cc4f68e285181ba7f32497bf7dee6b1496165b", size = 6656266, upload-time = "2026-07-04T17:07:14.368Z" }, + { url = "https://files.pythonhosted.org/packages/83/3e/fb7615b211b82a32f44d5180a6d421b61f84d4fadd578b48ba4ac34e189f/numpy-2.5.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:caf3e317d33d60c37986b452613f4ab51246d0691350c03d0cb4a898627f4a95", size = 15179720, upload-time = "2026-07-04T17:07:16.272Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/0f992cb24560673496c5d68de61913b57166ce530ffda07c1f280e0cc464/numpy-2.5.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54ad769f17bc2d833b620851989f62054fb9ab93c969d9e1dc3c8e3d56beea21", size = 16664835, upload-time = "2026-07-04T17:07:19.021Z" }, + { url = "https://files.pythonhosted.org/packages/a2/2f/97d6475ee91afe2587797d09446f9d3e475ad4cb681662d824809327b75a/numpy-2.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c12afb53450fa976d4c681c50a7423729a4c51c0465ed9f32b8a9cabbc472373", size = 16539135, upload-time = "2026-07-04T17:07:22.015Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5b/4db81e4ba0be7e2776b1de68c82aa862c7f8ec27e1b4927d4ae075e20678/numpy-2.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e8c11c405efc5ff6816d5983c96cdfa215bab3428961243af3ff59b228490438", size = 18426684, upload-time = "2026-07-04T17:07:24.941Z" }, + { url = "https://files.pythonhosted.org/packages/1f/64/c0ba2d90724d450279a7df8f32057241070250a26a7e2b5337d77347f481/numpy-2.5.1-cp314-cp314-win32.whl", hash = "sha256:f2479a47f8d5932d1718168a681ad6e536a9df484c83cfcf9de365e164537ace", size = 6116103, upload-time = "2026-07-04T17:07:27.622Z" }, + { url = "https://files.pythonhosted.org/packages/c1/1a/837f9ed7405adcd7a40538792eb169eddd8fa5630c16a1ef49dae71a30f4/numpy-2.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:24d0eb82c0541d3415a33425db64ae439dffccd7b4dbcb30e7c35120205c506a", size = 12562177, upload-time = "2026-07-04T17:07:29.887Z" }, + { url = "https://files.pythonhosted.org/packages/22/ed/49707938b6dd0a78a9178dd93227dc89e4c11af47f5c798d70366e8d0483/numpy-2.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5a4c988b38d261deeeaad9954e3deb091ad905c94e8bb6708654ef1d97f286b0", size = 10627739, upload-time = "2026-07-04T17:07:32.568Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c7/bb4b882cfe7f299cbc8b66e42e7dd78cf9d14e40f9469fc5e3db7e15b3bd/numpy-2.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a33276be12fa045805f477f22482088b66bb758ffbe89a9d21457de863a32e22", size = 11894709, upload-time = "2026-07-04T17:07:34.941Z" }, + { url = "https://files.pythonhosted.org/packages/40/3f/5af7f4a7f6224aef48017aa82bb6174c7a659d724be0c75017b7e64a55b4/numpy-2.5.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:f089d7b00756190aacf1f5d34bdf38c3c430ac82b4f868f8cede73380460fce7", size = 5453810, upload-time = "2026-07-04T17:07:37.495Z" }, + { url = "https://files.pythonhosted.org/packages/20/c9/3474309bc94d634d3f9c3eddf03250ecb8c22cd948ef16fef69a77cc5d7b/numpy-2.5.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:09e9bfd8d2cf479c7d174804fb3811c53a8e9f20a37444008606b57d6b7a826d", size = 6761189, upload-time = "2026-07-04T17:07:39.563Z" }, + { url = "https://files.pythonhosted.org/packages/90/8a/558ae39fdd55d7e7f7fef9a84a6e964ac6b23edbd2a07e52bb084500507d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e68d8dd1e7eba712948f2053a29ec86917bc70ba1358df869d9f06649ef9cf09", size = 15225039, upload-time = "2026-07-04T17:07:41.682Z" }, + { url = "https://files.pythonhosted.org/packages/63/27/ca7392b2d030277bdf0273e7d23255b3ee57d57a7c170a6f4fb3981e1e5d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99d5095fa265a0c4152e7bb12759e14381ef5496152f1ce58f44bdf55c44beb4", size = 16701306, upload-time = "2026-07-04T17:07:44.611Z" }, + { url = "https://files.pythonhosted.org/packages/02/42/03d53ae7996c44d4374a8262e9dc41671fd56cbb98f7d47ef85cf5da4c6b/numpy-2.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab87a91b3cc3382b8956095bd8f95e00cf679bb81554339be1a2ba404a1473c1", size = 16589955, upload-time = "2026-07-04T17:07:47.694Z" }, + { url = "https://files.pythonhosted.org/packages/7b/15/6c1784ae469640e65db111e9a34b3d0f14d91e8a38b9ce34810ced370dbb/numpy-2.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:224ca51130ef7da85bea2191625181cb4f337f9cb64b471f10c1a12aa8b60077", size = 18464252, upload-time = "2026-07-04T17:07:50.684Z" }, + { url = "https://files.pythonhosted.org/packages/94/a8/f98e50356cf167df656c526c2dfeec2d7dde182f2a3da4b458a5938e2776/numpy-2.5.1-cp314-cp314t-win32.whl", hash = "sha256:6eab239876581b2b3c5a242281b6007bbdbcd1c7085d7709bb57c5929b11e6bf", size = 6263298, upload-time = "2026-07-04T17:07:53.445Z" }, + { url = "https://files.pythonhosted.org/packages/72/ac/96ae880cdecad0b3275d9359fcec72667b49a4863c9f12942e43679dda02/numpy-2.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:83ce9c80d5b521b0d77ddcbe5447c218d247929b6cc056ca5351342accfff0af", size = 12748623, upload-time = "2026-07-04T17:07:55.384Z" }, + { url = "https://files.pythonhosted.org/packages/a1/5a/4d2b1601df3602dba7a14f3348ba9bfe94a18adb428e693df6154c293831/numpy-2.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:5a6db61f9aaa57e369905c67d852045d3c4f7126405b29d09b19dec118e9c9cb", size = 10697674, upload-time = "2026-07-04T17:07:58.506Z" }, +] + +[[package]] +name = "packaging" +version = "26.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, +] + +[[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.11.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/78/9b/560e4be8e26f6fd133a03630a8df0c663b9e8d61b4ade152b72005aec83b/platformdirs-4.11.0.tar.gz", hash = "sha256:0555d18370482847566ffabcaa53ad7c6c1c29f195989ae1ed634a05f76ea1e0", size = 31953, upload-time = "2026-07-21T13:09:36.565Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/68/d8d58938dfb1370b266a1a729e6d77a985be23689a0496498ee17b2cbf90/platformdirs-4.11.0-py3-none-any.whl", hash = "sha256:360ccded2b7fce0af0ff80cc8f5942a1c5d99b0e856033acb030bfc634709e74", size = 23247, upload-time = "2026-07-21T13:09:35.422Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[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.1.1" +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/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[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.15.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/06/ae069393fc66e8ff33036d4b368003833bf6e88ccf182e17e7a2f1c754fd/ruff-0.15.22.tar.gz", hash = "sha256:3f15175b1fb580126f58285a5dae6b2ea89000136d980c64499211f116b54809", size = 4785063, upload-time = "2026-07-16T15:14:13.244Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/18/ee54b7ae1e121be7a28ea6da4b67564ebb0530e183a54415ab7e3bcd2c4e/ruff-0.15.22-py3-none-linux_armv6l.whl", hash = "sha256:44423e73493737f5e7c5b41d475483898ff37afcdae38bc3da5085e29af1c2d8", size = 10781258, upload-time = "2026-07-16T15:13:19.452Z" }, + { url = "https://files.pythonhosted.org/packages/2f/d2/2520cb14761ddbeaf57642a76942fc36adcbdbe53b4532241995f6fc485c/ruff-0.15.22-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b82c6482946e9eda7ff2e091d25b8bad3f718684e1916d41bd56873cee05b697", size = 10999477, upload-time = "2026-07-16T15:13:23.318Z" }, + { url = "https://files.pythonhosted.org/packages/c9/10/74e53572aa758dfaa678c2a2646b5c5515d884b7ca56be4d2ce03ca4b560/ruff-0.15.22-py3-none-macosx_11_0_arm64.whl", hash = "sha256:11c1c715af53a09f714e011106bffc419751ec8232fcb5da42173284ea3fec6f", size = 10466716, upload-time = "2026-07-16T15:13:26.162Z" }, + { url = "https://files.pythonhosted.org/packages/1e/cc/44eaaf0844e028182f2d0a8f2190d0f359159aed0a9e5ab861d892f1ae2a/ruff-0.15.22-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:742a29cf29bddb7c8327895d6a10e0e6c5b38a96dd407af9b5d0857f809c0576", size = 10892644, upload-time = "2026-07-16T15:13:29.229Z" }, + { url = "https://files.pythonhosted.org/packages/9f/21/8edf559014d2b0f82beea19cfb713993ad802ccda16868769979c6090a84/ruff-0.15.22-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:72af58b951b0ae395935ae79763dc349bc0eb706319d28f7a33ad2cfb3cfc178", size = 10576719, upload-time = "2026-07-16T15:13:32.35Z" }, + { url = "https://files.pythonhosted.org/packages/bf/1e/3a13abd392a3b50b62e5938a831f9ab6e588358cacad5c18545b716d2182/ruff-0.15.22-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:62d425005c1835eb24e2ee4161cb90e8db263415f4a71c8c72c33abaa6c0c224", size = 11376494, upload-time = "2026-07-16T15:13:35.958Z" }, + { url = "https://files.pythonhosted.org/packages/bf/3e/422d3d95bcf04dd78e1aeac22184d4f9a8fb2c01865d39d44618484a0317/ruff-0.15.22-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e8b9b3f8779a4f08c969defc3c8c35abffaa757e601ed5ae66d6d1db6519969a", size = 12208370, upload-time = "2026-07-16T15:13:39.185Z" }, + { url = "https://files.pythonhosted.org/packages/1e/91/5d065a0e0a02bf4813f5119ad278462eed081d2b832eb7c021ade0ec9e65/ruff-0.15.22-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1e0dd1b2e4d3d585f897a0d137cbf4eaf6223bef4e8ce34d6bb12556c5f9249e", size = 11581098, upload-time = "2026-07-16T15:13:42.132Z" }, + { url = "https://files.pythonhosted.org/packages/f6/f9/a0d4871d12fae702eb1f41b686caf05f1f8b124dc6db6f784f53d74918fa/ruff-0.15.22-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:365523eb91d9224e1bcb03b022fbf0facb8f9e23792a2c53d9d4b3924bdbdebb", size = 11399422, upload-time = "2026-07-16T15:13:45.2Z" }, + { url = "https://files.pythonhosted.org/packages/18/80/c843a5176cddbceb0b7e8dd41cf9993490796c1c469348d384f5a5c13c56/ruff-0.15.22-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:fabfd168afdf29fee5be98b831efa9683c94d7c5a3b58b9ce5a2e38444589a74", size = 11381683, upload-time = "2026-07-16T15:13:48.46Z" }, + { url = "https://files.pythonhosted.org/packages/d4/00/8485de0ae92239438a36cfc51350db9b9e85c9ebdfaea91b18e422706662/ruff-0.15.22-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:225dbf095a87f1d9f90f5fd7924d2613ee452a75a4308c63a8f50f761787aa7c", size = 10850295, upload-time = "2026-07-16T15:13:51.655Z" }, + { url = "https://files.pythonhosted.org/packages/fa/91/24977ec2ec72eaf15e4394ace2959fdff2dd1e14f03e005e838023407169/ruff-0.15.22-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1877d63b9d24ed278744f1523fd11b85540566d54641f97c566d7d9dc5ca5296", size = 10579640, upload-time = "2026-07-16T15:13:54.79Z" }, + { url = "https://files.pythonhosted.org/packages/9c/47/9b51216951974df1f263ac19da550d34252e0ed7218c25f10c5ef9ed7517/ruff-0.15.22-py3-none-musllinux_1_2_i686.whl", hash = "sha256:a1606c510bd7215680d32efab38965f7cdec3ef69f5170a3f4791404ffdd5262", size = 11105077, upload-time = "2026-07-16T15:13:57.915Z" }, + { url = "https://files.pythonhosted.org/packages/c2/47/20e9d4a3b8016778acea5fc32bb50d35d207500a17ddb529ffa6996feef8/ruff-0.15.22-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:630479b18625f5ffc373f77603a22a9f8ac0acd7ff0501178b5db28ec71e9c64", size = 11490980, upload-time = "2026-07-16T15:14:01.032Z" }, + { url = "https://files.pythonhosted.org/packages/4d/76/3f72d8fc38c1cb77b38c56a70da9d0c17700cc1cc50f9649c9d3c8f5ba71/ruff-0.15.22-py3-none-win32.whl", hash = "sha256:e5ba0e4a13fd14abbed2a77b517a3911290c6c6c59ef67784328d1668fab76cf", size = 10789165, upload-time = "2026-07-16T15:14:04.16Z" }, + { url = "https://files.pythonhosted.org/packages/cb/46/4965251734c2b6fcdca1b1b187d20bcac3af0ee5b083b89c910bb961ce3a/ruff-0.15.22-py3-none-win_amd64.whl", hash = "sha256:9be63ba1eb936acd2d1342fb8337c356353706fce233b2a15a09a97037e6acde", size = 11938297, upload-time = "2026-07-16T15:14:07.316Z" }, + { url = "https://files.pythonhosted.org/packages/57/c9/e69b1ff4c8b69093ef08b8919ab767af0569666865b39c30a8795d88d3c6/ruff-0.15.22-py3-none-win_arm64.whl", hash = "sha256:e1168075b72158510839f250027659cdd78476f40507dd517892304c41318661", size = 11298172, upload-time = "2026-07-16T15:14:10.51Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[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 = "urllib3" +version = "2.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +] + +[[package]] +name = "zarr-indexing" +source = { editable = "." } +dependencies = [ + { name = "numpy" }, +] + +[package.optional-dependencies] +testing = [ + { name = "hypothesis" }, +] + +[package.dev-dependencies] +docs = [ + { name = "griffe-inherited-docstrings" }, + { name = "mkdocs" }, + { name = "mkdocs-material" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "ruff" }, +] +test = [ + { name = "hypothesis" }, + { name = "pytest" }, +] + +[package.metadata] +requires-dist = [ + { name = "hypothesis", marker = "extra == 'testing'", specifier = ">=6.160.0" }, + { name = "numpy", specifier = ">=2" }, +] +provides-extras = ["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.5" }, + { name = "ruff", specifier = "==0.15.22" }, +] +test = [ + { name = "hypothesis", specifier = ">=6.160.0" }, + { name = "pytest" }, +] diff --git a/packages/zarr-metadata/.readthedocs.yaml b/packages/zarr-metadata/.readthedocs.yaml new file mode 100644 index 0000000000..828773818c --- /dev/null +++ b/packages/zarr-metadata/.readthedocs.yaml @@ -0,0 +1,43 @@ +# Read the Docs configuration for the zarr-metadata docs site, separate from +# the zarr-python site configured by the repo-root .readthedocs.yaml. The RTD +# project for zarr-metadata must set its configuration-file path to +# packages/zarr-metadata/.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. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- packages/zarr-metadata; + then + exit 183; + fi + install: + - pip install --upgrade pip + - pip install ./packages/zarr-metadata --group packages/zarr-metadata/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-indexing 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-metadata && mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html + +mkdocs: + configuration: packages/zarr-metadata/mkdocs.yml diff --git a/packages/zarr-metadata/CHANGELOG.md b/packages/zarr-metadata/CHANGELOG.md new file mode 100644 index 0000000000..c1e9f81a61 --- /dev/null +++ b/packages/zarr-metadata/CHANGELOG.md @@ -0,0 +1,346 @@ +# Release notes + + + +## 0.5.0 (2026-08-14) + +### Bugfixes + +- `JSONValue`'s array arm is now the covariant `Sequence["JSONValue"]` rather + than the invariant `list["JSONValue"] | tuple["JSONValue", ...]`. Values typed + with a narrower element type — a `list[str]` field on a TypedDict, a + `Sequence[float]` — now count as JSON values, and TypedDicts whose fields + carry precise types are now assignable to `Mapping[str, JSONValue]`. + Type-level cost, accepted deliberately: `Sequence` says nothing about the + concrete container and admits `str`/`bytes`, so runtime code narrowing a JSON + array must exclude `str`/`bytes`/`bytearray` — as it already had to, since + `str` was always a union arm. ([#4264](https://github.com/zarr-developers/zarr-python/pull/4264)) + +### Deprecations and Removals + +- Unified the naming grammar for SCREAMING_SNAKE constants with the one used for + type names. A constant's name is now a purely syntactic transformation of the + name of the `Literal` type it manifests, so the format version is spelled + `ZARR_V2`/`ZARR_V3` and comes first, matching the `ZarrV2`/`ZarrV3` prefix on + the corresponding type: + + - `ARRAY_METADATA_STORE_KEY_V2` → `ZARR_V2_ARRAY_METADATA_STORE_KEY` + - `ARRAY_METADATA_STORE_KEY_V3` → `ZARR_V3_ARRAY_METADATA_STORE_KEY` + - `ATTRIBUTES_STORE_KEY_V2` → `ZARR_V2_ATTRIBUTES_STORE_KEY` + - `GROUP_METADATA_STORE_KEY_V2` → `ZARR_V2_GROUP_METADATA_STORE_KEY` + - `GROUP_METADATA_STORE_KEY_V3` → `ZARR_V3_GROUP_METADATA_STORE_KEY` + - `CONSOLIDATED_METADATA_STORE_KEY_V2` → `ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY` + - `ARRAY_ORDER_V2` → `ZARR_V2_ARRAY_ORDER` + - `ARRAY_DIMENSION_SEPARATOR_V2` → `ZARR_V2_ARRAY_DIMENSION_SEPARATOR` + - `CONSOLIDATED_METADATA_KEY_V3` → `ZARR_V3_CONSOLIDATED_METADATA_KEY` + + The old names are removed, not aliased. This supersedes the 0.4.0 convention + under which type names put the format version first while constants put it + last: every constant that manifests a `Literal` type now follows the same rule + as that type. + + The last of those is the one rename the syntactic rule does not force: + `ZARR_V3_CONSOLIDATED_METADATA_KEY` manifests no `Literal` type, so it is + outside the rule and was renamed for consistency with its siblings. + + Digit runs stay glued to the token they follow, so spec vocabulary is + preserved: `Uint8DataTypeName` pairs with `UINT8_DATA_TYPE_NAME` (not + `UINT_8_...`) and `Crc32cCodecName` with `CRC32C_CODEC_NAME`. No dtype, codec, + chunk-grid, or chunk-key-encoding constant changed name. + + Constants that do not manifest a `Literal` type are outside the rule and are + unchanged: the `*_METADATA_*_KEYS_V2`/`_V3` key sets, the + `CANONICAL_*_HEX_FLOAT*` bit patterns, and `UNSET`. The key sets keep the + version-last spelling, so `zarr_metadata.model` exports both + `ARRAY_METADATA_REQUIRED_KEYS_V2` and `ZARR_V2_ARRAY_METADATA_STORE_KEY`. They + name validation policy rather than a spec document, have no paired type to + derive from, and renaming them would be a second breaking change buying only + cosmetic consistency — so it is deliberately deferred. + + `tests/test_public_api.py::test_constant_names_derive_from_their_type_names` + derives every constant name from the type it manifests and asserts they match, + so the two grammars cannot diverge again. + + Store keys also moved to the modules that describe the documents they name, + matching the package's layering (the `v2`/`v3` modules describe the specs; the + `model` layer is built on top of them). `ZARR_V2_ATTRIBUTES_STORE_KEY` now + lives in `zarr_metadata.v2.attributes` beside the `.zattrs` type it names, + rather than in the array model; the other five moved likewise, and + `ZarrV2AttributesStoreKey` is no longer an array-specific concept. + `zarr_metadata.model` re-exports all six, so + `from zarr_metadata.model import ZARR_V2_ARRAY_METADATA_STORE_KEY` is + unaffected. + + `CONSOLIDATED_METADATA_KEY_V3` moved to `zarr_metadata.v3.consolidated` and was + renamed to `ZARR_V3_CONSOLIDATED_METADATA_KEY` for consistency. It is not a + store key: unlike v2's `.zmetadata` file, v3 consolidated metadata is embedded + as an extension field inside the group's own `zarr.json`. + + All seven keys and the six store-key `Literal` aliases are now also exported + from the top-level `zarr_metadata` namespace, alongside the document types and + the rest of the spec vocabulary, so `from zarr_metadata import + ZARR_V2_ARRAY_METADATA_STORE_KEY` works. The model layer's validators, parsers, + type guards, and metadata key sets remain `zarr_metadata.model` imports. + + ([#4232](https://github.com/zarr-developers/zarr-python/pull/4232)) + +### Misc + +- The source distribution now ships an explicit allowlist (`/src`, `/tests`, + `/docs`, `/mkdocs.yml`, `/justfile`, `/CHANGELOG.md`) rather than whatever + happens to sit in the package directory, so an sdist both tests and documents + itself and cannot pick up scratch files from the tree it was built in. ([#4248](https://github.com/zarr-developers/zarr-python/pull/4248)) + + +## 0.4.0 (2026-07-29) + +### Features + +- Added `zarr_metadata.model`: frozen-dataclass models (`ZarrV2ArrayMetadata`, + `ZarrV3ArrayMetadata`, `ZarrV2GroupMetadata`, `ZarrV3GroupMetadata`, + `ZarrV2ConsolidatedMetadata`, `ZarrV3ConsolidatedMetadata`, `ZarrV3NamedConfig`) + that are canonical, semantically lossless representations of Zarr metadata + documents, plus structural validators (`validate_*` / `is_*` / `parse_*`). + Every v3 extension point (data type, chunk grid, chunk key encoding, codecs, + storage transformers) is held as `ZarrV3NamedConfig`: a name, configuration, + and `must_understand` obligation; nothing is interpreted. On the wire, an + empty configuration with the default obligation uses the spec's plain-string + shorthand. Model fields are annotated with the role alias + `ZarrV3MetadataField` (today exactly `ZarrV3NamedConfig`), so annotations + convey the logical meaning and stay put if the spec adds another field form. + + Validation is strict about what the types declare: v2 `dtype` / `order` / + `compressor` / `filters` / `dimension_separator` shapes and the fixed + `zarr_format` / `node_type` literals are all enforced. Every + `ValidationProblem` carries a machine-readable `kind` + (`missing_key` / `invalid_type` / `invalid_value` / `invalid_json`) so + consumers can dispatch on the failure mode without matching message strings, + and every ingestion failure — including missing store keys and undecodable + bytes in `from_key_value` — surfaces as `MetadataValidationError`. An + adversarial review added further structural checks: JSON booleans are not + accepted as dimension lengths, dimensions are non-negative, + `dimension_names` must have one entry per dimension of `shape`, `attributes` + and `configuration` values are JSON-checked recursively (like `fill_value`), + non-finite floats and non-standard JSON constants are rejected, abstract + mappings and sequences normalize to encoder-safe canonical containers, + v2 `shape` and `chunks` must have the same rank, non-null v2 filter pipelines + contain at least one filter, document `TypeIs` guards only narrow values that + already use the declared canonical containers, + and the inline consolidated-metadata envelope and entries are deep-validated + so the group validator's verdict always agrees with the model constructor. + + The v3 models expose `must_understand_fields`: the subset of `extra_fields` + not explicitly waived with `must_understand: false` (fields are implicitly + must-understand per the spec). Readers discharge the spec's fail-to-open + duty by subtracting the extension names they recognize; the model only + partitions by obligation, since recognition is reader-specific. + + Optional pydantic integration ships as `zarr_metadata.pydantic` (importing it + requires pydantic 2.13 or newer; the core package does not depend on it): one + `Annotated` + field type per model, validating raw documents through `from_json`, passing + core-model instances through unchanged, serializing via `to_json`, and + publishing JSON Schemas derived from private constrained document types that + mirror the independently expressible runtime rules. Cross-field cardinality + relations still require runtime validation. The instances are the core model + classes, so values interoperate freely with non-pydantic code. + + `create_default` keeps its output self-consistent: overriding `shape` without + a chunk grid derives one regular chunk covering the array (v3 + `chunk_shape == shape`; v2 `chunks == shape`) instead of silently keeping the + scalar default's 0-d grid. + + A v2 `.zarray` that omits `dimension_separator` is interpreted with the v2 + convention's default `"."` (the model previously normalized absence to `"/"`, + which would misaddress the chunks of real-world default-separator arrays). + The value is never null: absent, `"."`, or `"/"` are the only spellings. + + Optional document keys use `UNSET` — a PEP 661 sentinel + (`typing_extensions.Sentinel`), usable directly in type expressions — never + `None`: in a model, `None` always corresponds to a JSON `null` in the + document (a v2 `compressor`, an unnamed dimension inside `dimension_names`), + and `UNSET` always means the key is absent. Checker note: ty types the + sentinel exactly; pyright needs `<= 1.1.404` until microsoft/pyright#11115 + is fixed (this package's CI pins it); mypy users need a `cast` or + `type: ignore` at narrowing sites until python/mypy#21647 merges. This keeps semantically distinct spellings + distinct — an absent `dimension_names` ("there are no dimension names") and + an explicit `[null, null]` ("every dimension has a name, which is null") are + different documents and round-trip as such. The `consolidated_metadata: null` + written by a historical zarr-python bug is the one deliberate exception to + faithful round-tripping: those stores remain readable, but the bug spelling + is repaired to absence on read and never written back. + + The v2 models treat the `.zattrs` file's presence as part of the store: + `attributes` is `UNSET` when no `.zattrs` file exists (and `to_key_value` + emits none), while an explicit empty `.zattrs` is `{}` and round-trips as a + file. Previously `to_key_value` always emitted `.zattrs`, silently adding a + file to stores that never had one. + + The store-key `Literal` aliases (`ZarrV2ArrayMetadataStoreKey`, + `ZarrV2AttributesStoreKey`, ...) are exported from `zarr_metadata.model` + alongside their constants, and each `to_key_value` return type is keyed by + them, so the set of store keys a model can emit is visible in its signature. + `from_key_value` deliberately keeps `Mapping[str, bytes]` input: it accepts + any string-keyed store mapping and ignores unrelated keys. + + `to_json` returns a document that shares no mutable state with the model: + every value that can hold a mutable container (attributes, configurations, + extra fields, v2 codec configurations, fill values, consolidated entries) is + deep-copied on the way out, so editing a serialized document can never + silently mutate the frozen model that produced it. ([#4119](https://github.com/zarr-developers/zarr-python/issues/4119)) + +### Improved Documentation + +- `zarr-metadata` now has a standalone documentation site at + , with a comprehensive API reference + covering every public module, versioned by this package's release tags. The + package also gained a `justfile` collecting its development commands + (`test`, `lint`, `typecheck`, `docs-check`, `docs-serve`, `changelog-draft`), + which the package CI workflow now delegates to. ([#4208](https://github.com/zarr-developers/zarr-python/issues/4208)) + +### Deprecations and Removals + +- The document (TypedDict) types are renamed to put the format version at the + front of the name and to mark the JSON-document form with a `JSON` suffix, + so a format version can never be misread as a class revision and the bare + entity names are reserved for the `zarr_metadata.model` dataclasses: + + - `ArrayMetadataV2` → `ZarrV2ArrayMetadataJSON` (and `...Partial` accordingly) + - `ArrayMetadataV3` → `ZarrV3ArrayMetadataJSON` (and `...Partial` accordingly) + - `GroupMetadataV2` → `ZarrV2GroupMetadataJSON` (and `...Partial` accordingly) + - `GroupMetadataV3` → `ZarrV3GroupMetadataJSON` (and `...Partial` accordingly) + - `ConsolidatedMetadataV2` → `ZarrV2ConsolidatedMetadataJSON` + - `ConsolidatedMetadataV3` → `ZarrV3ConsolidatedMetadataJSON` + - `NamedConfigV3` → `ZarrV3NamedConfigJSON` + - `MetadataV3` → `ZarrV3MetadataFieldJSON` (the union of the bare-name and + named-configuration spellings of one metadata field) + - `ExtensionFieldV3` → `ZarrV3ExtensionField` + - `CodecMetadataV2` → `ZarrV2CodecMetadata` + - `DataTypeMetadataV2` → `ZarrV2DataTypeMetadata` + - `ArrayOrderV2` → `ZarrV2ArrayOrder` + - `ArrayDimensionSeparatorV2` → `ZarrV2ArrayDimensionSeparator` + - `ZArrayMetadata` → `ZarrV2ZArrayJSON` (the strict on-disk `.zarray` document) + - `ZGroupMetadata` → `ZarrV2ZGroupJSON` (the strict on-disk `.zgroup` document) + - `ZAttrsMetadata` → `ZarrV2ZAttrsJSON` (the `.zattrs` document) + + The old names are removed, not aliased. The `zarr_metadata.pydantic` field + types take the bare entity names (`ZarrV3ArrayMetadata`, ...), matching the + model classes they validate into. + + The conventions, stated once for future additions: CamelCase type names put + the format version first (`ZarrV2ArrayMetadataJSON`, + `ZarrV3ArrayMetadataStoreKey`), while SCREAMING_SNAKE constants and + snake_case functions put it last (`ARRAY_METADATA_STORE_KEY_V2`, + `validate_array_metadata_v3`). The `JSON` suffix marks a raw-document type + whose bare name is taken by (or reserved for) a `zarr_metadata.model` + dataclass; raw field-level types the models hold verbatim + (`ZarrV2CodecMetadata`, `ZarrV3ExtensionField`) keep their bare names. + Extension-entity types put the registered entity name first and end in + exactly one role suffix (`BloscCodecMetadata`, `Uint8DataTypeName`) — the + `V2` in `V2ChunkKeyEncodingMetadata` is that encoding's entity name, not a + format version, which is always spelled `ZarrV2`/`ZarrV3`. Every public + type name is checked against this grammar by + `tests/test_public_api.py::test_public_type_names_comply_with_naming_grammar`. + + ([#4119](https://github.com/zarr-developers/zarr-python/issues/4119)) + + +## 0.3.0 (2026-06-19) + +### Deprecations and Removals + +- Introduces a new `JSONValue` type that models python objects that serialize directly to JSON. This type is used to annotate the contents of `attributes` and `fill_value` fields, replacing the use of the overly wide `object` type. This is technically a breaking change. ([#4037](https://github.com/zarr-developers/zarr-python/pull/4037)) +- Promoted a curated "front door" of names to the top-level `zarr_metadata` + namespace, so consumers can write e.g. `from zarr_metadata import + ArrayMetadataV3, ShardingIndexLocation, BLOSC_CNAME` instead of importing from + deep submodule paths. The front door covers every metadata-document TypedDict, + each codec/chunk-grid/chunk-key-encoding canonical type, the full data-type + trio for every dtype, and every constant + `Literal` pair. Deep submodule paths + continue to work unchanged. + + Several promoted names were given clearer, less ambiguous spellings than their + deep-module names, since they now appear bare at the top level: + `Endian`/`ENDIAN` → `Endianness`/`ENDIANNESS`, + `IndexLocation`/`INDEX_LOCATION` → `ShardingIndexLocation`/`SHARDING_INDEX_LOCATION`, + `RoundingMode`/`ROUNDING_MODE` → `CastRoundingMode`/`CAST_ROUNDING_MODE`, + `OutOfRangeMode`/`OUT_OF_RANGE_MODE` → `CastOutOfRangeMode`/`CAST_OUT_OF_RANGE_MODE`, + `DateTimeUnit` → `NumpyTimeUnit`, + `NamedConfig` → `NamedConfigV3`, and + `MetadataFieldV3` → `MetadataV3` (matching the name `zarrs` uses for this + `name`-or-`{name, configuration}` shape). + + Also added the `NUMPY_TIME_UNIT` runtime constant (a `Final` tuple paired with + the `NumpyTimeUnit` Literal) in `zarr_metadata.v3.data_type.numpy_timedelta64`. ([#4083](https://github.com/zarr-developers/zarr-python/pull/4083)) + + +## 0.2.0 (2026-05-19) + +### Bugfixes + +- `GzipCodecConfiguration.level` is now required, and `GzipCodecMetadata` + no longer accepts the bare-string `"gzip"` form. The codec's compressed + output depends on `level`, so metadata that omits it cannot reproducibly + identify the chunk bytes produced by a writer. **Breaking** for consumers + that previously typed gzip codec metadata as the bare string or + constructed a `GzipCodecConfiguration` without `level`. + ([#3978](https://github.com/zarr-developers/zarr-python/pull/3978)) +- `BytesCodecObject.configuration` is now `NotRequired`. The configuration + has no required keys (`endian` is conditionally required at runtime + based on data type), so the object form may omit it entirely — matching + the bare-string short-hand. **Soft-breaking** for consumers that + previously relied on `configuration` always being present. + ([#3978](https://github.com/zarr-developers/zarr-python/pull/3978)) +- Better modelling of Zarr v2 stored metadata. Zarr v2 splits a node's + metadata across two JSON documents (`.zarray`/`.zgroup` and `.zattrs`), + but `GroupMetadataV2` had no `attributes` field while `ArrayMetadataV2` + did — an inconsistency. `GroupMetadataV2` now also has an optional + `attributes` field, and `ArrayMetadataV2.attributes` is now + `NotRequired` for symmetry. **Soft-breaking** for consumers that + relied on `ArrayMetadataV2.attributes` always being present. + ([#3962](https://github.com/zarr-developers/zarr-python/pull/3962)) + +### Features + +- Added `ArrayMetadataV3Partial`, `GroupMetadataV3Partial`, + `ArrayMetadataV2Partial`, and `GroupMetadataV2Partial` — sibling + TypedDicts to the existing full metadata types, declared with + `total=False` so every field is `NotRequired`. Use these when typing + dicts that intentionally hold a subset of a complete metadata document + (test fixtures, fragment templates, in-progress builders). An + equivalence test pins each `Partial` to the keys and value types of + its full sibling so the two cannot drift. + ([#3982](https://github.com/zarr-developers/zarr-python/pull/3982)) +- Added three new top-level types modelling the **strict on-disk** shape + of Zarr v2 metadata documents: `ZArrayMetadata` (the `.zarray` file), + `ZGroupMetadata` (the `.zgroup` file), and `ZAttrsMetadata` (the + `.zattrs` file). Use these when you want a type that faithfully matches + what's stored on disk; use the merged `ArrayMetadataV2`/`GroupMetadataV2` + when you want the in-memory representation a Python program typically + works with. + ([#3962](https://github.com/zarr-developers/zarr-python/pull/3962)) +- Added typed constants exposing the spec-permitted values of constrained + Literal fields, importable at the per-codec module level. For example, + `from zarr_metadata.v3.codec.bytes import ENDIAN` provides + `("little", "big")` as a tuple, enabling runtime iteration or validator + generation without re-stating the Literal values by hand. + ([#3978](https://github.com/zarr-developers/zarr-python/pull/3978)) + +## 0.1.1 (2026-05-06) + +### Misc + +- First usable release on PyPI. Version 0.1.0 was uploaded then deleted to + reserve the project name; this version is the first one PyPI will install. + No source changes from 0.1.0. + ([#3949](https://github.com/zarr-developers/zarr-python/pull/3949)) + +## 0.1.0 (2026-05-01) + +### Features + +- Initial release. Provides `TypedDict` definitions and `Literal` aliases + for the JSON shapes specified by Zarr v2 and v3 metadata, plus a subset + of `zarr-extensions` types and the un-specified-but-widely-used + consolidated metadata documents. Pair with a runtime validator like + `pydantic` to check JSON loaded from disk. + ([#3919](https://github.com/zarr-developers/zarr-python/pull/3919)) diff --git a/packages/zarr-metadata/LICENSE.txt b/packages/zarr-metadata/LICENSE.txt new file mode 100644 index 0000000000..1e8da4d242 --- /dev/null +++ b/packages/zarr-metadata/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-metadata/README.md b/packages/zarr-metadata/README.md new file mode 100644 index 0000000000..6b6b172aec --- /dev/null +++ b/packages/zarr-metadata/README.md @@ -0,0 +1,134 @@ +# zarr-metadata + +Python types, models, and validators for Zarr v2 and v3 metadata. + +Documentation: + +## What this is + +Two layers and an optional integration: + +- **Typed JSON shapes**: `TypedDict` definitions and `Literal` aliases for the + JSON documents specified by the [Zarr v2](https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html) + and [Zarr v3](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html) + specifications, plus types for [`zarr-extensions`](https://github.com/zarr-developers/zarr-extensions/) + and a few widely-used-but-unspecified entities (e.g. consolidated metadata). +- **Document models** (`zarr_metadata.model`): canonical frozen-dataclass + models of whole metadata documents, with structural validators, loc-aware + parsers, and store-key (de)serialization. A document produced by `to_json` + shares no mutable state with the model that produced it. +- **Optional Pydantic integration** (`zarr_metadata.pydantic`, requires + Pydantic 2.13 or newer): each model as a Pydantic field type that validates + raw documents through the same strict parser. + +## What this is for + +The public `TypedDict` definitions describe the static JSON shape of Zarr +metadata. For strict, loc-aware validation of JSON loaded from disk, use the +model parser: + +```python +import json +from zarr_metadata.model import ZarrV3ArrayMetadata + +with open("zarr.json", "rb") as f: + raw = json.load(f) + +metadata = ZarrV3ArrayMetadata.from_json(raw) +``` + +The optional Pydantic integration delegates raw input to the same strict +parser and returns the same normalized model class: + +```python +from pydantic import TypeAdapter +import zarr_metadata.pydantic as zmp + +metadata = TypeAdapter(zmp.ZarrV3ArrayMetadata).validate_python(raw) +encoded = metadata.to_key_value()["zarr.json"] +``` + +A bare `TypeAdapter` over a public document `TypedDict` is a coercive shape +adapter, not a Zarr conformance validator; it may coerce values or discard +members that the strict model parser rejects. + +## Validation boundary + +The model validators enforce the declared document structure and a small set +of context-free consistency rules, including fixed format literals, finite +JSON numbers, non-negative dimensions, non-empty v3 codec pipelines, and one +`dimension_names` entry per array dimension. They do not interpret extension +names or configurations, resolve codec pipelines, or decide whether a data +type, chunk grid, codec, or storage transformer is supported. Those decisions +belong to consumer implementations. + +The Pydantic integration's generated JSON Schemas express independently +checkable document structure and field constraints, but they are not a +replacement for runtime model validation. Standard JSON Schema treats a +mathematically integral number such as `1.0` as an integer, while the runtime +boundary requires Python `int` values, and it cannot express arbitrary +same-length relations such as `dimension_names` versus `shape` or v2 `chunks` +versus `shape`. Consumers should run the model parser after schema validation. + +## Scope + +At minimum, this library supports what Zarr-Python needs: the complete +Zarr v2 and v3 specs, consolidated metadata, and a subset of the metadata +defined in `zarr-extensions`. We are generally open to contributions that +add types, models, or structural validation for Zarr metadata with a +published spec. + +Runtime array behavior is out of scope: nothing here encodes or decodes +chunks, resolves codec or data type names to implementations, or performs +store I/O. The models begin and end at the metadata documents themselves — +`from_key_value` / `to_key_value` map documents to store keys and bytes, +and everything past that belongs to consumer libraries. + +## Developing + +Package-scoped development commands live in the [`justfile`](./justfile) +(requires [just](https://github.com/casey/just)): + +``` +just test # run the test suite (extra args go to pytest) +just lint # ruff, same invocation as CI +just typecheck # pyright, pinned to the version CI uses +just docs-check # strict build of the docs site +just check # all of the above +just docs-serve # serve the docs site locally +``` + +Run them from this directory, or from anywhere in the repository as +`just packages/zarr-metadata/`. + +## Releasing + +The package version is derived from git tags by `hatch-vcs`. Tags must +match the pattern `zarr_metadata-v` (e.g. `zarr_metadata-v0.2.0`) +so they do not collide with the main `zarr-python` release tags. + +To cut a release: + +1. Create and push a tag of the form `zarr_metadata-v` on the + commit you want to publish, e.g.: + ``` + git tag zarr_metadata-v0.2.0 + git push origin zarr_metadata-v0.2.0 + ``` +2. Pushing the tag fires the `zarr-metadata release` workflow, which + builds the wheel/sdist (version resolved from the tag), runs an + install smoke test, and publishes to PyPI via OIDC trusted publishing. + +We intentionally do *not* create a GitHub Release for `zarr-metadata` +versions — GitHub Releases live at the repo level, and a zarr-metadata +release would surface in the zarr-python repo's Releases UI as if it +were a zarr-python release. + +To dry-run a build against TestPyPI, dispatch the workflow manually +(`Actions` → `zarr-metadata release` → `Run workflow`). Manual dispatches +build from the current commit; with no recent tag the version will look +like `0.1.devN`, which is fine for TestPyPI. + +## License + +[MIT](./LICENSE.txt) diff --git a/packages/zarr-metadata/changes/README.md b/packages/zarr-metadata/changes/README.md new file mode 100644 index 0000000000..bf0fc85425 --- /dev/null +++ b/packages/zarr-metadata/changes/README.md @@ -0,0 +1,25 @@ +Writing a changelog entry for `zarr-metadata` +--------------------------------------------- + +Fragments in **this** directory are released notes for the `zarr-metadata` +package only — kept separate from the parent zarr-python `changes/` +directory so a PR touching only `packages/zarr-metadata/` 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-metadata`. + +A `zarr-metadata` release runs `towncrier build` in `packages/zarr-metadata/`, +which consumes the fragments here and updates `CHANGELOG.md`. Fragments +that describe parent zarr-python changes (not the metadata package) +belong in the top-level `changes/` directory, not here. diff --git a/packages/zarr-metadata/docs/_static/favicon-96x96.png b/packages/zarr-metadata/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000..e77977ccf4 Binary files /dev/null and b/packages/zarr-metadata/docs/_static/favicon-96x96.png differ diff --git a/packages/zarr-metadata/docs/_static/logo_bw.png b/packages/zarr-metadata/docs/_static/logo_bw.png new file mode 100644 index 0000000000..df1979d3cc Binary files /dev/null and b/packages/zarr-metadata/docs/_static/logo_bw.png differ diff --git a/packages/zarr-metadata/docs/api/index.md b/packages/zarr-metadata/docs/api/index.md new file mode 100644 index 0000000000..5e230c7aa2 --- /dev/null +++ b/packages/zarr-metadata/docs/api/index.md @@ -0,0 +1,34 @@ +--- +title: API reference +--- + +# API reference + +The package is organized to mirror the structure of the Zarr specifications: + +- [`zarr_metadata.model`](model.md) — frozen-dataclass document models, + structural validators, loc-aware parsers, and the `UNSET` sentinel +- [`zarr_metadata.pydantic`](pydantic.md) — optional Pydantic field types + over the models +- [`zarr_metadata.v2`](v2.md) — `TypedDict` shapes for Zarr v2 documents + (`.zarray`, `.zgroup`, `.zattrs`, `.zmetadata`) +- [`zarr_metadata.v3`](v3/index.md) — `TypedDict` shapes for Zarr v3 + documents, with subpackages for [chunk grids](v3/chunk_grid.md), + [chunk key encodings](v3/chunk_key_encoding.md), [codecs](v3/codec.md), + and [data types](v3/data_type.md) + +The document types, models, and spec vocabulary — including the store keys — +are re-exported at the top level, so +`from zarr_metadata import ZarrV3ArrayMetadataJSON` and +`from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON` are equivalent. +The model layer's validators, parsers, type guards, and metadata key sets are +imported from [`zarr_metadata.model`](model.md) directly. + +## Common types + +A few cross-cutting aliases are exported only from the top-level +`zarr_metadata` namespace: + +::: zarr_metadata.JSONValue + +::: zarr_metadata.ZarrV3NamedConfigJSON diff --git a/packages/zarr-metadata/docs/api/model.md b/packages/zarr-metadata/docs/api/model.md new file mode 100644 index 0000000000..c82ba98f2d --- /dev/null +++ b/packages/zarr-metadata/docs/api/model.md @@ -0,0 +1,5 @@ +--- +title: model +--- + +::: zarr_metadata.model diff --git a/packages/zarr-metadata/docs/api/pydantic.md b/packages/zarr-metadata/docs/api/pydantic.md new file mode 100644 index 0000000000..edecb416a7 --- /dev/null +++ b/packages/zarr-metadata/docs/api/pydantic.md @@ -0,0 +1,5 @@ +--- +title: pydantic +--- + +::: zarr_metadata.pydantic diff --git a/packages/zarr-metadata/docs/api/v2.md b/packages/zarr-metadata/docs/api/v2.md new file mode 100644 index 0000000000..2fe5b6ec56 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v2.md @@ -0,0 +1,17 @@ +--- +title: v2 +--- + +::: zarr_metadata.v2 + options: + members: false + +::: zarr_metadata.v2.array + +::: zarr_metadata.v2.group + +::: zarr_metadata.v2.attributes + +::: zarr_metadata.v2.codec + +::: zarr_metadata.v2.consolidated diff --git a/packages/zarr-metadata/docs/api/v3/chunk_grid.md b/packages/zarr-metadata/docs/api/v3/chunk_grid.md new file mode 100644 index 0000000000..724b1c9d8d --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/chunk_grid.md @@ -0,0 +1,11 @@ +--- +title: chunk_grid +--- + +::: zarr_metadata.v3.chunk_grid + options: + members: false + +::: zarr_metadata.v3.chunk_grid.regular + +::: zarr_metadata.v3.chunk_grid.rectilinear diff --git a/packages/zarr-metadata/docs/api/v3/chunk_key_encoding.md b/packages/zarr-metadata/docs/api/v3/chunk_key_encoding.md new file mode 100644 index 0000000000..bb063deb25 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/chunk_key_encoding.md @@ -0,0 +1,11 @@ +--- +title: chunk_key_encoding +--- + +::: zarr_metadata.v3.chunk_key_encoding + options: + members: false + +::: zarr_metadata.v3.chunk_key_encoding.default + +::: zarr_metadata.v3.chunk_key_encoding.v2 diff --git a/packages/zarr-metadata/docs/api/v3/codec.md b/packages/zarr-metadata/docs/api/v3/codec.md new file mode 100644 index 0000000000..cb96d2c7d5 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/codec.md @@ -0,0 +1,25 @@ +--- +title: codec +--- + +::: zarr_metadata.v3.codec + options: + members: false + +::: zarr_metadata.v3.codec.blosc + +::: zarr_metadata.v3.codec.bytes + +::: zarr_metadata.v3.codec.cast_value + +::: zarr_metadata.v3.codec.crc32c + +::: zarr_metadata.v3.codec.gzip + +::: zarr_metadata.v3.codec.scale_offset + +::: zarr_metadata.v3.codec.sharding_indexed + +::: zarr_metadata.v3.codec.transpose + +::: zarr_metadata.v3.codec.zstd diff --git a/packages/zarr-metadata/docs/api/v3/data_type.md b/packages/zarr-metadata/docs/api/v3/data_type.md new file mode 100644 index 0000000000..f482c33201 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/data_type.md @@ -0,0 +1,45 @@ +--- +title: data_type +--- + +::: zarr_metadata.v3.data_type + options: + members: false + +::: zarr_metadata.v3.data_type.bool + +::: zarr_metadata.v3.data_type.int8 + +::: zarr_metadata.v3.data_type.int16 + +::: zarr_metadata.v3.data_type.int32 + +::: zarr_metadata.v3.data_type.int64 + +::: zarr_metadata.v3.data_type.uint8 + +::: zarr_metadata.v3.data_type.uint16 + +::: zarr_metadata.v3.data_type.uint32 + +::: zarr_metadata.v3.data_type.uint64 + +::: zarr_metadata.v3.data_type.float16 + +::: zarr_metadata.v3.data_type.float32 + +::: zarr_metadata.v3.data_type.float64 + +::: zarr_metadata.v3.data_type.complex64 + +::: zarr_metadata.v3.data_type.complex128 + +::: zarr_metadata.v3.data_type.raw + +::: zarr_metadata.v3.data_type.bytes + +::: zarr_metadata.v3.data_type.string + +::: zarr_metadata.v3.data_type.numpy_datetime64 + +::: zarr_metadata.v3.data_type.numpy_timedelta64 diff --git a/packages/zarr-metadata/docs/api/v3/index.md b/packages/zarr-metadata/docs/api/v3/index.md new file mode 100644 index 0000000000..f20267d372 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/index.md @@ -0,0 +1,15 @@ +--- +title: v3 +--- + +::: zarr_metadata.v3 + options: + members: false + +::: zarr_metadata.v3.ZarrV3MetadataFieldJSON + +::: zarr_metadata.v3.array + +::: zarr_metadata.v3.group + +::: zarr_metadata.v3.consolidated diff --git a/packages/zarr-metadata/docs/index.md b/packages/zarr-metadata/docs/index.md new file mode 100644 index 0000000000..58e4f290c6 --- /dev/null +++ b/packages/zarr-metadata/docs/index.md @@ -0,0 +1,98 @@ +# zarr-metadata + +Basic tools for modelling Zarr metadata, with minimal dependencies. + +`zarr-metadata` is developed in the +[zarr-python repository](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata) +and released independently of `zarr` itself. Install it with: + +``` +pip install zarr-metadata +``` + +## Who needs this + +This library might be useful to you if your software interacts with Zarr metadata documents. + +## What this is + +This library is *not* a full Zarr implementation. Instead, it's a collection of data structures and routines that +closely model the content of the Zarr specifications, such as: + +- **Typed JSON shapes** ([`zarr_metadata.v2`](api/v2.md) and + [`zarr_metadata.v3`](api/v3/index.md)): `TypedDict` definitions and + `Literal` aliases for the JSON documents specified by the + [Zarr v2](https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html) and + [Zarr v3](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html) + specifications, plus types for + [zarr-extensions](https://github.com/zarr-developers/zarr-extensions/) and a + few widely-used-but-unspecified entities (e.g. consolidated metadata). +- **Document models** ([`zarr_metadata.model`](api/model.md)): canonical + frozen-dataclass models of whole metadata documents, with structural + validators, loc-aware parsers, and store-key (de)serialization. A document + produced by `to_json` shares no mutable state with the model that produced + it. +- **Optional Pydantic integration** ([`zarr_metadata.pydantic`](api/pydantic.md), + requires Pydantic 2.13 or newer): each model as a Pydantic field type that + validates raw documents through the same strict parser. + +## What this is for + +The public `TypedDict` definitions describe the static JSON shape of Zarr +metadata. For strict, loc-aware validation of JSON loaded from disk, use the +model parser: + +```python +import json +from zarr_metadata.model import ZarrV3ArrayMetadata + +with open("zarr.json", "rb") as f: + raw = json.load(f) + +metadata = ZarrV3ArrayMetadata.from_json(raw) +``` + +The optional Pydantic integration delegates raw input to the same strict +parser and returns the same normalized model class: + +```python +from pydantic import TypeAdapter +import zarr_metadata.pydantic as zmp + +metadata = TypeAdapter(zmp.ZarrV3ArrayMetadata).validate_python(raw) +encoded = metadata.to_key_value()["zarr.json"] +``` + +A bare `TypeAdapter` over a public document `TypedDict` is a coercive shape +adapter, not a Zarr conformance validator; it may coerce values or discard +members that the strict model parser rejects. + +## Validation boundary + +The model validators enforce the declared document structure and a small set +of context-free consistency rules, including fixed format literals, finite +JSON numbers, non-negative dimensions, non-empty v3 codec pipelines, and one +`dimension_names` entry per array dimension. They do not interpret extension +names or configurations, resolve codec pipelines, or decide whether a data +type, chunk grid, codec, or storage transformer is supported. Those decisions +belong to consumer implementations. + +## Scope + +At minimum, this library supports what Zarr-Python needs: the complete +Zarr v2 and v3 specs, consolidated metadata, and a subset of the metadata +defined in `zarr-extensions`. We are generally open to contributions that +add types, models, or structural validation for Zarr metadata with a +published spec. + +Runtime array behavior is out of scope: nothing here encodes or decodes +chunks, resolves codec or data type names to implementations, or performs +store I/O. The models begin and end at the metadata documents themselves — +`from_key_value` / `to_key_value` map documents to store keys and bytes, +and everything past that belongs to consumer libraries. + +## Reference + +- [API reference](api/index.md) +- [Changelog](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/CHANGELOG.md) +- [License (MIT)](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/LICENSE.txt) diff --git a/packages/zarr-metadata/justfile b/packages/zarr-metadata/justfile new file mode 100644 index 0000000000..0f1861ed7d --- /dev/null +++ b/packages/zarr-metadata/justfile @@ -0,0 +1,58 @@ +# Development verbs for the zarr-metadata package. Recipes run with this +# directory as the working directory regardless of where `just` is invoked. + +# List available recipes +default: + @just --list + +# Run the test suite; extra args are passed to pytest +test *args: + uv run --group test pytest tests {{ args }} + +# Lint with the same invocation CI uses +lint: + uvx ruff check . + +# Pinned to the last pyright that types PEP 661 sentinels in class attributes +# correctly; 1.1.405+ regressed (microsoft/pyright#11115). Unpin when fixed. +pyright_version := "1.1.404" + +# CI runs pyright on python 3.11; the pinned pyright predates 3.14, whose +# stdlib it cannot parse, so pin the interpreter to match CI. +# Type-check the package sources +typecheck: + uv run --python 3.11 --group test --with 'pyright=={{ pyright_version }}' pyright src + +# Run everything CI runs for this package +check: lint typecheck test 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-metadata/mkdocs.yml b/packages/zarr-metadata/mkdocs.yml new file mode 100644 index 0000000000..18e1fc8c35 --- /dev/null +++ b/packages/zarr-metadata/mkdocs.yml @@ -0,0 +1,111 @@ +site_name: zarr-metadata +# 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-metadata +repo_url: https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata +# 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-metadata/docs/ +site_description: Spec-defined metadata types, models, and validators for Zarr v2 and v3. +site_author: Davis Bennett +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr-metadata.readthedocs.io/'] +docs_dir: docs +use_directory_urls: true + +nav: + - index.md + - API Reference: + - api/index.md + - ' zarr_metadata.model': api/model.md + - ' zarr_metadata.pydantic': api/pydantic.md + - ' zarr_metadata.v2': api/v2.md + - ' zarr_metadata.v3': + - api/v3/index.md + - ' zarr_metadata.v3.chunk_grid': api/v3/chunk_grid.md + - ' zarr_metadata.v3.chunk_key_encoding': api/v3/chunk_key_encoding.md + - ' zarr_metadata.v3.codec': api/v3/codec.md + - ' zarr_metadata.v3.data_type': api/v3/data_type.md + - Changelog: https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/CHANGELOG.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/ + +watch: + - src + +theme: + language: en + name: material + logo: _static/logo_bw.png + favicon: _static/favicon-96x96.png + + palette: + # Light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + font: + text: Roboto + code: Roboto Mono + + features: + - content.code.annotate + - content.code.copy + - navigation.indexes + - navigation.instant + - navigation.tracking + - search.suggest + - search.share + +plugins: + - autorefs + - search + - mkdocstrings: + enable_inventory: true + handlers: + python: + paths: [src] + options: + allow_inspection: true + docstring_section_style: list + docstring_style: numpy + inherited_members: true + line_length: 60 + separate_signature: true + show_root_heading: true + show_signature_annotations: true + show_source: true + show_symbol_type_toc: true + signature_crossrefs: true + show_if_no_docstring: true + extensions: + - griffe_inherited_docstrings + + inventories: + - https://docs.python.org/3/objects.inv + - https://zarr.readthedocs.io/en/stable/objects.inv + +markdown_extensions: + - admonition + - attr_list + - def_list + - footnotes + - md_in_html + - pymdownx.details + - pymdownx.superfences + - toc: + permalink: true + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite diff --git a/packages/zarr-metadata/pyproject.toml b/packages/zarr-metadata/pyproject.toml new file mode 100644 index 0000000000..a58d3579a1 --- /dev/null +++ b/packages/zarr-metadata/pyproject.toml @@ -0,0 +1,169 @@ +[build-system] +requires = ["hatchling>=1.29.0", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "zarr-metadata" +dynamic = ["version"] +description = "Spec-defined metadata types, models, and validators for Zarr v2 and v3." +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 :: 4 - Beta", + "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"] +dependencies = [ + # >=4.16: first release where `Sentinel` pickles by reference + # (`__reduce__` returns the sentinel's name), so `UNSET` — and any model + # holding it — can cross process boundaries and be deep-copied with its + # singleton identity intact. 4.15 and earlier refuse to pickle sentinels. + "typing_extensions>=4.16", +] + +[project.urls] +Homepage = "https://github.com/zarr-developers/zarr-python" +Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata" +Issues = "https://github.com/zarr-developers/zarr-python/issues" +Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/CHANGELOG.md" +Documentation = "https://zarr-metadata.readthedocs.io/" + +[dependency-groups] +test = ["pytest", "pydantic>=2.13", "jsonschema"] +docs = [ + # Pins match the zarr-python docs environment in the repo-root + # pyproject.toml so the two sites render with the same toolchain. + "mkdocs-material==9.7.6", + "mkdocs==1.6.1", + "mkdocstrings==1.0.4", + "mkdocstrings-python==2.0.5", + "griffe-inherited-docstrings==1.1.3", + # mkdocstrings uses ruff to format rendered signatures + "ruff==0.15.20", +] + +[tool.hatch.version] +source = "vcs" +tag-pattern = '^zarr_metadata-v(?P.+)$' +# `git_describe_command` ensures we get the zarr_metadata tags instead of latest. +# `local_scheme` strips the git commit info so the appending info is just a counter from latest tag. +# test-pypi doesn't accept git commit info in tags, and the count should be enough to distinguish unique runs. +raw-options = { root = "../..", git_describe_command = "git describe --dirty --tags --long --match zarr_metadata-v*", local_scheme = "no-local-version" } + +[tool.hatch.build.targets.wheel] +packages = ["src/zarr_metadata"] + +# An allowlist, so nothing that merely happens to sit in the package directory +# — a scratch script, a stray notebook — can ride along in a release. The list +# keeps an sdist self-testing and self-documenting: every fixture this suite +# reads is a JSON file sitting next to the test module that loads it, so +# `/tests` is the whole test dependency, and `/docs` plus `/mkdocs.yml` are a +# self-contained site (mkdocstrings reads `src`, nothing reaches outside the +# package) so `just docs-check` runs from an unpacked sdist too. `changes/` +# and `.readthedocs.yaml` are deliberately absent: towncrier fragments are +# repo bookkeeping, and the RTD config addresses paths from the repo root. +# `pyproject.toml`, `README.md` and `LICENSE.txt` are added by hatchling itself. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/docs", + "/mkdocs.yml", + "/justfile", + "/CHANGELOG.md", +] + +[tool.ruff] +extend = "../../pyproject.toml" +target-version = "py311" + +[tool.pytest.ini_options] +minversion = "7" +testpaths = ["tests"] +xfail_strict = true +addopts = ["-ra", "--strict-config", "--strict-markers"] +filterwarnings = [ + "error", + # Pydantic validates these public immutable-shape TypedDicts correctly but + # cannot enforce the type checker's ReadOnly mutation restriction. + "ignore:Items? .* using the `ReadOnly` qualifier.*:UserWarning:pydantic._internal._generate_schema", +] + +[tool.numpydoc_validation] +checks = [ + "GL10", + "SS04", + "PR02", + "PR03", + "PR05", + "PR06", +] + +# CI pins pyright==1.1.404: later versions regress PEP 661 sentinel typing in +# class attributes (microsoft/pyright#11115), which zarr_metadata.model._sentinel +# relies on. Use the same pin locally; unpin when the fix lands. +[tool.pyright] +include = ["src"] +enableExperimentalFeatures = true +typeCheckingMode = "strict" +pythonVersion = "3.11" + +[tool.towncrier] +# Fragments for this package live alongside the package source, separate +# from the parent zarr-python `changes/` directory, so a PR touching only +# `packages/zarr-metadata/` produces a release note for this package only. +directory = "changes" +filename = "CHANGELOG.md" +package = "zarr_metadata" +underlines = ["", "", ""] +title_format = "## {version} ({project_date})" +issue_format = "[#{issue}](https://github.com/zarr-developers/zarr-python/pull/{issue})" +start_string = "\n" + +# Declaring any type replaces towncrier's built-in set, so all five the +# `changes/README.md` menu offers are restated here. They are the defaults +# verbatim except for `misc`, whose `showcontent` towncrier defaults to false: +# a `misc` entry would render as a bare PR link, which tells a reader nothing. +# A change worth a release note is worth a sentence, whatever its category. +[[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-metadata/src/zarr_metadata/__init__.py b/packages/zarr-metadata/src/zarr_metadata/__init__.py new file mode 100644 index 0000000000..1a6b39f04d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/__init__.py @@ -0,0 +1,402 @@ +from importlib.metadata import version + +from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON +from zarr_metadata.model import ( + UNSET, + ZARR_V2_ARRAY_METADATA_STORE_KEY, + ZARR_V2_ATTRIBUTES_STORE_KEY, + ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY, + ZARR_V2_GROUP_METADATA_STORE_KEY, + ZARR_V3_ARRAY_METADATA_STORE_KEY, + ZARR_V3_CONSOLIDATED_METADATA_KEY, + ZARR_V3_GROUP_METADATA_STORE_KEY, + MetadataValidationError, + ProblemKind, + ValidationProblem, + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadataPartial, + ZarrV2ArrayMetadataStoreKey, + ZarrV2AttributesStoreKey, + ZarrV2ConsolidatedMetadata, + ZarrV2ConsolidatedMetadataStoreKey, + ZarrV2GroupMetadata, + ZarrV2GroupMetadataPartial, + ZarrV2GroupMetadataStoreKey, + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadataPartial, + ZarrV3ArrayMetadataStoreKey, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3GroupMetadataPartial, + ZarrV3GroupMetadataStoreKey, + ZarrV3MetadataField, + ZarrV3NamedConfig, +) +from zarr_metadata.v2.array import ( + ZARR_V2_ARRAY_DIMENSION_SEPARATOR, + ZARR_V2_ARRAY_ORDER, + ZarrV2ArrayDimensionSeparator, + ZarrV2ArrayMetadataJSON, + ZarrV2ArrayMetadataJSONPartial, + ZarrV2ArrayOrder, + ZarrV2DataTypeMetadata, + ZarrV2ZArrayJSON, +) +from zarr_metadata.v2.attributes import ZarrV2ZAttrsJSON +from zarr_metadata.v2.codec import ZarrV2CodecMetadata +from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataJSON +from zarr_metadata.v2.group import ( + ZarrV2GroupMetadataJSON, + ZarrV2GroupMetadataJSONPartial, + ZarrV2ZGroupJSON, +) +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ( + ZarrV3ArrayMetadataJSON, + ZarrV3ArrayMetadataJSONPartial, + ZarrV3ExtensionField, +) +from zarr_metadata.v3.chunk_grid.rectilinear import ( + RECTILINEAR_CHUNK_GRID_NAME, + RectilinearChunkGridMetadata, + RectilinearChunkGridName, +) +from zarr_metadata.v3.chunk_grid.regular import ( + REGULAR_CHUNK_GRID_NAME, + RegularChunkGridMetadata, + RegularChunkGridName, +) +from zarr_metadata.v3.chunk_key_encoding.default import ( + DEFAULT_CHUNK_KEY_ENCODING_NAME, + DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR, + DefaultChunkKeyEncodingMetadata, + DefaultChunkKeyEncodingName, + DefaultChunkKeyEncodingSeparator, +) +from zarr_metadata.v3.chunk_key_encoding.v2 import ( + V2_CHUNK_KEY_ENCODING_NAME, + V2_CHUNK_KEY_ENCODING_SEPARATOR, + V2ChunkKeyEncodingMetadata, + V2ChunkKeyEncodingName, + V2ChunkKeyEncodingSeparator, +) +from zarr_metadata.v3.codec.blosc import ( + BLOSC_CNAME, + BLOSC_CODEC_NAME, + BLOSC_SHUFFLE, + BloscCName, + BloscCodecMetadata, + BloscCodecName, + BloscShuffle, +) +from zarr_metadata.v3.codec.bytes import ( + BYTES_CODEC_NAME, + ENDIANNESS, + BytesCodecMetadata, + BytesCodecName, + Endianness, +) +from zarr_metadata.v3.codec.cast_value import ( + CAST_OUT_OF_RANGE_MODE, + CAST_ROUNDING_MODE, + CAST_VALUE_CODEC_NAME, + CastOutOfRangeMode, + CastRoundingMode, + CastValueCodecMetadata, + CastValueCodecName, +) +from zarr_metadata.v3.codec.crc32c import CRC32C_CODEC_NAME, Crc32cCodecMetadata, Crc32cCodecName +from zarr_metadata.v3.codec.gzip import GZIP_CODEC_NAME, GzipCodecMetadata, GzipCodecName +from zarr_metadata.v3.codec.scale_offset import ( + SCALE_OFFSET_CODEC_NAME, + ScaleOffsetCodecMetadata, + ScaleOffsetCodecName, +) +from zarr_metadata.v3.codec.sharding_indexed import ( + SHARDING_INDEX_LOCATION, + SHARDING_INDEXED_CODEC_NAME, + ShardingIndexedCodecMetadata, + ShardingIndexedCodecName, + ShardingIndexLocation, +) +from zarr_metadata.v3.codec.transpose import ( + TRANSPOSE_CODEC_NAME, + TransposeCodecMetadata, + TransposeCodecName, +) +from zarr_metadata.v3.codec.zstd import ZSTD_CODEC_NAME, ZstdCodecMetadata, ZstdCodecName +from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON +from zarr_metadata.v3.data_type.bool import ( + BOOL_DATA_TYPE_NAME, + BoolDataTypeName, + BoolFillValue, +) +from zarr_metadata.v3.data_type.bytes import ( + BYTES_DATA_TYPE_NAME, + BytesDataTypeName, + BytesFillValue, +) +from zarr_metadata.v3.data_type.complex64 import ( + COMPLEX64_DATA_TYPE_NAME, + Complex64DataTypeName, + Complex64FillValue, +) +from zarr_metadata.v3.data_type.complex128 import ( + COMPLEX128_DATA_TYPE_NAME, + Complex128DataTypeName, + Complex128FillValue, +) +from zarr_metadata.v3.data_type.float16 import ( + FLOAT16_DATA_TYPE_NAME, + Float16DataTypeName, + Float16FillValue, +) +from zarr_metadata.v3.data_type.float32 import ( + FLOAT32_DATA_TYPE_NAME, + Float32DataTypeName, + Float32FillValue, +) +from zarr_metadata.v3.data_type.float64 import ( + FLOAT64_DATA_TYPE_NAME, + Float64DataTypeName, + Float64FillValue, +) +from zarr_metadata.v3.data_type.int8 import ( + INT8_DATA_TYPE_NAME, + Int8DataTypeName, + Int8FillValue, +) +from zarr_metadata.v3.data_type.int16 import ( + INT16_DATA_TYPE_NAME, + Int16DataTypeName, + Int16FillValue, +) +from zarr_metadata.v3.data_type.int32 import ( + INT32_DATA_TYPE_NAME, + Int32DataTypeName, + Int32FillValue, +) +from zarr_metadata.v3.data_type.int64 import ( + INT64_DATA_TYPE_NAME, + Int64DataTypeName, + Int64FillValue, +) +from zarr_metadata.v3.data_type.numpy_datetime64 import ( + NUMPY_DATETIME64_DATA_TYPE_NAME, + NumpyDatetime64DataTypeName, + NumpyDatetime64FillValue, +) +from zarr_metadata.v3.data_type.numpy_timedelta64 import ( + NUMPY_TIME_UNIT, + NUMPY_TIMEDELTA64_DATA_TYPE_NAME, + NumpyTimedelta64DataTypeName, + NumpyTimedelta64FillValue, + NumpyTimeUnit, +) +from zarr_metadata.v3.data_type.raw import RawBytesDataTypeName, RawBytesFillValue +from zarr_metadata.v3.data_type.string import ( + STRING_DATA_TYPE_NAME, + StringDataTypeName, + StringFillValue, +) +from zarr_metadata.v3.data_type.struct import ( + STRUCT_DATA_TYPE_NAME, + StructDataTypeName, + StructFillValue, +) +from zarr_metadata.v3.data_type.uint8 import ( + UINT8_DATA_TYPE_NAME, + Uint8DataTypeName, + Uint8FillValue, +) +from zarr_metadata.v3.data_type.uint16 import ( + UINT16_DATA_TYPE_NAME, + Uint16DataTypeName, + Uint16FillValue, +) +from zarr_metadata.v3.data_type.uint32 import ( + UINT32_DATA_TYPE_NAME, + Uint32DataTypeName, + Uint32FillValue, +) +from zarr_metadata.v3.data_type.uint64 import ( + UINT64_DATA_TYPE_NAME, + Uint64DataTypeName, + Uint64FillValue, +) +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataJSONPartial + +__version__ = version("zarr-metadata") + + +__all__ = [ + "BLOSC_CNAME", + "BLOSC_CODEC_NAME", + "BLOSC_SHUFFLE", + "BOOL_DATA_TYPE_NAME", + "BYTES_CODEC_NAME", + "BYTES_DATA_TYPE_NAME", + "CAST_OUT_OF_RANGE_MODE", + "CAST_ROUNDING_MODE", + "CAST_VALUE_CODEC_NAME", + "COMPLEX64_DATA_TYPE_NAME", + "COMPLEX128_DATA_TYPE_NAME", + "CRC32C_CODEC_NAME", + "DEFAULT_CHUNK_KEY_ENCODING_NAME", + "DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR", + "ENDIANNESS", + "FLOAT16_DATA_TYPE_NAME", + "FLOAT32_DATA_TYPE_NAME", + "FLOAT64_DATA_TYPE_NAME", + "GZIP_CODEC_NAME", + "INT8_DATA_TYPE_NAME", + "INT16_DATA_TYPE_NAME", + "INT32_DATA_TYPE_NAME", + "INT64_DATA_TYPE_NAME", + "NUMPY_DATETIME64_DATA_TYPE_NAME", + "NUMPY_TIMEDELTA64_DATA_TYPE_NAME", + "NUMPY_TIME_UNIT", + "RECTILINEAR_CHUNK_GRID_NAME", + "REGULAR_CHUNK_GRID_NAME", + "SCALE_OFFSET_CODEC_NAME", + "SHARDING_INDEXED_CODEC_NAME", + "SHARDING_INDEX_LOCATION", + "STRING_DATA_TYPE_NAME", + "STRUCT_DATA_TYPE_NAME", + "TRANSPOSE_CODEC_NAME", + "UINT8_DATA_TYPE_NAME", + "UINT16_DATA_TYPE_NAME", + "UINT32_DATA_TYPE_NAME", + "UINT64_DATA_TYPE_NAME", + "UNSET", + "V2_CHUNK_KEY_ENCODING_NAME", + "V2_CHUNK_KEY_ENCODING_SEPARATOR", + "ZARR_V2_ARRAY_DIMENSION_SEPARATOR", + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZARR_V2_ARRAY_ORDER", + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "ZSTD_CODEC_NAME", + "BloscCName", + "BloscCodecMetadata", + "BloscCodecName", + "BloscShuffle", + "BoolDataTypeName", + "BoolFillValue", + "BytesCodecMetadata", + "BytesCodecName", + "BytesDataTypeName", + "BytesFillValue", + "CastOutOfRangeMode", + "CastRoundingMode", + "CastValueCodecMetadata", + "CastValueCodecName", + "Complex64DataTypeName", + "Complex64FillValue", + "Complex128DataTypeName", + "Complex128FillValue", + "Crc32cCodecMetadata", + "Crc32cCodecName", + "DefaultChunkKeyEncodingMetadata", + "DefaultChunkKeyEncodingName", + "DefaultChunkKeyEncodingSeparator", + "Endianness", + "Float16DataTypeName", + "Float16FillValue", + "Float32DataTypeName", + "Float32FillValue", + "Float64DataTypeName", + "Float64FillValue", + "GzipCodecMetadata", + "GzipCodecName", + "Int8DataTypeName", + "Int8FillValue", + "Int16DataTypeName", + "Int16FillValue", + "Int32DataTypeName", + "Int32FillValue", + "Int64DataTypeName", + "Int64FillValue", + "JSONValue", + "MetadataValidationError", + "NumpyDatetime64DataTypeName", + "NumpyDatetime64FillValue", + "NumpyTimeUnit", + "NumpyTimedelta64DataTypeName", + "NumpyTimedelta64FillValue", + "ProblemKind", + "RawBytesDataTypeName", + "RawBytesFillValue", + "RectilinearChunkGridMetadata", + "RectilinearChunkGridName", + "RegularChunkGridMetadata", + "RegularChunkGridName", + "ScaleOffsetCodecMetadata", + "ScaleOffsetCodecName", + "ShardingIndexLocation", + "ShardingIndexedCodecMetadata", + "ShardingIndexedCodecName", + "StringDataTypeName", + "StringFillValue", + "StructDataTypeName", + "StructFillValue", + "TransposeCodecMetadata", + "TransposeCodecName", + "Uint8DataTypeName", + "Uint8FillValue", + "Uint16DataTypeName", + "Uint16FillValue", + "Uint32DataTypeName", + "Uint32FillValue", + "Uint64DataTypeName", + "Uint64FillValue", + "V2ChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingName", + "V2ChunkKeyEncodingSeparator", + "ValidationProblem", + "ZarrV2ArrayDimensionSeparator", + "ZarrV2ArrayMetadata", + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayMetadataJSONPartial", + "ZarrV2ArrayMetadataPartial", + "ZarrV2ArrayMetadataStoreKey", + "ZarrV2ArrayOrder", + "ZarrV2AttributesStoreKey", + "ZarrV2CodecMetadata", + "ZarrV2ConsolidatedMetadata", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2ConsolidatedMetadataStoreKey", + "ZarrV2DataTypeMetadata", + "ZarrV2GroupMetadata", + "ZarrV2GroupMetadataJSON", + "ZarrV2GroupMetadataJSONPartial", + "ZarrV2GroupMetadataPartial", + "ZarrV2GroupMetadataStoreKey", + "ZarrV2ZArrayJSON", + "ZarrV2ZAttrsJSON", + "ZarrV2ZGroupJSON", + "ZarrV3ArrayMetadata", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ArrayMetadataJSONPartial", + "ZarrV3ArrayMetadataPartial", + "ZarrV3ArrayMetadataStoreKey", + "ZarrV3ConsolidatedMetadata", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3ExtensionField", + "ZarrV3GroupMetadata", + "ZarrV3GroupMetadataJSON", + "ZarrV3GroupMetadataJSONPartial", + "ZarrV3GroupMetadataPartial", + "ZarrV3GroupMetadataStoreKey", + "ZarrV3MetadataField", + "ZarrV3MetadataFieldJSON", + "ZarrV3NamedConfig", + "ZarrV3NamedConfigJSON", + "ZstdCodecMetadata", + "ZstdCodecName", + "__version__", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/_common.py b/packages/zarr-metadata/src/zarr_metadata/_common.py new file mode 100644 index 0000000000..08c143107f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/_common.py @@ -0,0 +1,50 @@ +""" +Top-level cross-version primitives for Zarr metadata. + +Version-specific types live under `zarr_metadata.v2` and `zarr_metadata.v3`. +Codec and dtype spec types live under `zarr_metadata.v3.codec` and +`zarr_metadata.v3.data_type`. +""" + +from collections.abc import Mapping, Sequence +from typing import NotRequired + +from typing_extensions import TypeAliasType, TypedDict + +JSONValue = TypeAliasType( + "JSONValue", + int | float | bool | str | Sequence["JSONValue"] | Mapping[str, "JSONValue"] | None, +) +"""A recursive type alias for JSON-encodable values. + +Defined via `TypeAliasType` (rather than a plain `TypeAlias`) so the +self-reference is a named recursion point that pydantic can resolve when +building a `TypeAdapter`; a bare recursive `TypeAlias` raises +`PydanticUserError`/`RecursionError` at validation time. + +The array arm is the covariant `Sequence` rather than the invariant +`list["JSONValue"] | tuple["JSONValue", ...]`, so values typed with a +*narrower* element type still count as JSON values: a `list[str]` field on a +TypedDict is assignable to `JSONValue` under `Sequence` but not under +`list[JSONValue]` (`list` is invariant in its element type, and pyright's +diagnostic for that failure suggests exactly this change). This is what lets +downstream TypedDicts give their fields precise types (`Sequence[str]`, +`list[int]`, ...) while remaining assignable to `Mapping[str, JSONValue]`. +The type-level cost, accepted deliberately: `Sequence` says nothing about the +concrete container, and it admits `str`/`bytes` (`str` was already a union +arm); runtime code narrowing a JSON array must exclude `str`/`bytes`/ +`bytearray` regardless of how this alias is spelled. +""" + + +class ZarrV3NamedConfigJSON(TypedDict): + """ + Externally-tagged union member for a metadata field. + + The optional `configuration` mapping holds arbitrary JSON-encodable + values. `must_understand` is implicitly true when absent. + """ + + name: str + configuration: NotRequired[Mapping[str, JSONValue]] + must_understand: NotRequired[bool] diff --git a/packages/zarr-metadata/src/zarr_metadata/_pydantic_schema.py b/packages/zarr-metadata/src/zarr_metadata/_pydantic_schema.py new file mode 100644 index 0000000000..e9792d6931 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/_pydantic_schema.py @@ -0,0 +1,114 @@ +"""Private input types used only to generate accurate Pydantic JSON schemas.""" + +from __future__ import annotations + +from collections.abc import Mapping # noqa: TC003 # resolved by Pydantic at runtime +from typing import Annotated, Literal, NotRequired + +from pydantic import Field +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v2.array import ( # noqa: TC001 # resolved by Pydantic at runtime + ZarrV2DataTypeMetadata, +) +from zarr_metadata.v2.codec import ( # resolved by Pydantic at runtime + ZarrV2CodecMetadata, +) + +NonNegativeInt = Annotated[int, Field(ge=0)] + + +class ZarrV3NamedConfigJSON(TypedDict, closed=True): + """Closed v3 named configuration accepted at optional extension points.""" + + name: str + configuration: NotRequired[Mapping[str, JSONValue]] + must_understand: NotRequired[bool] + + +class ZarrV3MandatoryNamedConfigJSON(TypedDict, closed=True): + """Closed named configuration accepted where understanding is mandatory.""" + + name: str + configuration: NotRequired[Mapping[str, JSONValue]] + must_understand: NotRequired[Literal[True]] + + +ZarrV3MetadataFieldJSON = str | ZarrV3NamedConfigJSON +ZarrV3MandatoryMetadataFieldJSON = str | ZarrV3MandatoryNamedConfigJSON +ZarrV3CodecPipelineJSON = Annotated[tuple[ZarrV3MetadataFieldJSON, ...], Field(min_length=1)] +ZarrV2FilterPipelineJSON = Annotated[tuple[ZarrV2CodecMetadata, ...], Field(min_length=1)] + + +class ZarrV3ArrayMetadataJSON(TypedDict, extra_items=JSONValue): + """Schema input for a v3 array document, including arbitrary extensions.""" + + zarr_format: Literal[3] + node_type: Literal["array"] + data_type: ZarrV3MandatoryMetadataFieldJSON + shape: tuple[NonNegativeInt, ...] + chunk_grid: ZarrV3MandatoryMetadataFieldJSON + chunk_key_encoding: ZarrV3MandatoryMetadataFieldJSON + fill_value: JSONValue + codecs: ZarrV3CodecPipelineJSON + attributes: NotRequired[Mapping[str, JSONValue]] + storage_transformers: NotRequired[tuple[ZarrV3MetadataFieldJSON, ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +class ZarrV3ConsolidatedMetadataJSON(TypedDict, closed=True): + """Schema input for the closed inline consolidated-metadata envelope.""" + + kind: Literal["inline"] + must_understand: Literal[False] + metadata: Mapping[str, ZarrV3ArrayMetadataJSON | ZarrV3GroupMetadataJSON] + + +class ZarrV3GroupMetadataJSON(TypedDict, extra_items=JSONValue): + """Schema input for a v3 group document, including arbitrary extensions.""" + + zarr_format: Literal[3] + node_type: Literal["group"] + attributes: NotRequired[Mapping[str, JSONValue]] + consolidated_metadata: NotRequired[ZarrV3ConsolidatedMetadataJSON | None] + + +class ZarrV2ArrayMetadataJSON(TypedDict, closed=True): + """Schema input for the closed, merged v2 array representation.""" + + zarr_format: Literal[2] + shape: tuple[NonNegativeInt, ...] + chunks: tuple[NonNegativeInt, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: Literal["C", "F"] + filters: ZarrV2FilterPipelineJSON | None + dimension_separator: NotRequired[Literal[".", "/"]] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV2GroupMetadataJSON(TypedDict, closed=True): + """Schema input for the closed, merged v2 group representation.""" + + zarr_format: Literal[2] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV2ConsolidatedMetadataJSON(TypedDict, closed=True): + """Schema input matching the v2 consolidated model's structural parser.""" + + zarr_consolidated_format: Literal[1] + metadata: Mapping[str, JSONValue] + + +__all__ = [ + "ZarrV2ArrayMetadataJSON", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2GroupMetadataJSON", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3GroupMetadataJSON", + "ZarrV3MetadataFieldJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/model/__init__.py b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py new file mode 100644 index 0000000000..edf3561d1d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py @@ -0,0 +1,148 @@ +"""In-memory models for Zarr metadata documents. + +Models are frozen dataclasses that hold a canonical, semantically lossless +representation of the JSON documents; they never interpret extension points +(codecs, chunk grids, data types). Validators check JSON structure, not domain validity. +Each document concept gets a `validate_*` function returning every problem +found (a `list[ValidationProblem]`, each with a machine-readable `kind`), an +`is_*` type guard, and a `parse_*` function that narrows or raises +`MetadataValidationError`. Model `from_json` / `from_key_value` constructors +raise `MetadataValidationError` for every ingestion failure, including +missing store keys and undecodable bytes. +""" + +from zarr_metadata.model._array import ( + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadataPartial, + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadataPartial, + ZarrV3MetadataField, + ZarrV3NamedConfig, +) +from zarr_metadata.model._group import ( + ZarrV2ConsolidatedMetadata, + ZarrV2GroupMetadata, + ZarrV2GroupMetadataPartial, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3GroupMetadataPartial, +) +from zarr_metadata.model._sentinel import UNSET +from zarr_metadata.model._validation import ( + ARRAY_METADATA_OPTIONAL_KEYS_V3, + ARRAY_METADATA_REQUIRED_KEYS_V2, + ARRAY_METADATA_REQUIRED_KEYS_V3, + ARRAY_METADATA_STANDARD_KEYS_V3, + GROUP_METADATA_OPTIONAL_KEYS_V3, + GROUP_METADATA_REQUIRED_KEYS_V2, + GROUP_METADATA_REQUIRED_KEYS_V3, + GROUP_METADATA_STANDARD_KEYS_V3, + MetadataValidationError, + ProblemKind, + ValidationProblem, + is_array_metadata_v2, + is_array_metadata_v3, + is_group_metadata_v2, + is_group_metadata_v3, + is_json, + is_metadata_field_v3, + parse_array_metadata_v2, + parse_array_metadata_v3, + parse_group_metadata_v2, + parse_group_metadata_v3, + parse_json, + parse_metadata_field_v3, + validate_array_metadata_v2, + validate_array_metadata_v3, + validate_group_metadata_v2, + validate_group_metadata_v3, + validate_json, + validate_metadata_field_v3, +) + +# Store keys are facts about the on-disk specs, so they are defined in the +# `v2`/`v3` modules that describe those documents. They are re-exported here +# because the model layer is where consumers reach for them. +from zarr_metadata.v2.array import ( + ZARR_V2_ARRAY_METADATA_STORE_KEY, + ZarrV2ArrayMetadataStoreKey, +) +from zarr_metadata.v2.attributes import ( + ZARR_V2_ATTRIBUTES_STORE_KEY, + ZarrV2AttributesStoreKey, +) +from zarr_metadata.v2.consolidated import ( + ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY, + ZarrV2ConsolidatedMetadataStoreKey, +) +from zarr_metadata.v2.group import ( + ZARR_V2_GROUP_METADATA_STORE_KEY, + ZarrV2GroupMetadataStoreKey, +) +from zarr_metadata.v3.array import ( + ZARR_V3_ARRAY_METADATA_STORE_KEY, + ZarrV3ArrayMetadataStoreKey, +) +from zarr_metadata.v3.consolidated import ZARR_V3_CONSOLIDATED_METADATA_KEY +from zarr_metadata.v3.group import ( + ZARR_V3_GROUP_METADATA_STORE_KEY, + ZarrV3GroupMetadataStoreKey, +) + +__all__ = [ + "ARRAY_METADATA_OPTIONAL_KEYS_V3", + "ARRAY_METADATA_REQUIRED_KEYS_V2", + "ARRAY_METADATA_REQUIRED_KEYS_V3", + "ARRAY_METADATA_STANDARD_KEYS_V3", + "GROUP_METADATA_OPTIONAL_KEYS_V3", + "GROUP_METADATA_REQUIRED_KEYS_V2", + "GROUP_METADATA_REQUIRED_KEYS_V3", + "GROUP_METADATA_STANDARD_KEYS_V3", + "UNSET", + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "MetadataValidationError", + "ProblemKind", + "ValidationProblem", + "ZarrV2ArrayMetadata", + "ZarrV2ArrayMetadataPartial", + "ZarrV2ArrayMetadataStoreKey", + "ZarrV2AttributesStoreKey", + "ZarrV2ConsolidatedMetadata", + "ZarrV2ConsolidatedMetadataStoreKey", + "ZarrV2GroupMetadata", + "ZarrV2GroupMetadataPartial", + "ZarrV2GroupMetadataStoreKey", + "ZarrV3ArrayMetadata", + "ZarrV3ArrayMetadataPartial", + "ZarrV3ArrayMetadataStoreKey", + "ZarrV3ConsolidatedMetadata", + "ZarrV3GroupMetadata", + "ZarrV3GroupMetadataPartial", + "ZarrV3GroupMetadataStoreKey", + "ZarrV3MetadataField", + "ZarrV3NamedConfig", + "is_array_metadata_v2", + "is_array_metadata_v3", + "is_group_metadata_v2", + "is_group_metadata_v3", + "is_json", + "is_metadata_field_v3", + "parse_array_metadata_v2", + "parse_array_metadata_v3", + "parse_group_metadata_v2", + "parse_group_metadata_v3", + "parse_json", + "parse_metadata_field_v3", + "validate_array_metadata_v2", + "validate_array_metadata_v3", + "validate_group_metadata_v2", + "validate_group_metadata_v3", + "validate_json", + "validate_metadata_field_v3", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array.py b/packages/zarr-metadata/src/zarr_metadata/model/_array.py new file mode 100644 index 0000000000..0b562bc188 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array.py @@ -0,0 +1,498 @@ +"""In-memory models for Zarr array metadata documents.""" + +from __future__ import annotations + +import copy +import dataclasses +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal, TypeAlias, cast + +from typing_extensions import TypedDict, Unpack + +from zarr_metadata.model._sentinel import UNSET +from zarr_metadata.model._validation import ( + ARRAY_METADATA_STANDARD_KEYS_V3, + MetadataValidationError, + ValidationProblem, + arrays_to_tuples, + dump_store_json, + load_store_json, + parse_array_metadata_v2, + parse_array_metadata_v3, + parse_metadata_field_v3, +) +from zarr_metadata.v2.array import ZARR_V2_ARRAY_METADATA_STORE_KEY +from zarr_metadata.v2.attributes import ZARR_V2_ATTRIBUTES_STORE_KEY +from zarr_metadata.v3.array import ZARR_V3_ARRAY_METADATA_STORE_KEY + +if TYPE_CHECKING: + from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON + from zarr_metadata.v2.array import ( + ZarrV2ArrayDimensionSeparator, + ZarrV2ArrayMetadataJSON, + ZarrV2ArrayMetadataStoreKey, + ZarrV2ArrayOrder, + ZarrV2DataTypeMetadata, + ) + from zarr_metadata.v2.attributes import ZarrV2AttributesStoreKey + from zarr_metadata.v2.codec import ZarrV2CodecMetadata + from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + from zarr_metadata.v3.array import ( + ZarrV3ArrayMetadataJSON, + ZarrV3ArrayMetadataStoreKey, + ZarrV3ExtensionField, + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3NamedConfig: + """A normalized v3 metadata field with its reader obligation. + + Bare names and missing configurations normalize to an empty configuration. + Bare names and missing `must_understand` members normalize to the spec's + implicit `True` value. + """ + + name: str + configuration: dict[str, JSONValue] + must_understand: bool = True + + def to_json(self) -> ZarrV3MetadataFieldJSON: + if not self.configuration and self.must_understand: + return self.name + out: ZarrV3NamedConfigJSON = {"name": self.name} + if self.configuration: + # to_json output shares no mutable state with the model. + out["configuration"] = copy.deepcopy(self.configuration) + if not self.must_understand: + out["must_understand"] = False + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV3NamedConfig: + field = parse_metadata_field_v3(data) + if isinstance(field, str): + return cls(name=field, configuration={}, must_understand=True) + # Sound cast: parse_metadata_field_v3 checked the configuration is a + # string-keyed mapping of JSON values; arrays_to_tuples only converts + # lists to tuples within that shape. + configuration = cast( + "dict[str, JSONValue]", arrays_to_tuples(dict(field.get("configuration", {}))) + ) + return cls( + name=field["name"], + configuration=configuration, + must_understand=field.get("must_understand", True), + ) + + +ZarrV3MetadataField: TypeAlias = ZarrV3NamedConfig +"""The in-memory model of one field of a v3 metadata document. + +This is the role-named alias for annotation positions: model fields and +consumer signatures should say `ZarrV3MetadataField` (the logical meaning) +rather than `ZarrV3NamedConfig` (the serialized form the field currently +takes). Today every metadata field normalizes to a named configuration plus +its reader obligation, so the alias is exactly `ZarrV3NamedConfig`; if a future +spec revision adds a field form that cannot be normalized to those values, +this alias widens to a union and annotation sites do not change. Mirrors the +raw-layer split between `ZarrV3NamedConfigJSON` (shape) and +`ZarrV3MetadataFieldJSON` (field union). +""" + + +def must_understand_subset( + extra_fields: Mapping[str, ZarrV3ExtensionField], +) -> dict[str, ZarrV3ExtensionField]: + """The subset of `extra_fields` the reader is obligated to understand. + + Per the v3 spec, an extension field is implicitly `must_understand: True` + unless it explicitly says otherwise, and an implementation MUST fail to + open a group or array carrying fields it does not recognize that are not + explicitly `must_understand: false`. A non-mapping field value cannot + carry the explicit waiver, so it always requires understanding (the + runtime isinstance check defends against values looser than the declared + `ZarrV3ExtensionField`). + """ + fields = cast("Mapping[str, object]", extra_fields) + return cast( + "dict[str, ZarrV3ExtensionField]", + { + name: value + for name, value in fields.items() + if not ( + isinstance(value, Mapping) + and cast("Mapping[str, object]", value).get("must_understand") is False + ) + }, + ) + + +class ZarrV3ArrayMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV3ArrayMetadata`. + + Every key is optional and typed with the model's own (not serialized) + value types, so it describes valid keyword arguments to + `ZarrV3ArrayMetadata.update`. The `init=False` fields `zarr_format` and + `node_type` are intentionally excluded, since they cannot be passed to + `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_array.py::test_partial_keys_match_settable_model_fields`. + """ + + shape: tuple[int, ...] + fill_value: JSONValue + data_type: ZarrV3MetadataField + chunk_grid: ZarrV3MetadataField + codecs: tuple[ZarrV3MetadataField, ...] + chunk_key_encoding: ZarrV3MetadataField + dimension_names: tuple[str | None, ...] | UNSET + attributes: dict[str, JSONValue] + storage_transformers: tuple[ZarrV3MetadataField, ...] + extra_fields: dict[str, ZarrV3ExtensionField] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3ArrayMetadata: + """In-memory model of a v3 array metadata document. + + A canonical, semantically lossless representation of the `zarr.json` + content for an array. Extension points (`data_type`, `chunk_grid`, + `chunk_key_encoding`, `codecs`, `storage_transformers`) are held as + `ZarrV3MetadataField` values (currently `ZarrV3NamedConfig` name, + configuration, and obligation records) and are never interpreted; + `fill_value` is held verbatim in its JSON form. Equivalent extension + spellings normalize to shorthand strings when configuration is empty and + understanding is required. + """ + + zarr_format: Literal[3] = field(default=3, init=False) + node_type: Literal["array"] = field(default="array", init=False) + shape: tuple[int, ...] + fill_value: JSONValue + data_type: ZarrV3MetadataField + chunk_grid: ZarrV3MetadataField + codecs: tuple[ZarrV3MetadataField, ...] + chunk_key_encoding: ZarrV3MetadataField + dimension_names: tuple[str | None, ...] | UNSET + attributes: dict[str, JSONValue] + storage_transformers: tuple[ZarrV3MetadataField, ...] + extra_fields: dict[str, ZarrV3ExtensionField] + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV3ArrayMetadataPartial]) -> ZarrV3ArrayMetadata: + """ + Create a default (empty) v3 array metadata model, with optional overrides. + + The default is a structurally-valid scalar `uint8` array — the array + analog of `list()` returning `[]`. Any field can be overridden by keyword + (the same fields accepted by `update`). Overriding `shape` without + `chunk_grid` derives a consistent default grid: one regular chunk + covering the array (`chunk_shape` equal to `shape`). + + The derivation is deliberately one-way. A user-supplied `chunk_grid` + is an extension point and is taken verbatim — deriving `shape` from + it would require interpreting the grid's configuration, which this + layer never does (and cannot do for unrecognized grid names). So + overriding `chunk_grid` without `shape` keeps the scalar default + `shape=()`, and consistency between the two is the caller's + responsibility. + """ + if "shape" in overrides and "chunk_grid" not in overrides: + overrides["chunk_grid"] = ZarrV3NamedConfig( + name="regular", configuration={"chunk_shape": tuple(overrides["shape"])} + ) + default = cls( + shape=(), + fill_value=0, + data_type=ZarrV3NamedConfig(name="uint8", configuration={}), + chunk_grid=ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": ()}), + codecs=(ZarrV3NamedConfig(name="bytes", configuration={}),), + chunk_key_encoding=ZarrV3NamedConfig(name="default", configuration={}), + dimension_names=UNSET, + attributes={}, + storage_transformers=(), + extra_fields={}, + ) + return default.update(**overrides) + + def update(self, **kwargs: Unpack[ZarrV3ArrayMetadataPartial]) -> ZarrV3ArrayMetadata: + """ + Return a new `ZarrV3ArrayMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV3ArrayMetadataPartial` can be updated; any attempt to update + other fields (including the fixed `zarr_format` / `node_type`) is + rejected at the type level. Each given field fully replaces its + previous value, including `extra_fields`. + + This is useful for test fixtures that want to override a few fields of a + base template without having to re-specify the entire document. + + No re-validation is performed (`update` is `dataclasses.replace`), so + a repair or edit can produce an invalid document; validity is checked + on `from_json`, not on field replacement. + """ + return dataclasses.replace(self, **kwargs) + + def __post_init__(self) -> None: + overlap = set(self.extra_fields.keys()).intersection(ARRAY_METADATA_STANDARD_KEYS_V3) + if overlap: + raise MetadataValidationError( + [ + ValidationProblem( + ("extra_fields",), + "Extra fields cannot overlap with standard Zarr V3 array metadata fields", + "invalid_value", + ) + ] + ) + + def to_json(self) -> ZarrV3ArrayMetadataJSON: + # to_json output shares no mutable state with the model: every value + # that can hold a mutable container is deep-copied. + out: ZarrV3ArrayMetadataJSON = { + "zarr_format": self.zarr_format, + "node_type": self.node_type, + "shape": self.shape, + "fill_value": copy.deepcopy(self.fill_value), + "data_type": self.data_type.to_json(), + "chunk_grid": self.chunk_grid.to_json(), + "codecs": tuple(codec.to_json() for codec in self.codecs), + "chunk_key_encoding": self.chunk_key_encoding.to_json(), + } + if self.dimension_names is not UNSET: + out["dimension_names"] = self.dimension_names + if len(self.attributes) > 0: + out["attributes"] = copy.deepcopy(self.attributes) + if len(self.storage_transformers) > 0: + out["storage_transformers"] = tuple( + transformer.to_json() for transformer in self.storage_transformers + ) + # Extra fields are the TypedDict's `extra_items` (PEP 728). Assign them + # by key rather than `out.update(**...)`: type checkers understand the + # indexed-write path against `extra_items`, but not the `update(**...)` + # overload. + for key, value in self.extra_fields.items(): + out[key] = copy.deepcopy(value) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV3ArrayMetadata: + parsed = parse_array_metadata_v3(arrays_to_tuples(data)) + # Sound cast: the TypedDict types all non-standard keys as its + # `extra_items` (`ZarrV3ExtensionField`); the comprehension's inferred value + # type is the union over ALL keys because the key filter cannot narrow it. + extra_fields = cast( + "dict[str, ZarrV3ExtensionField]", + {k: v for k, v in parsed.items() if k not in ARRAY_METADATA_STANDARD_KEYS_V3}, + ) + return cls( + shape=parsed["shape"], + fill_value=parsed["fill_value"], + data_type=ZarrV3NamedConfig.from_json(parsed["data_type"]), + chunk_grid=ZarrV3NamedConfig.from_json(parsed["chunk_grid"]), + codecs=tuple(ZarrV3NamedConfig.from_json(c) for c in parsed["codecs"]), + chunk_key_encoding=ZarrV3NamedConfig.from_json(parsed["chunk_key_encoding"]), + dimension_names=parsed.get("dimension_names", UNSET), + attributes=dict(parsed.get("attributes", {})), + storage_transformers=tuple( + ZarrV3NamedConfig.from_json(t) for t in parsed.get("storage_transformers", ()) + ), + extra_fields=extra_fields, + ) + + @property + def must_understand_fields(self) -> dict[str, ZarrV3ExtensionField]: + """Extra fields the reader is obligated to understand. + + Everything in `extra_fields` not explicitly waived with + `must_understand: false` (the spec's implicit-true rule). A compliant + reader MUST fail to open the array if this contains any field it does + not recognize; the model layer only partitions by obligation, since + recognition is reader-specific. + """ + return must_understand_subset(self.extra_fields) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV3ArrayMetadata: + return cls.from_json(load_store_json(mapping, ZARR_V3_ARRAY_METADATA_STORE_KEY)) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV3ArrayMetadataStoreKey, bytes]: + return {ZARR_V3_ARRAY_METADATA_STORE_KEY: dump_store_json(self.to_json(), indent=indent)} + + +class ZarrV2ArrayMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV2ArrayMetadata`. + + Every key is optional and typed with the model's own value types, so it + describes valid keyword arguments to `ZarrV2ArrayMetadata.update` and + `create_default`. The `init=False` field `zarr_format` is intentionally + excluded, since it cannot be passed to `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_array.py::test_v2_partial_keys_match_settable_model_fields`. + """ + + shape: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + chunks: tuple[int, ...] + fill_value: JSONValue + order: ZarrV2ArrayOrder + compressor: ZarrV2CodecMetadata | None + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: ZarrV2ArrayDimensionSeparator + attributes: dict[str, JSONValue] | UNSET + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV2ArrayMetadata: + """In-memory model of a v2 array metadata document. + + A canonical, lossless representation of the `.zarray` content plus the + sibling `.zattrs` attributes. `dtype`, `compressor`, and `filters` are + held in their raw JSON forms and are never interpreted; `fill_value` is + held verbatim in its JSON form. `attributes` is `UNSET` when no + `.zattrs` file (or merged `attributes` key) exists — distinct from an + explicit empty `.zattrs`, which is `{}` and round-trips as a file. One + spelling normalization: a `.zarray` that omits `dimension_separator` + means `"."` by the v2 convention, and the model holds and re-emits that + value explicitly. + """ + + zarr_format: Literal[2] = field(default=2, init=False) + shape: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + chunks: tuple[int, ...] + fill_value: JSONValue + order: ZarrV2ArrayOrder + compressor: ZarrV2CodecMetadata | None + filters: tuple[ZarrV2CodecMetadata, ...] | None + # "." is the v2 convention's default for an ABSENT dimension_separator key; + # from_json normalizes absence to it (a semantics-preserving spelling + # normalization, like the v3 bare-string metadata-field form). The value + # is never None: the document grammar has no null spelling for this field. + dimension_separator: ZarrV2ArrayDimensionSeparator = field(default=".") + attributes: dict[str, JSONValue] | UNSET + + def update(self, **kwargs: Unpack[ZarrV2ArrayMetadataPartial]) -> ZarrV2ArrayMetadata: + """ + Return a new `ZarrV2ArrayMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV2ArrayMetadataPartial` can be updated; the fixed `zarr_format` is + rejected at the type level. Each given field fully replaces its previous + value. + """ + return dataclasses.replace(self, **kwargs) + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV2ArrayMetadataPartial]) -> ZarrV2ArrayMetadata: + """ + Create a default (empty) v2 array metadata model, with optional overrides. + + The default is a structurally-valid scalar `uint8` (`"|u1"`) array — the + array analog of `list()` returning `[]`. Any field can be overridden by + keyword (the same fields accepted by `update`). Overriding `shape` + without `chunks` derives `chunks` equal to `shape` (one chunk covering + the array). + + The derivation is deliberately one-way, matching the v3 model: + overriding `chunks` without `shape` keeps the scalar default + `shape=()`, and consistency between the two is the caller's + responsibility. + """ + if "shape" in overrides and "chunks" not in overrides: + overrides["chunks"] = tuple(overrides["shape"]) + default = cls( + shape=(), + dtype="|u1", + chunks=(), + fill_value=0, + order="C", + compressor=None, + filters=None, + attributes=UNSET, + ) + return default.update(**overrides) + + def to_json(self) -> ZarrV2ArrayMetadataJSON: + """Return the merged in-memory document form. + + `attributes` is included when set (even empty). This is not the + on-disk `.zarray` content: a conforming `.zarray` must exclude + `attributes` (they live in the sibling `.zattrs` file). Use + `to_key_value` to produce the spec-conforming split for storage. + """ + # to_json output shares no mutable state with the model: every value + # that can hold a mutable container is deep-copied. + out: ZarrV2ArrayMetadataJSON = { + "zarr_format": self.zarr_format, + "shape": self.shape, + "dtype": self.dtype, + "order": self.order, + "chunks": self.chunks, + "fill_value": copy.deepcopy(self.fill_value), + "dimension_separator": self.dimension_separator, + "compressor": copy.deepcopy(self.compressor), + "filters": copy.deepcopy(self.filters), + } + if self.attributes is not UNSET: + out["attributes"] = copy.deepcopy(self.attributes) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV2ArrayMetadata: + parsed = parse_array_metadata_v2(arrays_to_tuples(data)) + return cls( + shape=parsed["shape"], + dtype=parsed["dtype"], + chunks=parsed["chunks"], + fill_value=parsed["fill_value"], + order=parsed["order"], + compressor=parsed["compressor"], + filters=parsed["filters"], + dimension_separator=parsed.get("dimension_separator", "."), + attributes=(dict(parsed["attributes"]) if "attributes" in parsed else UNSET), + ) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV2ArrayMetadata: + zarray_raw = cast("object", load_store_json(mapping, ZARR_V2_ARRAY_METADATA_STORE_KEY)) + if not isinstance(zarray_raw, Mapping): + return cls.from_json(zarray_raw) + zarray = cast("Mapping[str, object]", zarray_raw) + if "attributes" in zarray: + raise MetadataValidationError( + [ + ValidationProblem( + ("attributes",), + "unexpected document member", + "invalid_value", + ) + ] + ) + if ZARR_V2_ATTRIBUTES_STORE_KEY in mapping: + zattrs = cast("object", load_store_json(mapping, ZARR_V2_ATTRIBUTES_STORE_KEY)) + return cls.from_json({**zarray, "attributes": zattrs}) + return cls.from_json(zarray) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV2ArrayMetadataStoreKey | ZarrV2AttributesStoreKey, bytes]: + # Attributes live only in the sibling `.zattrs` file; the `.zarray` + # document must exclude them. The `.zattrs` key is present exactly + # when attributes are set (even empty) — UNSET emits no file. + zarray = {k: v for k, v in self.to_json().items() if k != "attributes"} + out: dict[ZarrV2ArrayMetadataStoreKey | ZarrV2AttributesStoreKey, bytes] = { + ZARR_V2_ARRAY_METADATA_STORE_KEY: dump_store_json(zarray, indent=indent) + } + if self.attributes is not UNSET: + out[ZARR_V2_ATTRIBUTES_STORE_KEY] = dump_store_json(self.attributes, indent=indent) + return out diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group.py b/packages/zarr-metadata/src/zarr_metadata/model/_group.py new file mode 100644 index 0000000000..63dfe5611f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group.py @@ -0,0 +1,436 @@ +"""In-memory models for Zarr group and consolidated metadata documents.""" + +from __future__ import annotations + +import copy +import dataclasses +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal, cast + +from typing_extensions import TypedDict, Unpack + +from zarr_metadata.model._array import ( + ZarrV3ArrayMetadata, + must_understand_subset, +) +from zarr_metadata.model._sentinel import UNSET +from zarr_metadata.model._validation import ( + GROUP_METADATA_STANDARD_KEYS_V3, + MetadataValidationError, + ValidationProblem, + arrays_to_tuples, + dump_store_json, + load_store_json, + parse_group_metadata_v2, + parse_group_metadata_v3, + validate_consolidated_metadata_v3, + validate_json, +) +from zarr_metadata.v2.attributes import ZARR_V2_ATTRIBUTES_STORE_KEY +from zarr_metadata.v2.consolidated import ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY +from zarr_metadata.v2.group import ZARR_V2_GROUP_METADATA_STORE_KEY +from zarr_metadata.v3.consolidated import ZARR_V3_CONSOLIDATED_METADATA_KEY +from zarr_metadata.v3.group import ZARR_V3_GROUP_METADATA_STORE_KEY + +if TYPE_CHECKING: + from zarr_metadata._common import JSONValue + from zarr_metadata.v2.attributes import ZarrV2AttributesStoreKey + from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataStoreKey + from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON, ZarrV2GroupMetadataStoreKey + from zarr_metadata.v3.array import ZarrV3ExtensionField + from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON + from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataStoreKey + + +class ZarrV3GroupMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV3GroupMetadata`. + + Every key is optional and typed with the model's own value types, so it + describes valid keyword arguments to `ZarrV3GroupMetadata.update` and + `create_default`. The `init=False` fields `zarr_format` and `node_type` + are intentionally excluded, since they cannot be passed to + `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_group.py::test_group_partial_keys_match_settable_model_fields`. + """ + + attributes: dict[str, JSONValue] + consolidated_metadata: ZarrV3ConsolidatedMetadata | UNSET + extra_fields: dict[str, ZarrV3ExtensionField] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3GroupMetadata: + """In-memory model of a v3 group metadata document. + + A canonical, semantically lossless representation of the `zarr.json` + content for a group. The `consolidated_metadata` reference-implementation + convention is modeled as a typed field holding thin child models; every + other unknown top-level key lands in `extra_fields` verbatim. + """ + + zarr_format: Literal[3] = field(default=3, init=False) + node_type: Literal["group"] = field(default="group", init=False) + attributes: dict[str, JSONValue] + consolidated_metadata: ZarrV3ConsolidatedMetadata | UNSET + extra_fields: dict[str, ZarrV3ExtensionField] + + def __post_init__(self) -> None: + reserved = GROUP_METADATA_STANDARD_KEYS_V3 | {ZARR_V3_CONSOLIDATED_METADATA_KEY} + if set(self.extra_fields.keys()).intersection(reserved): + raise MetadataValidationError( + [ + ValidationProblem( + ("extra_fields",), + "Extra fields cannot overlap with standard Zarr V3 group metadata fields", + "invalid_value", + ) + ] + ) + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV3GroupMetadataPartial]) -> ZarrV3GroupMetadata: + """ + Create a default (empty) v3 group metadata model, with optional overrides. + + The default is a structurally-valid group with no attributes — the group + analog of `list()` returning `[]`. Any field can be overridden by keyword + (the same fields accepted by `update`). + """ + default = cls(attributes={}, consolidated_metadata=UNSET, extra_fields={}) + return default.update(**overrides) + + def update(self, **kwargs: Unpack[ZarrV3GroupMetadataPartial]) -> ZarrV3GroupMetadata: + """ + Return a new `ZarrV3GroupMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV3GroupMetadataPartial` can be updated; the fixed `zarr_format` / + `node_type` are rejected at the type level. Each given field fully + replaces its previous value, including `extra_fields`. + """ + return dataclasses.replace(self, **kwargs) + + def to_json(self) -> ZarrV3GroupMetadataJSON: + # to_json output shares no mutable state with the model: every value + # that can hold a mutable container is deep-copied. + out: ZarrV3GroupMetadataJSON = { + "zarr_format": self.zarr_format, + "node_type": self.node_type, + } + if len(self.attributes) > 0: + out["attributes"] = copy.deepcopy(self.attributes) + if self.consolidated_metadata is not UNSET: + # Consolidated metadata is a known non-core top-level JSON field. + out[ZARR_V3_CONSOLIDATED_METADATA_KEY] = cast( + "ZarrV3ExtensionField", self.consolidated_metadata.to_json() + ) + for key, value in self.extra_fields.items(): + out[key] = copy.deepcopy(value) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV3GroupMetadata: + parsed = parse_group_metadata_v3(arrays_to_tuples(data)) + # Cast for narrowing across standard and arbitrary extra TypedDict items. + consolidated_raw = cast("object", parsed.get(ZARR_V3_CONSOLIDATED_METADATA_KEY, UNSET)) + consolidated: ZarrV3ConsolidatedMetadata | UNSET + if consolidated_raw is UNSET or consolidated_raw is None: + # consolidated_metadata: null was written by a historical + # zarr-python bug; it gets no model representation. It is read as + # absence and never written back — repaired, not preserved. + consolidated = UNSET + else: + consolidated = ZarrV3ConsolidatedMetadata.from_json(consolidated_raw) + # Sound cast: the TypedDict types all non-standard keys as its + # `extra_items` (`ZarrV3ExtensionField`); the comprehension's inferred value + # type is the union over ALL keys because the key filter cannot narrow it. + extra_fields = cast( + "dict[str, ZarrV3ExtensionField]", + { + k: v + for k, v in parsed.items() + if k not in GROUP_METADATA_STANDARD_KEYS_V3 + and k != ZARR_V3_CONSOLIDATED_METADATA_KEY + }, + ) + return cls( + attributes=dict(parsed.get("attributes", {})), + consolidated_metadata=consolidated, + extra_fields=extra_fields, + ) + + @property + def must_understand_fields(self) -> dict[str, ZarrV3ExtensionField]: + """Extra fields the reader is obligated to understand. + + Everything in `extra_fields` not explicitly waived with + `must_understand: false` (the spec's implicit-true rule). A compliant + reader MUST fail to open the group if this contains any field it does + not recognize; the model layer only partitions by obligation, since + recognition is reader-specific. + """ + return must_understand_subset(self.extra_fields) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV3GroupMetadata: + return cls.from_json(load_store_json(mapping, ZARR_V3_GROUP_METADATA_STORE_KEY)) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV3GroupMetadataStoreKey, bytes]: + return {ZARR_V3_GROUP_METADATA_STORE_KEY: dump_store_json(self.to_json(), indent=indent)} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3ConsolidatedMetadata: + """In-memory model of v3 inline consolidated metadata. + + Models the reference-implementation convention where consolidated metadata + is embedded as an extension field on a group's `zarr.json`. Each entry in + `metadata` is a complete child document, held as a thin array or group + model. `must_understand` is typed permissively as `bool` to mirror the + document shape, but only `False` is valid; this is enforced at runtime. + """ + + kind: Literal["inline"] = field(default="inline", init=False) + must_understand: bool = False + metadata: dict[str, ZarrV3ArrayMetadata | ZarrV3GroupMetadata] + + def __post_init__(self) -> None: + if self.must_understand is not False: + raise MetadataValidationError( + [ + ValidationProblem( + ("must_understand",), + f"Invalid value for 'must_understand'. Expected False. " + f"Got {self.must_understand!r}.", + "invalid_value", + ) + ] + ) + + def to_json(self) -> ZarrV3ConsolidatedMetadataJSON: + # `must_understand` is emitted as the literal False: the field is typed + # permissively as `bool`, but `__post_init__` guarantees the value. + return { + "kind": self.kind, + "must_understand": False, + "metadata": {key: node.to_json() for key, node in self.metadata.items()}, + } + + @classmethod + def from_json(cls, data: object) -> ZarrV3ConsolidatedMetadata: + normalized = arrays_to_tuples(data) + problems = validate_consolidated_metadata_v3(normalized) + if problems: + raise MetadataValidationError(problems) + env = cast("Mapping[str, object]", normalized) + entries: dict[str, ZarrV3ArrayMetadata | ZarrV3GroupMetadata] = {} + for key, entry in cast("Mapping[str, object]", env["metadata"]).items(): + node_type = cast("Mapping[str, object]", entry).get("node_type") + if node_type == "array": + entries[key] = ZarrV3ArrayMetadata.from_json(entry) + else: + entries[key] = ZarrV3GroupMetadata.from_json(entry) + return cls(metadata=entries) + + +class ZarrV2GroupMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV2GroupMetadata`. + + Every key is optional and typed with the model's own value types, so it + describes valid keyword arguments to `ZarrV2GroupMetadata.update` and + `create_default`. The `init=False` field `zarr_format` is intentionally + excluded, since it cannot be passed to `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_group.py::test_group_partial_keys_match_settable_model_fields`. + """ + + attributes: dict[str, JSONValue] | UNSET + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV2GroupMetadata: + """In-memory model of a v2 group metadata document. + + A canonical, lossless representation of the `.zgroup` content plus the + sibling `.zattrs` attributes, folded into a single in-memory value + (mirroring the merged `ZarrV2GroupMetadataJSON` document form). `attributes` is + `UNSET` when no `.zattrs` file (or merged `attributes` key) exists — + distinct from an explicit empty `.zattrs`, which is `{}` and round-trips + as a file. + """ + + zarr_format: Literal[2] = field(default=2, init=False) + attributes: dict[str, JSONValue] | UNSET + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV2GroupMetadataPartial]) -> ZarrV2GroupMetadata: + """ + Create a default (empty) v2 group metadata model, with optional overrides. + + The default is a structurally-valid group with no attributes — the group + analog of `list()` returning `[]`. Any field can be overridden by keyword + (the same fields accepted by `update`). + """ + default = cls(attributes=UNSET) + return default.update(**overrides) + + def update(self, **kwargs: Unpack[ZarrV2GroupMetadataPartial]) -> ZarrV2GroupMetadata: + """ + Return a new `ZarrV2GroupMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV2GroupMetadataPartial` can be updated; the fixed `zarr_format` + is rejected at the type level. Each given field fully replaces its + previous value. + """ + return dataclasses.replace(self, **kwargs) + + def to_json(self) -> ZarrV2GroupMetadataJSON: + """Return the merged in-memory document form. + + `attributes` is included when set (even empty). This is not the + on-disk `.zgroup` content: a conforming `.zgroup` must exclude + `attributes` (they live in the sibling `.zattrs` file). Use + `to_key_value` to produce the spec-conforming split for storage. + """ + # to_json output shares no mutable state with the model. + out: ZarrV2GroupMetadataJSON = {"zarr_format": self.zarr_format} + if self.attributes is not UNSET: + out["attributes"] = copy.deepcopy(self.attributes) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV2GroupMetadata: + parsed = parse_group_metadata_v2(arrays_to_tuples(data)) + return cls(attributes=(dict(parsed["attributes"]) if "attributes" in parsed else UNSET)) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV2GroupMetadata: + zgroup_raw = cast("object", load_store_json(mapping, ZARR_V2_GROUP_METADATA_STORE_KEY)) + if not isinstance(zgroup_raw, Mapping): + return cls.from_json(zgroup_raw) + zgroup = cast("Mapping[str, object]", zgroup_raw) + if "attributes" in zgroup: + raise MetadataValidationError( + [ + ValidationProblem( + ("attributes",), + "unexpected document member", + "invalid_value", + ) + ] + ) + if ZARR_V2_ATTRIBUTES_STORE_KEY in mapping: + zattrs = cast("object", load_store_json(mapping, ZARR_V2_ATTRIBUTES_STORE_KEY)) + return cls.from_json({**zgroup, "attributes": zattrs}) + return cls.from_json(zgroup) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV2GroupMetadataStoreKey | ZarrV2AttributesStoreKey, bytes]: + # Attributes live only in the sibling `.zattrs` file; the `.zgroup` + # document must exclude them. The `.zattrs` key is present exactly + # when attributes are set (even empty) — UNSET emits no file. + zgroup = {k: v for k, v in self.to_json().items() if k != "attributes"} + out: dict[ZarrV2GroupMetadataStoreKey | ZarrV2AttributesStoreKey, bytes] = { + ZARR_V2_GROUP_METADATA_STORE_KEY: dump_store_json(zgroup, indent=indent) + } + if self.attributes is not UNSET: + out[ZARR_V2_ATTRIBUTES_STORE_KEY] = dump_store_json(self.attributes, indent=indent) + return out + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV2ConsolidatedMetadata: + """In-memory model of a v2 `.zmetadata` document. + + The `metadata` map holds the flat file-keyed entries (`"path/.zarray"`, + `"path/.zattrs"`, ...) verbatim, preserving the normalized JSON tree. + Entries are deliberately NOT merged into per-node models: which nodes had + a `.zattrs` file at all is information the canonical representation must + keep. Interpreting entries into node models is consumer work. + """ + + zarr_consolidated_format: Literal[1] = field(default=1, init=False) + metadata: dict[str, JSONValue] + + def to_json(self) -> dict[str, JSONValue]: + # to_json output shares no mutable state with the model. + return { + "zarr_consolidated_format": self.zarr_consolidated_format, + "metadata": copy.deepcopy(self.metadata), + } + + @classmethod + def from_json(cls, data: object) -> ZarrV2ConsolidatedMetadata: + normalized = arrays_to_tuples(data) + if not isinstance(normalized, Mapping): + raise MetadataValidationError( + [ValidationProblem((), "expected a mapping", "invalid_type")] + ) + doc = cast("Mapping[str, object]", normalized) + problems: list[ValidationProblem] = [ + ValidationProblem((key,), "missing required key", "missing_key") + for key in ("zarr_consolidated_format", "metadata") + if key not in doc + ] + problems.extend( + ValidationProblem((key,), "unexpected document member", "invalid_value") + for key in doc.keys() - {"zarr_consolidated_format", "metadata"} + ) + if "zarr_consolidated_format" in doc and ( + not isinstance(doc["zarr_consolidated_format"], int) + or isinstance(doc["zarr_consolidated_format"], bool) + or doc["zarr_consolidated_format"] != 1 + ): + problems.append( + ValidationProblem( + ("zarr_consolidated_format",), + f"expected 1, got {doc['zarr_consolidated_format']!r}", + "invalid_value", + ) + ) + if "metadata" in doc: + entries = doc["metadata"] + if not isinstance(entries, Mapping) or not all( + isinstance(k, str) for k in cast("Mapping[object, object]", entries) + ): + problems.append( + ValidationProblem( + ("metadata",), "expected a mapping with string keys", "invalid_type" + ) + ) + else: + for key, value in cast("Mapping[str, object]", entries).items(): + problems.extend( + ValidationProblem( + ("metadata", key, *problem.loc), problem.message, problem.kind + ) + for problem in validate_json(value) + ) + if problems: + raise MetadataValidationError(problems) + entries_tupled = cast( + "dict[str, JSONValue]", + arrays_to_tuples(dict(cast("Mapping[str, object]", doc["metadata"]))), + ) + return cls(metadata=entries_tupled) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV2ConsolidatedMetadata: + return cls.from_json(load_store_json(mapping, ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY)) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV2ConsolidatedMetadataStoreKey, bytes]: + return { + ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY: dump_store_json(self.to_json(), indent=indent) + } diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_sentinel.py b/packages/zarr-metadata/src/zarr_metadata/model/_sentinel.py new file mode 100644 index 0000000000..ad71e216fa --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_sentinel.py @@ -0,0 +1,37 @@ +"""The absence sentinel for optional metadata-document keys. + +The models observe one invariant: `None` in a model always corresponds to a +JSON `null` in the document (a v2 `compressor`/`filters` value, an unnamed +dimension inside `dimension_names`), and `UNSET` always means the document +key is absent. The two are never interchangeable, so a model value can never +leak into a document as a spelling the writer did not intend. + +Check with identity: `if model.dimension_names is UNSET: ...`. + +Because the contract is identity, the sentinel must never be reconstructed +from state: pickling and copying work by *reference* (typing_extensions >= +4.16 implements `Sentinel.__reduce__` as a lookup of the sentinel's name on +its defining module), so `pickle.loads(pickle.dumps(UNSET)) is UNSET` holds +across process boundaries, and models holding `UNSET` pickle and deep-copy +freely. Earlier typing_extensions releases refused to pickle sentinels +outright — hence the `>=4.16` floor in this package's dependencies. + +Checker support (PEP 661 is Final; stdlib `sentinel` arrives in Python +3.15): ty types this spelling exactly, including `is`/`is not` narrowing. +Pyright supports it but a regression (1.1.405+, tracked as +https://github.com/microsoft/pyright/issues/11115) degrades class-attribute +reads to `Unknown`, so this package pins pyright to the last good version +until the fix lands. Mypy support is in review +(https://github.com/python/mypy/pull/21647); until it merges, mypy-checked +consumers of these fields need a `cast` or `type: ignore` at narrowing +sites. This is a deliberate short-term cost: the sentinel is the standard, +and the checkers are converging on it. +""" + +from __future__ import annotations + +from typing_extensions import Sentinel + +UNSET = Sentinel("UNSET") +"""Marks a metadata-document key as absent (PEP 661 sentinel; usable directly +in type expressions, e.g. `tuple[str, ...] | UNSET`). Test with `is UNSET`.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_validation.py b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py new file mode 100644 index 0000000000..a12e1911b1 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py @@ -0,0 +1,875 @@ +"""Structural validation for Zarr metadata documents. + +Validators check JSON structure (key presence, value shapes, and fixed +literals like `zarr_format`), not domain validity. Each concept gets a +`validate_*` function returning every problem found, an `is_*` type guard, +and a `parse_*` function that narrows or raises `MetadataValidationError`. + +Every `ValidationProblem` carries a machine-readable `kind` alongside its +human-readable `message`, so consumers can dispatch on the failure mode +(`missing_key`, `invalid_type`, `invalid_value`, `invalid_json`) without +string-matching messages. +""" + +from __future__ import annotations + +import json +import math +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Final, Literal, NoReturn, cast + +from typing_extensions import TypeIs + +from zarr_metadata._common import JSONValue +from zarr_metadata.v2.array import ZarrV2ArrayMetadataJSON +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + +ProblemKind = Literal["missing_key", "invalid_type", "invalid_value", "invalid_json"] +"""Machine-readable classification of a `ValidationProblem`. + +- `missing_key`: a required key (document key or store key) is absent. +- `invalid_type`: a value has the wrong structural type (e.g. a string where + a mapping is required, a non-JSON-serializable object). +- `invalid_value`: a value has an acceptable type but an invalid content + (e.g. `zarr_format: 2` in a v3 document, `order: "Q"`). +- `invalid_json`: bytes that do not decode as JSON. +""" + + +@dataclass(frozen=True, slots=True) +class ValidationProblem: + """A single structural problem found while validating a metadata document. + + `loc` is the path from the document root to the offending value, e.g. + `("codecs", 0, "name")`. An empty `loc` refers to the document as a whole. + `kind` classifies the failure mode for programmatic dispatch; `message` + is the human-readable description. + """ + + loc: tuple[str | int, ...] + message: str + kind: ProblemKind + + def __str__(self) -> str: + location = ".".join(str(part) for part in self.loc) if self.loc else "" + return f"{location}: {self.message}" + + +class MetadataValidationError(ValueError): + """Raised when a value fails structural metadata validation. + + Carries every problem found (not just the first) in `.problems`. + """ + + def __init__(self, problems: list[ValidationProblem]) -> None: + self.problems = problems + super().__init__("\n".join(str(problem) for problem in problems)) + + +def _prefix(loc_head: str | int, problems: list[ValidationProblem]) -> list[ValidationProblem]: + """Prepend `loc_head` to the `loc` of every problem (for nested validators).""" + return [ValidationProblem((loc_head, *p.loc), p.message, p.kind) for p in problems] + + +def validate_json(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not JSON-serializable (recursively).""" + if isinstance(value, float): + if math.isfinite(value): + return [] + return [ValidationProblem((), f"non-finite float {value!r} is not JSON", "invalid_value")] + if isinstance(value, (str, int, bool)) or value is None: + return [] + problems: list[ValidationProblem] = [] + if isinstance(value, Mapping): + for key, item in cast("Mapping[object, object]", value).items(): + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string key {key!r} in JSON object", "invalid_type") + ) + continue + problems.extend(_prefix(key, validate_json(item))) + return problems + if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray)): + for index, item in enumerate(cast("Sequence[object]", value)): + problems.extend(_prefix(index, validate_json(item))) + return problems + return [ValidationProblem((), f"not a JSON-serializable value: {value!r}", "invalid_type")] + + +def _is_canonical_json(value: object) -> TypeIs[JSONValue]: + """Whether `value` already uses the concrete containers in `JSONValue`.""" + if isinstance(value, float): + return math.isfinite(value) + if isinstance(value, (str, int, bool)) or value is None: + return True + if isinstance(value, (list, tuple)): + sequence = cast("list[object] | tuple[object, ...]", value) + return all(_is_canonical_json(item) for item in sequence) + if isinstance(value, dict): + mapping = cast("dict[object, object]", value) + return all( + isinstance(key, str) and _is_canonical_json(item) for key, item in mapping.items() + ) + return False + + +def is_json(value: object) -> TypeIs[JSONValue]: + """Whether `value` is a canonical JSON structure (recursively).""" + return _is_canonical_json(value) + + +def parse_json(value: object) -> JSONValue: + """Return a canonical `JSONValue`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_json(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(JSONValue, normalized) + + +# The standard top-level keys of a v3 array metadata document. Anything outside +# this set is an extension field. Built from the TypedDict's required/optional +# key sets (which resolve inherited keys, unlike `__annotations__`). +ARRAY_METADATA_REQUIRED_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3ArrayMetadataJSON.__required_keys__ +) +ARRAY_METADATA_OPTIONAL_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3ArrayMetadataJSON.__optional_keys__ +) +ARRAY_METADATA_STANDARD_KEYS_V3: Final[frozenset[str]] = ( + ARRAY_METADATA_REQUIRED_KEYS_V3 | ARRAY_METADATA_OPTIONAL_KEYS_V3 +) + +ARRAY_METADATA_REQUIRED_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2ArrayMetadataJSON.__required_keys__ +) +ARRAY_METADATA_OPTIONAL_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2ArrayMetadataJSON.__optional_keys__ +) +ARRAY_METADATA_STANDARD_KEYS_V2: Final[frozenset[str]] = ( + ARRAY_METADATA_REQUIRED_KEYS_V2 | ARRAY_METADATA_OPTIONAL_KEYS_V2 +) + +# The standard top-level keys of a v3 group metadata document. Anything outside +# this set is an extension field. +GROUP_METADATA_REQUIRED_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3GroupMetadataJSON.__required_keys__ +) +GROUP_METADATA_OPTIONAL_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3GroupMetadataJSON.__optional_keys__ +) +GROUP_METADATA_STANDARD_KEYS_V3: Final[frozenset[str]] = ( + GROUP_METADATA_REQUIRED_KEYS_V3 | GROUP_METADATA_OPTIONAL_KEYS_V3 +) + +GROUP_METADATA_REQUIRED_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2GroupMetadataJSON.__required_keys__ +) +GROUP_METADATA_OPTIONAL_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2GroupMetadataJSON.__optional_keys__ +) +GROUP_METADATA_STANDARD_KEYS_V2: Final[frozenset[str]] = ( + GROUP_METADATA_REQUIRED_KEYS_V2 | GROUP_METADATA_OPTIONAL_KEYS_V2 +) + + +def _missing_keys(required: frozenset[str], doc: Mapping[str, object]) -> list[ValidationProblem]: + """One `missing_key` problem per required key absent from `doc`.""" + return [ + ValidationProblem((key,), "missing required key", "missing_key") + for key in sorted(required - doc.keys()) + ] + + +def _unexpected_keys( + allowed: frozenset[str], doc: Mapping[object, object] +) -> list[ValidationProblem]: + """One problem per member outside a closed document's declared shape.""" + problems: list[ValidationProblem] = [] + for key in doc: + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string document key {key!r}", "invalid_type") + ) + elif key not in allowed: + problems.append( + ValidationProblem((key,), "unexpected document member", "invalid_value") + ) + return problems + + +def _check_literal( + doc: Mapping[str, object], key: str, expected: object +) -> list[ValidationProblem]: + """One `invalid_value` problem if `doc[key]` is present but not `expected`.""" + if key in doc and (type(doc[key]) is not type(expected) or doc[key] != expected): + return [ + ValidationProblem((key,), f"expected {expected!r}, got {doc[key]!r}", "invalid_value") + ] + return [] + + +def _validate_extension_fields_v3( + doc: Mapping[object, object], + standard_keys: frozenset[str], + *, + additional_reserved_keys: frozenset[str] = frozenset(), +) -> list[ValidationProblem]: + """Validate v3 top-level key types and unknown-field JSON payloads.""" + problems: list[ValidationProblem] = [] + reserved_keys = standard_keys | additional_reserved_keys + for key, value in doc.items(): + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string top-level key {key!r}", "invalid_type") + ) + continue + if key in reserved_keys: + continue + problems.extend(_prefix(key, validate_json(value))) + return problems + + +def validate_metadata_field_v3( + value: object, *, allow_must_understand_false: bool = True +) -> list[ValidationProblem]: + """Return every reason `value` is not a v3 metadata field. + + A metadata field is a bare name string or a mapping containing `name` and + optional `configuration` and `must_understand` members. + """ + if isinstance(value, str): + return [] + if not isinstance(value, Mapping): + return [ + ValidationProblem( + (), + "expected a metadata field (string or extension object)", + "invalid_type", + ) + ] + field = cast("Mapping[object, object]", value) + problems: list[ValidationProblem] = [] + allowed_keys = frozenset({"name", "configuration", "must_understand"}) + for key in field: + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string metadata field key {key!r}", "invalid_type") + ) + elif key not in allowed_keys: + problems.append( + ValidationProblem((key,), "unexpected metadata field member", "invalid_value") + ) + if not isinstance(field.get("name"), str): + problems.append(ValidationProblem(("name",), "expected a string name", "invalid_type")) + if "configuration" in field: + configuration = field["configuration"] + if not isinstance(configuration, Mapping): + problems.append( + ValidationProblem(("configuration",), "expected a mapping", "invalid_type") + ) + elif not all(isinstance(k, str) for k in cast("Mapping[object, object]", configuration)): + problems.append( + ValidationProblem(("configuration",), "expected string keys", "invalid_type") + ) + else: + for key, item in cast("Mapping[str, object]", configuration).items(): + problems.extend(_prefix("configuration", _prefix(key, validate_json(item)))) + if "must_understand" in field: + must_understand = field["must_understand"] + if not isinstance(must_understand, bool): + problems.append( + ValidationProblem(("must_understand",), "expected a boolean", "invalid_type") + ) + elif not allow_must_understand_false and not must_understand: + problems.append( + ValidationProblem( + ("must_understand",), + "false is not supported at this extension point", + "invalid_value", + ) + ) + return problems + + +def is_metadata_field_v3(value: object) -> TypeIs[ZarrV3MetadataFieldJSON]: + """Whether `value` is a v3 metadata field: a bare name or a named config.""" + if isinstance(value, str): + return True + if not isinstance(value, dict): + return False + field = cast("dict[object, object]", value) + return _is_canonical_json(field) and not validate_metadata_field_v3(field) + + +def parse_metadata_field_v3(value: object) -> ZarrV3MetadataFieldJSON: + """Return `value` narrowed to `ZarrV3MetadataFieldJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_metadata_field_v3(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(ZarrV3MetadataFieldJSON, normalized) + + +def _is_int_sequence(value: object) -> bool: + """Whether `value` is a non-string sequence of integers. + + JSON booleans decode to `bool`, which is an `int` subclass in Python but + is not an integer in a metadata document, so booleans are excluded. + """ + return ( + not isinstance(value, (str, bytes, bytearray)) + and isinstance(value, Sequence) + and all( + isinstance(item, int) and not isinstance(item, bool) + for item in cast("Sequence[object]", value) + ) + ) + + +def _validate_dim_sequence(doc: Mapping[str, object], key: str) -> list[ValidationProblem]: + """Validate a dimension sequence (`shape` / `chunks`) if present in `doc`. + + Dimension lengths are non-negative integers. + """ + if key not in doc: + return [] + value = doc[key] + if not _is_int_sequence(value): + return [ValidationProblem((key,), "expected a sequence of int", "invalid_type")] + if any(item < 0 for item in cast("Sequence[int]", value)): + return [ValidationProblem((key,), "expected non-negative integers", "invalid_value")] + return [] + + +def _is_dtype_v2(value: object) -> bool: + """Whether `value` is shaped like a v2 dtype: a string or field records. + + A field record is a `(name, dtype)` or `(name, dtype, shape)` sequence, + where `dtype` is itself a string or nested field records and `shape` is a + sequence of int. The string content is NOT interpreted — whether the + string names a real dtype is domain validity, not structure. + """ + if isinstance(value, str): + return True + if not isinstance(value, Sequence): + return False + for record in cast("Sequence[object]", value): + if isinstance(record, str) or not isinstance(record, Sequence): + return False + fields = cast("Sequence[object]", record) + if len(fields) not in (2, 3): + return False + if not isinstance(fields[0], str): + return False + if not _is_dtype_v2(fields[1]): + return False + if len(fields) == 3 and not _is_int_sequence(fields[2]): + return False + return True + + +def _is_canonical_dtype_v2(value: object) -> bool: + """Whether a validated v2 dtype uses the tuple-backed public representation.""" + if isinstance(value, str): + return True + if not isinstance(value, tuple): + return False + for record in cast("tuple[object, ...]", value): + if not isinstance(record, tuple): + return False + fields = cast("tuple[object, ...]", record) + if not _is_canonical_dtype_v2(fields[1]): + return False + if len(fields) == 3 and not isinstance(fields[2], tuple): + return False + return True + + +def _is_canonical_metadata_field_v3(value: object) -> bool: + """Whether a validated v3 metadata field has its declared runtime container type.""" + return isinstance(value, (str, dict)) + + +def _is_canonical_array_metadata_v3(value: object) -> bool: + """Whether a validated v3 array document matches `ZarrV3ArrayMetadataJSON` at runtime.""" + if not isinstance(value, dict): + return False + doc = cast("dict[str, object]", value) + if not isinstance(doc["shape"], tuple) or not isinstance(doc["codecs"], tuple): + return False + if "storage_transformers" in doc and not isinstance(doc["storage_transformers"], tuple): + return False + if "dimension_names" in doc and not isinstance(doc["dimension_names"], tuple): + return False + if not all( + _is_canonical_metadata_field_v3(doc[key]) + for key in ("data_type", "chunk_grid", "chunk_key_encoding") + ): + return False + if not all( + _is_canonical_metadata_field_v3(item) for item in cast("tuple[object, ...]", doc["codecs"]) + ): + return False + return "storage_transformers" not in doc or all( + _is_canonical_metadata_field_v3(item) + for item in cast("tuple[object, ...]", doc["storage_transformers"]) + ) + + +def _is_canonical_array_metadata_v2(value: object) -> bool: + """Whether a validated v2 array document matches `ZarrV2ArrayMetadataJSON` at runtime.""" + if not isinstance(value, dict): + return False + doc = cast("dict[str, object]", value) + if not isinstance(doc["shape"], tuple) or not isinstance(doc["chunks"], tuple): + return False + if not _is_canonical_dtype_v2(doc["dtype"]): + return False + compressor = doc["compressor"] + if compressor is not None and not isinstance(compressor, dict): + return False + filters = doc["filters"] + return filters is None or ( + isinstance(filters, tuple) + and all(isinstance(item, dict) for item in cast("tuple[object, ...]", filters)) + ) + + +def _is_codec_v2(value: object) -> bool: + """Whether `value` is shaped like a v2 codec config: a mapping with a string `id`.""" + return isinstance(value, Mapping) and isinstance( + cast("Mapping[object, object]", value).get("id"), str + ) + + +def _validate_codec_v2(value: object) -> list[ValidationProblem]: + """Validate a v2 codec's required shape and JSON-valued configuration.""" + if not _is_codec_v2(value): + return [ + ValidationProblem( + (), "expected a codec configuration with a string 'id'", "invalid_type" + ) + ] + return validate_json(value) + + +def _validate_attributes(value: object) -> list[ValidationProblem]: + """Validate an `attributes` value: a mapping with string keys. + + Returns a problem at `("attributes",)` if it is not, else `[]`. Shared by the + v2 and v3 validators. Unlike the other `validate_*` functions (which + return value-relative locs for the caller to `_prefix`), this emits the + already-parent-relative `("attributes",)` loc, since it is only ever called + with a document's `attributes` value. + """ + if not isinstance(value, Mapping) or not all( + isinstance(k, str) for k in cast("Mapping[object, object]", value) + ): + return [ + ValidationProblem( + ("attributes",), "expected a mapping with string keys", "invalid_type" + ) + ] + problems: list[ValidationProblem] = [] + for key, item in cast("Mapping[str, object]", value).items(): + problems.extend(_prefix("attributes", _prefix(key, validate_json(item)))) + return problems + + +def validate_array_metadata_v3(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v3 array doc. + + Checks structure, not domain validity. Unknown top-level keys are allowed + (they map to `extra_fields`). + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(ARRAY_METADATA_REQUIRED_KEYS_V3, doc) + problems.extend( + _validate_extension_fields_v3( + cast("Mapping[object, object]", value), ARRAY_METADATA_STANDARD_KEYS_V3 + ) + ) + problems.extend(_check_literal(doc, "zarr_format", 3)) + problems.extend(_check_literal(doc, "node_type", "array")) + problems.extend(_validate_dim_sequence(doc, "shape")) + if "fill_value" in doc: + problems.extend(_prefix("fill_value", validate_json(doc["fill_value"]))) + for key in ("data_type", "chunk_grid", "chunk_key_encoding"): + if key in doc: + problems.extend( + _prefix( + key, + validate_metadata_field_v3(doc[key], allow_must_understand_false=False), + ) + ) + for key in ("codecs", "storage_transformers"): + if key in doc: + entries = doc[key] + if isinstance(entries, str) or not isinstance(entries, Sequence): + problems.append(ValidationProblem((key,), "expected a sequence", "invalid_type")) + else: + if key == "codecs" and len(cast("Sequence[object]", entries)) == 0: + problems.append( + ValidationProblem( + ("codecs",), "expected at least one codec", "invalid_value" + ) + ) + for index, entry in enumerate(cast("Sequence[object]", entries)): + problems.extend(_prefix(key, _prefix(index, validate_metadata_field_v3(entry)))) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + if "dimension_names" in doc: + # Simple typed sequences (dimension_names, shape, chunks) report a single + # field-level loc, not per-bad-item locs; per-index locs are reserved for + # the metadata-field lists (codecs, storage_transformers). + names = doc["dimension_names"] + if isinstance(names, str) or not isinstance(names, Sequence): + problems.append( + ValidationProblem(("dimension_names",), "expected a sequence", "invalid_type") + ) + elif not all( + item is None or isinstance(item, str) for item in cast("Sequence[object]", names) + ): + problems.append( + ValidationProblem( + ("dimension_names",), "expected items of str or None", "invalid_type" + ) + ) + elif _is_int_sequence(doc.get("shape")) and len(cast("Sequence[object]", names)) != len( + cast("Sequence[int]", doc["shape"]) + ): + problems.append( + ValidationProblem( + ("dimension_names",), + "expected one name per dimension of shape", + "invalid_value", + ) + ) + return problems + + +def is_array_metadata_v3(value: object) -> TypeIs[ZarrV3ArrayMetadataJSON]: + """Whether `value` is a structurally-valid v3 array metadata document.""" + return ( + _is_canonical_json(value) + and not validate_array_metadata_v3(value) + and _is_canonical_array_metadata_v3(value) + ) + + +def parse_array_metadata_v3(value: object) -> ZarrV3ArrayMetadataJSON: + """Return `value` as `ZarrV3ArrayMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_array_metadata_v3(normalized) + if problems: + raise MetadataValidationError(problems) + return cast("ZarrV3ArrayMetadataJSON", normalized) + + +def validate_array_metadata_v2(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v2 array doc. + + Checks structure, not domain validity: `dtype` must be a string or field + records, but the string content is not interpreted; `compressor` and + `filters` are required keys that may be `None`, and otherwise must be + codec configurations (mappings with a string `id`). + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(ARRAY_METADATA_REQUIRED_KEYS_V2, doc) + problems.extend( + _unexpected_keys(ARRAY_METADATA_STANDARD_KEYS_V2, cast("Mapping[object, object]", value)) + ) + problems.extend(_check_literal(doc, "zarr_format", 2)) + shape_problems = _validate_dim_sequence(doc, "shape") + chunks_problems = _validate_dim_sequence(doc, "chunks") + problems.extend(shape_problems) + problems.extend(chunks_problems) + if ( + not shape_problems + and not chunks_problems + and _is_int_sequence(doc.get("shape")) + and _is_int_sequence(doc.get("chunks")) + ): + shape = cast("Sequence[int]", doc["shape"]) + chunks = cast("Sequence[int]", doc["chunks"]) + if len(shape) != len(chunks): + problems.append( + ValidationProblem( + ("chunks",), + "expected the same number of dimensions as shape", + "invalid_value", + ) + ) + if "dtype" in doc and not _is_dtype_v2(doc["dtype"]): + problems.append( + ValidationProblem( + ("dtype",), + "expected a v2 dtype string or a sequence of field records", + "invalid_type", + ) + ) + if "order" in doc and doc["order"] not in ("C", "F"): + problems.append( + ValidationProblem( + ("order",), f"expected 'C' or 'F', got {doc['order']!r}", "invalid_value" + ) + ) + if "compressor" in doc: + compressor = doc["compressor"] + if compressor is not None: + problems.extend(_prefix("compressor", _validate_codec_v2(compressor))) + if "filters" in doc: + filters = doc["filters"] + if filters is not None and ( + isinstance(filters, str) + or not isinstance(filters, Sequence) + or not all(_is_codec_v2(item) for item in cast("Sequence[object]", filters)) + ): + problems.append( + ValidationProblem( + ("filters",), + "expected null or a sequence of codec configurations with string 'id's", + "invalid_type", + ) + ) + elif filters is not None: + if len(cast("Sequence[object]", filters)) == 0: + problems.append( + ValidationProblem(("filters",), "expected at least one filter", "invalid_value") + ) + for index, item in enumerate(cast("Sequence[object]", filters)): + problems.extend(_prefix("filters", _prefix(index, validate_json(item)))) + if "dimension_separator" in doc and doc["dimension_separator"] not in (".", "/"): + problems.append( + ValidationProblem( + ("dimension_separator",), + f"expected '.' or '/', got {doc['dimension_separator']!r}", + "invalid_value", + ) + ) + if "fill_value" in doc: + problems.extend(_prefix("fill_value", validate_json(doc["fill_value"]))) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + return problems + + +def is_array_metadata_v2(value: object) -> TypeIs[ZarrV2ArrayMetadataJSON]: + """Whether `value` is a structurally-valid v2 array metadata document.""" + return ( + _is_canonical_json(value) + and not validate_array_metadata_v2(value) + and _is_canonical_array_metadata_v2(value) + ) + + +def parse_array_metadata_v2(value: object) -> ZarrV2ArrayMetadataJSON: + """Return `value` as `ZarrV2ArrayMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_array_metadata_v2(normalized) + if problems: + raise MetadataValidationError(problems) + return cast("ZarrV2ArrayMetadataJSON", normalized) + + +def validate_consolidated_metadata_v3(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a valid inline consolidated envelope. + + Locs are value-relative (the caller prefixes with `consolidated_metadata` + where appropriate). Entries recurse into the array and group document + validators, so a validator verdict always agrees with what + `ZarrV3ConsolidatedMetadata.from_json` accepts. + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + env = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = [ + ValidationProblem((key,), "missing required key", "missing_key") + for key in ("kind", "must_understand", "metadata") + if key not in env + ] + problems.extend( + _unexpected_keys( + frozenset({"kind", "must_understand", "metadata"}), + cast("Mapping[object, object]", value), + ) + ) + problems.extend(_check_literal(env, "kind", "inline")) + if "must_understand" in env and env["must_understand"] is not False: + problems.append(ValidationProblem(("must_understand",), "expected False", "invalid_value")) + if "metadata" in env: + entries = env["metadata"] + if not isinstance(entries, Mapping): + problems.append(ValidationProblem(("metadata",), "expected a mapping", "invalid_type")) + else: + for key, entry in cast("Mapping[object, object]", entries).items(): + if not isinstance(key, str): + problems.append( + ValidationProblem(("metadata",), f"non-string key {key!r}", "invalid_type") + ) + continue + entry_obj: object = entry + node_type: object = None + if isinstance(entry, Mapping): + node_type = cast("Mapping[str, object]", entry).get("node_type") + if node_type == "array": + problems.extend( + _prefix("metadata", _prefix(key, validate_array_metadata_v3(entry_obj))) + ) + elif node_type == "group": + problems.extend( + _prefix("metadata", _prefix(key, validate_group_metadata_v3(entry_obj))) + ) + else: + problems.append( + ValidationProblem( + ("metadata", key, "node_type"), + "expected 'array' or 'group'", + "invalid_value", + ) + ) + return problems + + +def validate_group_metadata_v3(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v3 group doc. + + Checks structure, not domain validity. Unknown top-level keys are allowed + (they map to `extra_fields`); a `consolidated_metadata` key, if present, + is deep-validated (envelope and entries) via + `validate_consolidated_metadata_v3`. + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(GROUP_METADATA_REQUIRED_KEYS_V3, doc) + problems.extend( + _validate_extension_fields_v3( + cast("Mapping[object, object]", value), + GROUP_METADATA_STANDARD_KEYS_V3, + additional_reserved_keys=frozenset({"consolidated_metadata"}), + ) + ) + problems.extend(_check_literal(doc, "zarr_format", 3)) + problems.extend(_check_literal(doc, "node_type", "group")) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + if "consolidated_metadata" in doc and doc["consolidated_metadata"] is not None: + # consolidated_metadata: null (a historical zarr-python bug) is + # structurally accepted so those stores remain readable, but the model + # repairs it to absence on read and never writes it back. + problems.extend( + _prefix( + "consolidated_metadata", + validate_consolidated_metadata_v3(doc["consolidated_metadata"]), + ) + ) + return problems + + +def is_group_metadata_v3(value: object) -> TypeIs[ZarrV3GroupMetadataJSON]: + """Whether `value` is a structurally-valid v3 group metadata document.""" + return _is_canonical_json(value) and not validate_group_metadata_v3(value) + + +def parse_group_metadata_v3(value: object) -> ZarrV3GroupMetadataJSON: + """Return `value` narrowed to `ZarrV3GroupMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_group_metadata_v3(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(ZarrV3GroupMetadataJSON, normalized) + + +def validate_group_metadata_v2(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v2 group doc. + + Validates the in-memory merged form: the `.zgroup` fields plus an + optional `attributes` mapping folded in from `.zattrs`. + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(GROUP_METADATA_REQUIRED_KEYS_V2, doc) + problems.extend( + _unexpected_keys(GROUP_METADATA_STANDARD_KEYS_V2, cast("Mapping[object, object]", value)) + ) + problems.extend(_check_literal(doc, "zarr_format", 2)) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + return problems + + +def is_group_metadata_v2(value: object) -> TypeIs[ZarrV2GroupMetadataJSON]: + """Whether `value` is a structurally-valid v2 group metadata document.""" + return _is_canonical_json(value) and not validate_group_metadata_v2(value) + + +def parse_group_metadata_v2(value: object) -> ZarrV2GroupMetadataJSON: + """Return `value` narrowed to `ZarrV2GroupMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_group_metadata_v2(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(ZarrV2GroupMetadataJSON, normalized) + + +def _reject_json_constant(constant: str) -> NoReturn: + """Reject the JavaScript constants accepted by Python's JSON decoder.""" + raise ValueError(f"non-standard JSON constant {constant!r}") + + +def load_store_json(mapping: Mapping[str, bytes], key: str) -> Any: + """Decode the JSON document stored at `key` in `mapping`. + + Every ingestion failure surfaces as `MetadataValidationError`: a missing + store key is a `missing_key` problem and undecodable bytes are an + `invalid_json` problem, rather than leaking `KeyError` / + `json.JSONDecodeError` to callers. + """ + if key not in mapping: + raise MetadataValidationError( + [ValidationProblem((key,), "missing store key", "missing_key")] + ) + try: + return json.loads(mapping[key], parse_constant=_reject_json_constant) + except (UnicodeDecodeError, ValueError) as exc: + raise MetadataValidationError( + [ValidationProblem((key,), f"invalid JSON: {exc}", "invalid_json")] + ) from exc + + +def dump_store_json(value: object, *, indent: int | str | None = None) -> bytes: + """Encode a metadata document as strict RFC 8259 JSON bytes.""" + return json.dumps(value, indent=indent, allow_nan=False).encode("utf-8") + + +def arrays_to_tuples(obj: object) -> object: + """Recursively materialize mappings and convert array-like values to tuples.""" + if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes, bytearray)): + sequence = cast("Sequence[object]", obj) + converted_sequence = tuple(arrays_to_tuples(item) for item in sequence) + if isinstance(obj, tuple) and all( + converted is original + for converted, original in zip(converted_sequence, sequence, strict=True) + ): + return cast("tuple[object, ...]", obj) + return converted_sequence + if isinstance(obj, Mapping): + mapping = cast("Mapping[object, object]", obj) + converted: dict[object, object] = { + key: arrays_to_tuples(value) for key, value in mapping.items() + } + if isinstance(obj, dict) and all(converted[key] is value for key, value in mapping.items()): + return cast("object", obj) + return converted + return obj diff --git a/packages/zarr-metadata/src/zarr_metadata/py.typed b/packages/zarr-metadata/src/zarr_metadata/py.typed new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/src/zarr_metadata/pydantic.py b/packages/zarr-metadata/src/zarr_metadata/pydantic.py new file mode 100644 index 0000000000..8584efa570 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/pydantic.py @@ -0,0 +1,176 @@ +"""Optional pydantic (v2) integration: field types over the core models. + +Importing this module requires pydantic; the core package deliberately does +not depend on it, so this module is never imported by `zarr_metadata` itself. + +Each exported name is an `Annotated` field type over the corresponding core +model class — the instances ARE the core classes, so values interoperate +freely with non-pydantic code (equality, isinstance, nesting). Validation +delegates to the library: a raw document routes through `from_json` (the +single source of truth for structural validation and normalization, so +pydantic's field-level coercion can never bypass it), an existing model +instance passes through unchanged, and serialization emits the canonical +document via `to_json`. `MetadataValidationError` subclasses `ValueError`, +so a failed parse surfaces as a pydantic `ValidationError` carrying the +loc-annotated problem messages. + +Usage: + + import zarr_metadata.pydantic as zmp + + class ArrayManifest(BaseModel): + path: str + metadata: zmp.ZarrV3ArrayMetadata + +Static type checkers see each field type as its core model class, so +`manifest.metadata` is a `zarr_metadata.model.ZarrV3ArrayMetadata`. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Annotated, TypeVar + +from pydantic import BeforeValidator, InstanceOf, PlainSerializer + +from zarr_metadata import model as _model +from zarr_metadata._pydantic_schema import ( + ZarrV2ArrayMetadataJSON as _ZarrV2ArrayMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV2ConsolidatedMetadataJSON as _ZarrV2ConsolidatedMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV2GroupMetadataJSON as _ZarrV2GroupMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3ArrayMetadataJSON as _ZarrV3ArrayMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3ConsolidatedMetadataJSON as _ZarrV3ConsolidatedMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3GroupMetadataJSON as _ZarrV3GroupMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3MetadataFieldJSON as _ZarrV3MetadataFieldSchema, +) +from zarr_metadata.v2.array import ZarrV2ArrayMetadataJSON as _ZarrV2ArrayMetadataJSON +from zarr_metadata.v2.consolidated import ( + ZarrV2ConsolidatedMetadataJSON as _ZarrV2ConsolidatedMetadataJSON, +) +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON as _ZarrV2GroupMetadataJSON +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON as _ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON as _ZarrV3ArrayMetadataJSON +from zarr_metadata.v3.consolidated import ( + ZarrV3ConsolidatedMetadataJSON as _ZarrV3ConsolidatedMetadataJSON, +) +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON as _ZarrV3GroupMetadataJSON + +if TYPE_CHECKING: + from collections.abc import Callable + +_M = TypeVar("_M") + + +def _coerce_to(cls: type[_M], parse: Callable[[object], _M]) -> Callable[[object], _M]: + """A validator that passes instances of `cls` through and parses anything else.""" + + def coerce(value: object) -> _M: + if isinstance(value, cls): + return value + return parse(value) + + return coerce + + +ZarrV3ArrayMetadata = Annotated[ + InstanceOf[_model.ZarrV3ArrayMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV3ArrayMetadata, _model.ZarrV3ArrayMetadata.from_json), + json_schema_input_type=_ZarrV3ArrayMetadataSchema, + ), + PlainSerializer(_model.ZarrV3ArrayMetadata.to_json, return_type=_ZarrV3ArrayMetadataJSON), +] +"""Field type for a v3 array metadata document (`zarr.json` content).""" + +ZarrV2ArrayMetadata = Annotated[ + InstanceOf[_model.ZarrV2ArrayMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV2ArrayMetadata, _model.ZarrV2ArrayMetadata.from_json), + json_schema_input_type=_ZarrV2ArrayMetadataSchema, + ), + PlainSerializer(_model.ZarrV2ArrayMetadata.to_json, return_type=_ZarrV2ArrayMetadataJSON), +] +"""Field type for a v2 array metadata document (merged `.zarray` + `.zattrs` form).""" + +ZarrV3GroupMetadata = Annotated[ + InstanceOf[_model.ZarrV3GroupMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV3GroupMetadata, _model.ZarrV3GroupMetadata.from_json), + json_schema_input_type=_ZarrV3GroupMetadataSchema, + ), + PlainSerializer(_model.ZarrV3GroupMetadata.to_json, return_type=_ZarrV3GroupMetadataJSON), +] +"""Field type for a v3 group metadata document (`zarr.json` content).""" + +ZarrV2GroupMetadata = Annotated[ + InstanceOf[_model.ZarrV2GroupMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV2GroupMetadata, _model.ZarrV2GroupMetadata.from_json), + json_schema_input_type=_ZarrV2GroupMetadataSchema, + ), + PlainSerializer(_model.ZarrV2GroupMetadata.to_json, return_type=_ZarrV2GroupMetadataJSON), +] +"""Field type for a v2 group metadata document (merged `.zgroup` + `.zattrs` form).""" + +ZarrV3ConsolidatedMetadata = Annotated[ + InstanceOf[_model.ZarrV3ConsolidatedMetadata], + BeforeValidator( + _coerce_to( + _model.ZarrV3ConsolidatedMetadata, + _model.ZarrV3ConsolidatedMetadata.from_json, + ), + json_schema_input_type=_ZarrV3ConsolidatedMetadataSchema, + ), + PlainSerializer( + _model.ZarrV3ConsolidatedMetadata.to_json, + return_type=_ZarrV3ConsolidatedMetadataJSON, + ), +] +"""Field type for v3 inline consolidated metadata.""" + +ZarrV2ConsolidatedMetadata = Annotated[ + InstanceOf[_model.ZarrV2ConsolidatedMetadata], + BeforeValidator( + _coerce_to( + _model.ZarrV2ConsolidatedMetadata, + _model.ZarrV2ConsolidatedMetadata.from_json, + ), + json_schema_input_type=_ZarrV2ConsolidatedMetadataSchema, + ), + PlainSerializer( + _model.ZarrV2ConsolidatedMetadata.to_json, + return_type=_ZarrV2ConsolidatedMetadataJSON, + ), +] +"""Field type for a v2 `.zmetadata` document.""" + +ZarrV3MetadataField = Annotated[ + InstanceOf[_model.ZarrV3NamedConfig], + BeforeValidator( + _coerce_to(_model.ZarrV3NamedConfig, _model.ZarrV3NamedConfig.from_json), + json_schema_input_type=_ZarrV3MetadataFieldSchema, + ), + PlainSerializer(_model.ZarrV3NamedConfig.to_json, return_type=_ZarrV3MetadataFieldJSON), +] +"""Field type for one normalized v3 metadata extension envelope.""" + +__all__ = [ + "ZarrV2ArrayMetadata", + "ZarrV2ConsolidatedMetadata", + "ZarrV2GroupMetadata", + "ZarrV3ArrayMetadata", + "ZarrV3ConsolidatedMetadata", + "ZarrV3GroupMetadata", + "ZarrV3MetadataField", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v2/__init__.py new file mode 100644 index 0000000000..b9001d168e --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/__init__.py @@ -0,0 +1,26 @@ +"""Zarr v2 metadata types.""" + +from zarr_metadata.v2.array import ( + ZarrV2ArrayDimensionSeparator, + ZarrV2ArrayMetadataJSON, + ZarrV2ArrayOrder, + ZarrV2DataTypeMetadata, + ZarrV2ZArrayJSON, +) +from zarr_metadata.v2.attributes import ZarrV2ZAttrsJSON +from zarr_metadata.v2.codec import ZarrV2CodecMetadata +from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataJSON +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON, ZarrV2ZGroupJSON + +__all__ = [ + "ZarrV2ArrayDimensionSeparator", + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayOrder", + "ZarrV2CodecMetadata", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2DataTypeMetadata", + "ZarrV2GroupMetadataJSON", + "ZarrV2ZArrayJSON", + "ZarrV2ZAttrsJSON", + "ZarrV2ZGroupJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/array.py b/packages/zarr-metadata/src/zarr_metadata/v2/array.py new file mode 100644 index 0000000000..e026e5c655 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/array.py @@ -0,0 +1,170 @@ +"""Zarr v2 array metadata types.""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired + +from typing_extensions import TypeAliasType, TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v2.codec import ZarrV2CodecMetadata + +ZarrV2DataTypeMetadata = TypeAliasType( + "ZarrV2DataTypeMetadata", + str + | tuple[ + tuple[str, "ZarrV2DataTypeMetadata"] + | tuple[str, "ZarrV2DataTypeMetadata", tuple[int, ...]], + ..., + ], +) +"""The v2 dtype representation. + +Either a numpy-style dtype string (e.g. `"/.zarray` for + a v2 array. User attributes live in a sibling `.zattrs` file and are + NOT part of this type; see `ZarrV2ZAttrsJSON`. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + shape: tuple[int, ...] + chunks: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: ZarrV2ArrayOrder + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: NotRequired[ZarrV2ArrayDimensionSeparator] + + +class ZarrV2ArrayMetadataJSON(TypedDict): + """ + Zarr v2 array metadata document, in-memory merged form. + + Models the union of `.zarray` (the spec-defined fields) and `.zattrs` + (user attributes). On disk, attributes live in a sibling `.zattrs` file + and are not part of `.zarray`; this type folds them in as the + `attributes` field so a single TypedDict represents the complete + in-memory state of a v2 array node. Consumers that read or write a + real `.zarray` file should split / merge `attributes` accordingly, + or use `ZarrV2ZArrayJSON` (strict on-disk) plus `ZarrV2ZAttrsJSON` directly. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + shape: tuple[int, ...] + chunks: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: ZarrV2ArrayOrder + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: NotRequired[ZarrV2ArrayDimensionSeparator] + attributes: NotRequired[Mapping[str, JSONValue]] + """User attributes from the sibling `.zattrs` file (not part of `.zarray`). + + See the class docstring for the rationale behind the merged representation. + """ + + +class ZarrV2ArrayMetadataJSONPartial(TypedDict, total=False): + """ + Partial form of `ZarrV2ArrayMetadataJSON`: every field is `NotRequired`. + + Field annotations mirror `ZarrV2ArrayMetadataJSON` exactly. The only difference is + `total=False`, which makes every key optional at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v2 array metadata document — e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. + + The `NotRequired[...]` wrappers on `dimension_separator` and `attributes` + are intentional: keeping them preserves byte-identical `__annotations__` + with `ZarrV2ArrayMetadataJSON` so the `==` check in + `tests/test_partial_equivalence.py` passes without special-casing those + fields (PEP 655 explicitly permits `NotRequired` inside `total=False`). + + Note: v2 array metadata has no `extra_items` setting (the v2 spec has no + extension-field concept), so this partial inherits the same closed shape. + + Drift between this type and `ZarrV2ArrayMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[2] + shape: tuple[int, ...] + chunks: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: ZarrV2ArrayOrder + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: NotRequired[ZarrV2ArrayDimensionSeparator] + attributes: NotRequired[Mapping[str, JSONValue]] + """User attributes from the sibling `.zattrs` file (not part of `.zarray`). + + See the class docstring for the rationale behind the merged representation. + """ + + +ZarrV2ArrayMetadataStoreKey = Literal[".zarray"] +"""Literal type of the store key holding a v2 array's metadata document.""" + +ZARR_V2_ARRAY_METADATA_STORE_KEY: Final[ZarrV2ArrayMetadataStoreKey] = ".zarray" +"""The store key a v2 array's metadata document is persisted under.""" + + +__all__ = [ + "ZARR_V2_ARRAY_DIMENSION_SEPARATOR", + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZARR_V2_ARRAY_ORDER", + "ZarrV2ArrayDimensionSeparator", + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayMetadataJSONPartial", + "ZarrV2ArrayMetadataStoreKey", + "ZarrV2ArrayOrder", + "ZarrV2DataTypeMetadata", + "ZarrV2ZArrayJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/attributes.py b/packages/zarr-metadata/src/zarr_metadata/v2/attributes.py new file mode 100644 index 0000000000..68785d1660 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/attributes.py @@ -0,0 +1,36 @@ +"""Zarr v2 user-attributes file content. + +See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from zarr_metadata._common import JSONValue + +ZarrV2ZAttrsJSON = Mapping[str, JSONValue] +"""On-disk `.zattrs` file content. + +A JSON object holding user-defined attributes for a v2 array or group. +Spec-defined keys for arrays / groups live in sibling `.zarray` / `.zgroup` +files (modeled by `ZarrV2ZArrayJSON` / `ZarrV2ZGroupJSON`). This type does not +constrain the keys or values of the attributes mapping. +""" + + +ZarrV2AttributesStoreKey = Literal[".zattrs"] +"""Literal type of the store key holding a v2 node's user attributes.""" + +ZARR_V2_ATTRIBUTES_STORE_KEY: Final[ZarrV2AttributesStoreKey] = ".zattrs" +"""The store key a v2 node's user attributes are persisted under. + +Shared by arrays and groups: both node types keep their attributes in a +sibling `.zattrs` file. +""" + + +__all__ = [ + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZarrV2AttributesStoreKey", + "ZarrV2ZAttrsJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/codec.py b/packages/zarr-metadata/src/zarr_metadata/v2/codec.py new file mode 100644 index 0000000000..69125544e6 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/codec.py @@ -0,0 +1,29 @@ +""" +Zarr v2 codec configuration shape. + +In v2, compressors and filters are numcodecs configuration dicts: a required +`id` field naming the codec, plus arbitrary codec-specific extra fields. +""" + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue + + +class ZarrV2CodecMetadata(TypedDict, extra_items=JSONValue): + """ + A numcodecs configuration dict, used as a v2 compressor or filter. + + The required `id` field names the codec; codec-specific parameters + (e.g. `cname`, `clevel` for blosc) appear as extra fields. + + See the "compressor" and "filters" sections of + https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + id: str + + +__all__ = [ + "ZarrV2CodecMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v2/consolidated.py new file mode 100644 index 0000000000..999c9131da --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/consolidated.py @@ -0,0 +1,56 @@ +"""Zarr v2 consolidated metadata (`.zmetadata` file). + +This module models the de-facto `.zmetadata` file used by the reference +Python implementation of Zarr v2. **This is NOT a spec artifact.** There +is no Zarr v2 specification that defines `.zmetadata`; it is a +canonical-implementation convention. +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from typing_extensions import TypedDict + +from zarr_metadata.v2.array import ZarrV2ZArrayJSON +from zarr_metadata.v2.attributes import ZarrV2ZAttrsJSON +from zarr_metadata.v2.group import ZarrV2ZGroupJSON + + +class ZarrV2ConsolidatedMetadataJSON(TypedDict): + """ + `.zmetadata` file contents. + + The `metadata` map uses flat path keys (`"foo/bar/.zarray"`, + `"foo/.zattrs"`, etc.) pointing to the JSON contents of the file at + that path. The keys include the filename suffix, not just the node + path; the value's shape is determined by which file the key points at: + + - `/.zarray` -> `ZarrV2ZArrayJSON` + - `/.zgroup` -> `ZarrV2ZGroupJSON` + - `/.zattrs` -> `ZarrV2ZAttrsJSON` + + The TypedDict cannot discriminate the value shape on the key suffix + at the type level; consumers should narrow at runtime by inspecting + `key.endswith(".zarray")` etc. + """ + + zarr_consolidated_format: int + metadata: Mapping[str, ZarrV2ZArrayJSON | ZarrV2ZGroupJSON | ZarrV2ZAttrsJSON] + + +ZarrV2ConsolidatedMetadataStoreKey = Literal[".zmetadata"] +"""Literal type of the store key holding a v2 hierarchy's consolidated metadata.""" + +ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY: Final[ZarrV2ConsolidatedMetadataStoreKey] = ".zmetadata" +"""The store key a v2 hierarchy's consolidated metadata is persisted under. + +Like the document it names, this is a reference-implementation convention +rather than a spec artifact; see the module docstring. +""" + + +__all__ = [ + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2ConsolidatedMetadataStoreKey", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/group.py b/packages/zarr-metadata/src/zarr_metadata/v2/group.py new file mode 100644 index 0000000000..34d72742c2 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/group.py @@ -0,0 +1,90 @@ +"""Zarr v2 group metadata types. + +See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html +""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue + + +class ZarrV2ZGroupJSON(TypedDict): + """ + On-disk `.zgroup` file content. + + Strict shape of the JSON document persisted at `/.zgroup` for + a v2 group. The spec defines exactly one field. User attributes live + in a sibling `.zattrs` file and are NOT part of this type; see + `ZarrV2ZAttrsJSON`. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + + +class ZarrV2GroupMetadataJSON(TypedDict): + """ + Zarr v2 group metadata document, in-memory merged form. + + Models the union of `.zgroup` (the spec-defined `zarr_format` field) + and `.zattrs` (user attributes). On disk these are persisted as two + separate files; this type folds them so a single TypedDict represents + the complete in-memory state of a v2 group node. Consumers that read + or write the real on-disk files should use `ZarrV2ZGroupJSON` (strict + `.zgroup`) plus `ZarrV2ZAttrsJSON` directly. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV2GroupMetadataJSONPartial(TypedDict, total=False): + """ + Partial form of `ZarrV2GroupMetadataJSON`: every field is `NotRequired`. + + Field annotations mirror `ZarrV2GroupMetadataJSON` exactly. The only difference is + `total=False`, which makes every key optional at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v2 group metadata document — e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. Provided for symmetry with the other + `*Partial` types; the practical effect is that `zarr_format` becomes optional. + + The `NotRequired[...]` wrapper on `attributes` is intentional: keeping it + preserves byte-identical `__annotations__` with `ZarrV2GroupMetadataJSON` so the + `==` check in `tests/test_partial_equivalence.py` passes without + special-casing that field (PEP 655 explicitly permits `NotRequired` inside + `total=False`). + + Note: v2 group metadata has no `extra_items` setting (the v2 spec has no + extension-field concept), so this partial inherits the same closed shape. + + Drift between this type and `ZarrV2GroupMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[2] + attributes: NotRequired[Mapping[str, JSONValue]] + + +ZarrV2GroupMetadataStoreKey = Literal[".zgroup"] +"""Literal type of the store key holding a v2 group's metadata document.""" + +ZARR_V2_GROUP_METADATA_STORE_KEY: Final[ZarrV2GroupMetadataStoreKey] = ".zgroup" +"""The store key a v2 group's metadata document is persisted under.""" + + +__all__ = [ + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZarrV2GroupMetadataJSON", + "ZarrV2GroupMetadataJSONPartial", + "ZarrV2GroupMetadataStoreKey", + "ZarrV2ZGroupJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py new file mode 100644 index 0000000000..4e335f9573 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py @@ -0,0 +1,14 @@ +"""Zarr v3 metadata types.""" + +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON, ZarrV3ExtensionField +from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + +__all__ = [ + "ZarrV3ArrayMetadataJSON", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3ExtensionField", + "ZarrV3GroupMetadataJSON", + "ZarrV3MetadataFieldJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py new file mode 100644 index 0000000000..406b76b723 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py @@ -0,0 +1,23 @@ +"""Internal cross-cutting aliases for Zarr v3 metadata. + +This module is private (underscore-prefixed) and exists to avoid circular +imports between leaf modules and sub-package `__init__.py` re-exports. +Public consumers should import `ZarrV3MetadataFieldJSON` from `zarr_metadata.v3`. +""" + +from zarr_metadata._common import ZarrV3NamedConfigJSON + +ZarrV3MetadataFieldJSON = str | ZarrV3NamedConfigJSON +"""The JSON shape of any v3 metadata extension-point entry: either a bare +short-hand name string or a `{name, configuration, must_understand}` envelope. + +Used for `data_type`, `chunk_grid`, `chunk_key_encoding`, individual +codec entries, and `storage_transformers` in v3 array metadata, and for +the inner `codecs` / `index_codecs` lists of the `sharding_indexed` +codec. +""" + + +__all__ = [ + "ZarrV3MetadataFieldJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/array.py b/packages/zarr-metadata/src/zarr_metadata/v3/array.py new file mode 100644 index 0000000000..31a5f6b755 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/array.py @@ -0,0 +1,95 @@ +"""Zarr v3 array metadata types.""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired, TypeAlias + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +ZarrV3ExtensionField: TypeAlias = JSONValue +"""The JSON value of an unknown top-level v3 metadata field. + +An object carrying the literal member `must_understand: false` may be ignored. +Every other JSON shape implicitly requires understanding; recognition itself +belongs to the reader rather than this structural type. +""" + + +class ZarrV3ArrayMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): + """ + Zarr v3 array metadata document (the `zarr.json` content for an array). + + Extra keys may contain arbitrary JSON values. + + See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#array-metadata + """ + + zarr_format: Literal[3] + node_type: Literal["array"] + data_type: ZarrV3MetadataFieldJSON + shape: tuple[int, ...] + chunk_grid: ZarrV3MetadataFieldJSON + chunk_key_encoding: ZarrV3MetadataFieldJSON + fill_value: JSONValue + codecs: tuple[ZarrV3MetadataFieldJSON, ...] + attributes: NotRequired[Mapping[str, JSONValue]] + storage_transformers: NotRequired[tuple[ZarrV3MetadataFieldJSON, ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +class ZarrV3ArrayMetadataJSONPartial(TypedDict, total=False, extra_items=ZarrV3ExtensionField): + """ + Partial form of `ZarrV3ArrayMetadataJSON`: every field is `NotRequired`. + + Field annotations and `extra_items=` mirror `ZarrV3ArrayMetadataJSON` exactly. + The only difference is `total=False`, which makes every key optional + at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v3 array metadata document — e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. + + The `NotRequired[...]` wrappers on `attributes`, `storage_transformers`, + and `dimension_names` are intentional: keeping them preserves byte-identical + `__annotations__` with `ZarrV3ArrayMetadataJSON` so the `==` check in + `tests/test_partial_equivalence.py` passes without special-casing those + fields (PEP 655 explicitly permits `NotRequired` inside `total=False`). + + Drift between this type and `ZarrV3ArrayMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[3] + node_type: Literal["array"] + data_type: ZarrV3MetadataFieldJSON + shape: tuple[int, ...] + chunk_grid: ZarrV3MetadataFieldJSON + chunk_key_encoding: ZarrV3MetadataFieldJSON + fill_value: JSONValue + codecs: tuple[ZarrV3MetadataFieldJSON, ...] + attributes: NotRequired[Mapping[str, JSONValue]] + storage_transformers: NotRequired[tuple[ZarrV3MetadataFieldJSON, ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +ZarrV3ArrayMetadataStoreKey = Literal["zarr.json"] +"""Literal type of the store key holding a v3 array's metadata document.""" + +ZARR_V3_ARRAY_METADATA_STORE_KEY: Final[ZarrV3ArrayMetadataStoreKey] = "zarr.json" +"""The store key a v3 array's metadata document is persisted under. + +v3 uses one key for both node types; the document's `node_type` field +distinguishes an array from a group. +""" + + +__all__ = [ + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ArrayMetadataJSONPartial", + "ZarrV3ArrayMetadataStoreKey", + "ZarrV3ExtensionField", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/__init__.py new file mode 100644 index 0000000000..22b3ab52be --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/__init__.py @@ -0,0 +1,23 @@ +""" +Zarr v3 chunk grid metadata types. + +Each chunk grid lives in its own submodule: + +- `regular` -- core v3 spec +- `rectilinear` -- zarr-extensions + +The `ChunkGridMetadata` aliases re-exported here are the canonical type +for each grid's permitted JSON shapes. For the underlying +`ChunkGridObject`, `ChunkGridConfiguration`, etc., import directly +from the leaf submodule. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-grids +""" + +from zarr_metadata.v3.chunk_grid.rectilinear import RectilinearChunkGridMetadata +from zarr_metadata.v3.chunk_grid.regular import RegularChunkGridMetadata + +__all__ = [ + "RectilinearChunkGridMetadata", + "RegularChunkGridMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py new file mode 100644 index 0000000000..e3551e3c72 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py @@ -0,0 +1,54 @@ +""" +Rectilinear chunk grid (zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +RECTILINEAR_CHUNK_GRID_NAME: Final = "rectilinear" +"""The `name` field value of the rectilinear chunk grid.""" + +RectilinearChunkGridName = Literal["rectilinear"] +"""Literal type of the `name` field of the rectilinear chunk grid.""" + +RectilinearDimSpec = int | tuple[int | tuple[int, int], ...] +"""JSON shape for one dimension's rectilinear spec. + +Either a bare integer (uniform shorthand for a regular dimension within +a rectilinear grid), or a tuple of integers and/or `[value, count]` RLE +pairs. +""" + + +class RectilinearChunkGridConfiguration(TypedDict): + """Configuration for the rectilinear chunk grid.""" + + kind: Literal["inline"] + chunk_shapes: tuple[RectilinearDimSpec, ...] + + +class RectilinearChunkGridObject(TypedDict): + """Rectilinear chunk grid metadata in object form.""" + + name: RectilinearChunkGridName + configuration: RectilinearChunkGridConfiguration + + +RectilinearChunkGridMetadata = RectilinearChunkGridObject +"""Permitted JSON shape for rectilinear chunk grid metadata. + +`kind` and `chunk_shapes` are required, so only the object form is valid; +the short-hand-name form is not permitted by the spec for this grid. +""" + +__all__ = [ + "RECTILINEAR_CHUNK_GRID_NAME", + "RectilinearChunkGridConfiguration", + "RectilinearChunkGridMetadata", + "RectilinearChunkGridName", + "RectilinearChunkGridObject", + "RectilinearDimSpec", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py new file mode 100644 index 0000000000..2f7a089934 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py @@ -0,0 +1,44 @@ +""" +Regular chunk grid (Zarr v3 core spec). + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#regular-grids +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +REGULAR_CHUNK_GRID_NAME: Final = "regular" +"""The `name` field value of the regular chunk grid.""" + +RegularChunkGridName = Literal["regular"] +"""Literal type of the `name` field of the regular chunk grid.""" + + +class RegularChunkGridConfiguration(TypedDict): + """Configuration for the regular chunk grid.""" + + chunk_shape: tuple[int, ...] + + +class RegularChunkGridObject(TypedDict): + """Regular chunk grid metadata in object form.""" + + name: RegularChunkGridName + configuration: RegularChunkGridConfiguration + + +RegularChunkGridMetadata = RegularChunkGridObject +"""Permitted JSON shape for regular chunk grid metadata. + +`chunk_shape` is required and has no default, so only the object form is +valid; the short-hand-name form is not permitted by the spec for this grid. +""" + +__all__ = [ + "REGULAR_CHUNK_GRID_NAME", + "RegularChunkGridConfiguration", + "RegularChunkGridMetadata", + "RegularChunkGridName", + "RegularChunkGridObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/__init__.py new file mode 100644 index 0000000000..b6774efbe3 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/__init__.py @@ -0,0 +1,25 @@ +""" +Zarr v3 chunk key encoding metadata types. + +Each chunk key encoding lives in its own submodule: + +- `default` -- v3 default encoding (`/`-separated) +- `v2` -- v2-compatibility encoding (`.`-separated by default) + +Both are defined by the v3 core spec. + +The `ChunkKeyEncodingMetadata` aliases re-exported here are the canonical +type for each encoding's permitted JSON shapes. For the underlying +`ChunkKeyEncodingObject`, `ChunkKeyEncodingConfiguration`, etc., import +directly from the leaf submodule. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding +""" + +from zarr_metadata.v3.chunk_key_encoding.default import DefaultChunkKeyEncodingMetadata +from zarr_metadata.v3.chunk_key_encoding.v2 import V2ChunkKeyEncodingMetadata + +__all__ = [ + "DefaultChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py new file mode 100644 index 0000000000..c783861b34 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py @@ -0,0 +1,61 @@ +""" +Default chunk key encoding (Zarr v3 core spec). + +The chunk key for a chunk with grid index `(k, j, i, ...)` is formed +by appending `ckji...` (where `` is `separator`). + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +DEFAULT_CHUNK_KEY_ENCODING_NAME: Final = "default" +"""The `name` field value of the default chunk key encoding.""" + +DefaultChunkKeyEncodingName = Literal["default"] +"""Literal type of the `name` field of the default chunk key encoding.""" + +DefaultChunkKeyEncodingSeparator = Literal["/", "."] +"""Literal type of permitted `separator` values for the default chunk key encoding. + +Defaults to `"/"` if absent. +""" + +DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR: Final = ("/", ".") +"""Tuple of permitted values for the `separator` field of the default chunk key encoding.""" + + +class DefaultChunkKeyEncodingConfiguration(TypedDict): + """Configuration for the default chunk key encoding. + + `separator` is optional and defaults to `"/"` per spec. + """ + + separator: NotRequired[DefaultChunkKeyEncodingSeparator] + + +class DefaultChunkKeyEncodingObject(TypedDict): + """Default chunk key encoding metadata in object form.""" + + name: DefaultChunkKeyEncodingName + configuration: NotRequired[DefaultChunkKeyEncodingConfiguration] + + +DefaultChunkKeyEncodingMetadata = DefaultChunkKeyEncodingObject | DefaultChunkKeyEncodingName +"""Permitted JSON shapes for the default chunk-key encoding metadata. + +The configuration has no required keys (`separator` defaults to `"/"`), +so the short-hand-name form is permitted in addition to the object form. +""" + +__all__ = [ + "DEFAULT_CHUNK_KEY_ENCODING_NAME", + "DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR", + "DefaultChunkKeyEncodingConfiguration", + "DefaultChunkKeyEncodingMetadata", + "DefaultChunkKeyEncodingName", + "DefaultChunkKeyEncodingObject", + "DefaultChunkKeyEncodingSeparator", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py new file mode 100644 index 0000000000..e2783d296d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py @@ -0,0 +1,67 @@ +""" +v2-compatibility chunk key encoding (Zarr v3 core spec). + +Intended only to allow existing v2 arrays to be converted to v3 without +having to rename chunks. Not recommended for new arrays. + +Naming note: these are Zarr **v3** types. The leading `V2` in +`V2ChunkKeyEncodingMetadata` (and friends) is the encoding's registered +*entity name* (`"v2"`), not the format-version marker that `ZarrV2...` +names carry — this package's version-prefixed names always spell it +`ZarrV2` / `ZarrV3`. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +V2_CHUNK_KEY_ENCODING_NAME: Final = "v2" +"""The `name` field value of the v2 chunk key encoding.""" + +V2ChunkKeyEncodingName = Literal["v2"] +"""Literal type of the `name` field of the v2 chunk key encoding.""" + +V2ChunkKeyEncodingSeparator = Literal["/", "."] +"""Literal type of permitted `separator` values for the v2 chunk key encoding. + +Defaults to `"."` if absent. +""" + +V2_CHUNK_KEY_ENCODING_SEPARATOR: Final = ("/", ".") +"""Tuple of permitted values for the `separator` field of the v2 chunk key encoding.""" + + +class V2ChunkKeyEncodingConfiguration(TypedDict): + """Configuration for the v2 chunk key encoding. + + `separator` is optional and defaults to `"."` per spec. + """ + + separator: NotRequired[V2ChunkKeyEncodingSeparator] + + +class V2ChunkKeyEncodingObject(TypedDict): + """v2-compatibility chunk key encoding metadata in object form.""" + + name: V2ChunkKeyEncodingName + configuration: NotRequired[V2ChunkKeyEncodingConfiguration] + + +V2ChunkKeyEncodingMetadata = V2ChunkKeyEncodingObject | V2ChunkKeyEncodingName +"""Permitted JSON shapes for the v2-compatibility chunk-key encoding metadata. + +The configuration has no required keys (`separator` defaults to `"."`), +so the short-hand-name form is permitted in addition to the object form. +""" + +__all__ = [ + "V2_CHUNK_KEY_ENCODING_NAME", + "V2_CHUNK_KEY_ENCODING_SEPARATOR", + "V2ChunkKeyEncodingConfiguration", + "V2ChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingName", + "V2ChunkKeyEncodingObject", + "V2ChunkKeyEncodingSeparator", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/__init__.py new file mode 100644 index 0000000000..c8a9a150fc --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/__init__.py @@ -0,0 +1,40 @@ +""" +Zarr v3 codec spec types. + +Each codec defined by the spec or by zarr-extensions has its own submodule +(`blosc`, `bytes`, `cast_value`, `crc32c`, `gzip`, `scale_offset`, +`sharding_indexed`, `transpose`, `zstd`). + +The `CodecMetadata` aliases re-exported here are the canonical type for +each codec's permitted JSON shapes (object form plus, where the spec allows, +a bare-string short-hand form). For the underlying `CodecObject`, +`CodecConfiguration`, etc., import directly from the leaf submodule. + +For the field-level "any codec entry" alias (used in array metadata's +`codecs` list and in sharding's inner pipelines), import `ZarrV3MetadataFieldJSON` +from `zarr_metadata.v3`. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/index.html +""" + +from zarr_metadata.v3.codec.blosc import BloscCodecMetadata +from zarr_metadata.v3.codec.bytes import BytesCodecMetadata +from zarr_metadata.v3.codec.cast_value import CastValueCodecMetadata +from zarr_metadata.v3.codec.crc32c import Crc32cCodecMetadata +from zarr_metadata.v3.codec.gzip import GzipCodecMetadata +from zarr_metadata.v3.codec.scale_offset import ScaleOffsetCodecMetadata +from zarr_metadata.v3.codec.sharding_indexed import ShardingIndexedCodecMetadata +from zarr_metadata.v3.codec.transpose import TransposeCodecMetadata +from zarr_metadata.v3.codec.zstd import ZstdCodecMetadata + +__all__ = [ + "BloscCodecMetadata", + "BytesCodecMetadata", + "CastValueCodecMetadata", + "Crc32cCodecMetadata", + "GzipCodecMetadata", + "ScaleOffsetCodecMetadata", + "ShardingIndexedCodecMetadata", + "TransposeCodecMetadata", + "ZstdCodecMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/blosc.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/blosc.py new file mode 100644 index 0000000000..5a986c8260 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/blosc.py @@ -0,0 +1,65 @@ +""" +Blosc codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/blosc/index.html +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +BLOSC_CODEC_NAME: Final = "blosc" +"""The `name` field value of the `blosc` codec.""" + +BloscCodecName = Literal["blosc"] +"""Literal type of the `name` field of the `blosc` codec.""" + +BloscShuffle = Literal["noshuffle", "shuffle", "bitshuffle"] +"""Literal type of blosc shuffle mode names.""" + +BLOSC_SHUFFLE: Final = ("noshuffle", "shuffle", "bitshuffle") +"""Tuple of permitted values for the `shuffle` field of the `blosc` codec.""" + +BloscCName = Literal["lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd"] +"""Literal type of blosc compressor identifiers.""" + +BLOSC_CNAME: Final = ("lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd") +"""Tuple of permitted values for the `cname` field of the `blosc` codec.""" + + +class BloscCodecConfiguration(TypedDict): + """Configuration for the Zarr v3 `blosc` codec.""" + + cname: BloscCName + clevel: int + shuffle: BloscShuffle + blocksize: int + typesize: NotRequired[int] + + +class BloscCodecObject(TypedDict): + """`blosc` codec metadata in object form.""" + + name: BloscCodecName + configuration: BloscCodecConfiguration + + +BloscCodecMetadata = BloscCodecObject +"""Permitted JSON shape for `blosc` codec metadata. + +The configuration has multiple required keys (`cname`, `clevel`, `shuffle`, +`blocksize`), so only the object form is valid; the short-hand-name form +is not permitted by the spec for this codec. +""" + +__all__ = [ + "BLOSC_CNAME", + "BLOSC_CODEC_NAME", + "BLOSC_SHUFFLE", + "BloscCName", + "BloscCodecConfiguration", + "BloscCodecMetadata", + "BloscCodecName", + "BloscCodecObject", + "BloscShuffle", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/bytes.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/bytes.py new file mode 100644 index 0000000000..04e746f898 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/bytes.py @@ -0,0 +1,64 @@ +""" +Bytes codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/bytes/index.html +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +BYTES_CODEC_NAME: Final = "bytes" +"""The `name` field value of the `bytes` codec.""" + +BytesCodecName = Literal["bytes"] +"""Literal type of the `name` field of the `bytes` codec.""" + +Endianness = Literal["little", "big"] +"""Literal type of byte order of multi-byte numeric data.""" + +ENDIANNESS: Final = ("little", "big") +"""Tuple of permitted values for the `endian` field of the `bytes` codec.""" + + +class BytesCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `bytes` codec. + + The `endian` field is required for multi-byte data types. + """ + + endian: NotRequired[Endianness] + + +class BytesCodecObject(TypedDict): + """`bytes` codec metadata in object form. + + `configuration` is itself optional — when no configuration fields are + set, the entire `configuration` key may be omitted. This matches the + bare-string short-hand form (`BytesCodecName`) at the canonical data + level; both encodings describe a `bytes` codec with default settings. + """ + + name: BytesCodecName + configuration: NotRequired[BytesCodecConfiguration] + + +BytesCodecMetadata = BytesCodecObject | BytesCodecName +"""Permitted JSON shapes for `bytes` codec metadata. + +The configuration has no required keys (`endian` is conditionally required +at runtime based on data type), so the spec's short-hand-name form is +permitted in addition to the object form, and the object form may itself +omit `configuration` entirely. +""" + +__all__ = [ + "BYTES_CODEC_NAME", + "ENDIANNESS", + "BytesCodecConfiguration", + "BytesCodecMetadata", + "BytesCodecName", + "BytesCodecObject", + "Endianness", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py new file mode 100644 index 0000000000..96c39e5916 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py @@ -0,0 +1,107 @@ +""" +Cast-value codec types. + +See https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/cast_value +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +CAST_VALUE_CODEC_NAME: Final = "cast_value" +"""The `name` field value of the `cast_value` codec.""" + +CastValueCodecName = Literal["cast_value"] +"""Literal type of the `name` field of the `cast_value` codec.""" + +CastRoundingMode = Literal[ + "nearest-even", + "towards-zero", + "towards-positive", + "towards-negative", + "nearest-away", +] +"""Literal type of permitted values for the `rounding` configuration field. + +Defaults to `"nearest-even"` if absent. +""" + +CAST_ROUNDING_MODE: Final = ( + "nearest-even", + "towards-zero", + "towards-positive", + "towards-negative", + "nearest-away", +) +"""Tuple of permitted values for the `rounding` field of the `cast_value` codec.""" + +CastOutOfRangeMode = Literal["clamp", "wrap"] +"""Literal type of permitted values for the `out_of_range` configuration field. + +If absent, out-of-range values are an encoding/decoding error. +""" + +CAST_OUT_OF_RANGE_MODE: Final = ("clamp", "wrap") +"""Tuple of permitted values for the `out_of_range` field of the `cast_value` codec.""" + +ScalarMapEntry = tuple[JSONValue, JSONValue] +"""A single `[input, output]` mapping in a `scalar_map` direction. + +Each scalar is JSON-encoded per its data type's fill-value rules (so +e.g. `"NaN"` and `"+Infinity"` are permitted). +""" + + +class ScalarMap(TypedDict): + """Optional encode/decode scalar overrides for the cast_value codec.""" + + encode: NotRequired[tuple[ScalarMapEntry, ...]] + decode: NotRequired[tuple[ScalarMapEntry, ...]] + + +class CastValueCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `cast_value` codec. + + `data_type` is the target data type that input values are cast to. It + is the same shape as the top-level array `data_type` field: either a + bare-string primitive name or a `{name, configuration}` envelope. + """ + + data_type: ZarrV3MetadataFieldJSON + rounding: NotRequired[CastRoundingMode] + out_of_range: NotRequired[CastOutOfRangeMode] + scalar_map: NotRequired[ScalarMap] + + +class CastValueCodecObject(TypedDict): + """`cast_value` codec metadata in object form.""" + + name: CastValueCodecName + configuration: CastValueCodecConfiguration + + +CastValueCodecMetadata = CastValueCodecObject +"""Permitted JSON shape for `cast_value` codec metadata. + +`configuration.data_type` is required, so only the object form is valid; +the short-hand-name form is not permitted by the spec for this codec. +""" + + +__all__ = [ + "CAST_OUT_OF_RANGE_MODE", + "CAST_ROUNDING_MODE", + "CAST_VALUE_CODEC_NAME", + "CastOutOfRangeMode", + "CastRoundingMode", + "CastValueCodecConfiguration", + "CastValueCodecMetadata", + "CastValueCodecName", + "CastValueCodecObject", + "ScalarMap", + "ScalarMapEntry", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/crc32c.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/crc32c.py new file mode 100644 index 0000000000..6b9b46c43d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/crc32c.py @@ -0,0 +1,50 @@ +""" +CRC32C codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/crc32c/index.html + +The CRC32C codec has no configuration fields, so the `configuration` +key is absent from the metadata. +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +CRC32C_CODEC_NAME: Final = "crc32c" +"""The `name` field value of the `crc32c` codec.""" + +Crc32cCodecName = Literal["crc32c"] +"""Literal type of the `name` field of the `crc32c` codec.""" + + +class Empty(TypedDict, closed=True): + """An empty mapping""" + + +class Crc32cCodecObject(TypedDict): + """`crc32c` codec metadata in object form. + + Per spec the codec has no configuration fields. `configuration` is + optional and, if present, should be an empty mapping. + """ + + name: Crc32cCodecName + configuration: NotRequired[Empty] + + +Crc32cCodecMetadata = Crc32cCodecObject | Crc32cCodecName +"""Permitted JSON shapes for `crc32c` codec metadata. + +The spec's Extension definition allows extensions with no required +configuration to be encoded as a bare short-hand name. CRC32C has no +configuration, so both forms are valid. +""" + + +__all__ = [ + "CRC32C_CODEC_NAME", + "Crc32cCodecMetadata", + "Crc32cCodecName", + "Crc32cCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/gzip.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/gzip.py new file mode 100644 index 0000000000..3b9936f8cd --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/gzip.py @@ -0,0 +1,55 @@ +""" +Gzip codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/gzip/index.html +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +GZIP_CODEC_NAME: Final = "gzip" +"""The `name` field value of the `gzip` codec.""" + +GzipCodecName = Literal["gzip"] +"""Literal type of the `name` field of the `gzip` codec.""" + + +class GzipCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `gzip` codec. + + `level` is an integer in the range 0-9; 0 disables compression and 9 + is slowest with the best compression ratio. The codec's compressed + output depends on `level`, so metadata that omits it cannot + reproducibly identify the chunk bytes produced by a writer — `level` + is required for the metadata to fulfill its reproducibility role, + even though the spec text does not mark it required with RFC 2119 + keywords. + """ + + level: int + + +class GzipCodecObject(TypedDict): + """`gzip` codec metadata in object form.""" + + name: GzipCodecName + configuration: GzipCodecConfiguration + + +GzipCodecMetadata = GzipCodecObject +"""Permitted JSON shape for `gzip` codec metadata. + +`configuration.level` is required (it determines the codec's output bytes +and is therefore part of the metadata's reproducibility contract), so +only the object form is valid; the short-hand-name form is not permitted. +""" + +__all__ = [ + "GZIP_CODEC_NAME", + "GzipCodecConfiguration", + "GzipCodecMetadata", + "GzipCodecName", + "GzipCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/scale_offset.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/scale_offset.py new file mode 100644 index 0000000000..9701db8497 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/scale_offset.py @@ -0,0 +1,61 @@ +""" +Scale-offset codec types. + +See https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/scale_offset +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue + +SCALE_OFFSET_CODEC_NAME: Final = "scale_offset" +"""The `name` field value of the `scale_offset` codec.""" + +ScaleOffsetCodecName = Literal["scale_offset"] +"""Literal type of the `name` field of the `scale_offset` codec.""" + + +class ScaleOffsetCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `scale_offset` codec. + + Both fields are optional. A missing `offset` is the additive identity + (e.g. 0 for numeric types); a missing `scale` is the multiplicative + identity (e.g. 1). Each scalar is JSON-encoded per the input array's + fill-value rules, so `"NaN"` and `"+Infinity"` style strings are + permitted in addition to numbers. + """ + + offset: NotRequired[JSONValue] + scale: NotRequired[JSONValue] + + +class ScaleOffsetCodecObject(TypedDict): + """`scale_offset` codec metadata in object form. + + `configuration` is itself optional per spec — when both `offset` and + `scale` are at their identity defaults, the codec is a no-op and the + entire `configuration` field may be omitted. + """ + + name: ScaleOffsetCodecName + configuration: NotRequired[ScaleOffsetCodecConfiguration] + + +ScaleOffsetCodecMetadata = ScaleOffsetCodecObject | ScaleOffsetCodecName +"""Permitted JSON shapes for `scale_offset` codec metadata. + +The configuration has no required keys (both `offset` and `scale` are +optional, and the configuration itself is optional), so the short-hand-name +form is permitted in addition to the object form. +""" + +__all__ = [ + "SCALE_OFFSET_CODEC_NAME", + "ScaleOffsetCodecConfiguration", + "ScaleOffsetCodecMetadata", + "ScaleOffsetCodecName", + "ScaleOffsetCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py new file mode 100644 index 0000000000..a8c9247ec4 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py @@ -0,0 +1,71 @@ +""" +Sharding-indexed codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/sharding-indexed/index.html +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +SHARDING_INDEXED_CODEC_NAME: Final = "sharding_indexed" +"""The `name` field value of the `sharding_indexed` codec.""" + +ShardingIndexedCodecName = Literal["sharding_indexed"] +"""Literal type of the `name` field of the `sharding_indexed` codec.""" + +ShardingIndexLocation = Literal["start", "end"] +"""Literal type of the position of the shard index within the encoded shard.""" + +SHARDING_INDEX_LOCATION: Final = ("start", "end") +"""Tuple of permitted values for the `index_location` field of the `sharding_indexed` codec.""" + + +class ShardingIndexedCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `sharding_indexed` codec. + + `chunk_shape` is the shape of inner chunks along each dimension; + it must evenly divide the shard shape. + + `codecs` is the codec pipeline applied to each inner chunk; exactly + one array-to-bytes codec is required. + + `index_codecs` is the codec pipeline applied to the shard index; + it must be deterministic (no variable-size compression). + + `index_location` defaults to `"end"` per the spec. + """ + + chunk_shape: tuple[int, ...] + codecs: tuple[ZarrV3MetadataFieldJSON, ...] + index_codecs: tuple[ZarrV3MetadataFieldJSON, ...] + index_location: NotRequired[ShardingIndexLocation] + + +class ShardingIndexedCodecObject(TypedDict): + """`sharding_indexed` codec metadata in object form.""" + + name: ShardingIndexedCodecName + configuration: ShardingIndexedCodecConfiguration + + +ShardingIndexedCodecMetadata = ShardingIndexedCodecObject +"""Permitted JSON shape for `sharding_indexed` codec metadata. + +The configuration has multiple required keys (`chunk_shape`, `codecs`, +`index_codecs`), so only the object form is valid; the short-hand-name +form is not permitted by the spec for this codec. +""" + +__all__ = [ + "SHARDING_INDEXED_CODEC_NAME", + "SHARDING_INDEX_LOCATION", + "ShardingIndexLocation", + "ShardingIndexedCodecConfiguration", + "ShardingIndexedCodecMetadata", + "ShardingIndexedCodecName", + "ShardingIndexedCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/transpose.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/transpose.py new file mode 100644 index 0000000000..ac469b356a --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/transpose.py @@ -0,0 +1,49 @@ +""" +Transpose codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/transpose/index.html +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +TRANSPOSE_CODEC_NAME: Final = "transpose" +"""The `name` field value of the `transpose` codec.""" + +TransposeCodecName = Literal["transpose"] +"""Literal type of the `name` field of the `transpose` codec.""" + + +class TransposeCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `transpose` codec. + + `order` is a permutation of the dimension indices 0..n-1 that + specifies the dimension reordering applied during encoding. + """ + + order: tuple[int, ...] + + +class TransposeCodecObject(TypedDict): + """`transpose` codec metadata in object form.""" + + name: TransposeCodecName + configuration: TransposeCodecConfiguration + + +TransposeCodecMetadata = TransposeCodecObject +"""Permitted JSON shape for `transpose` codec metadata. + +`order` is required, so only the object form is valid; the short-hand-name +form is not permitted by the spec for this codec. +""" + +__all__ = [ + "TRANSPOSE_CODEC_NAME", + "TransposeCodecConfiguration", + "TransposeCodecMetadata", + "TransposeCodecName", + "TransposeCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py new file mode 100644 index 0000000000..c0faa64bed --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py @@ -0,0 +1,51 @@ +""" +Zstandard codec types. + +See https://github.com/zarr-developers/zarr-specs/pull/256 (unmerged at +time of writing; the configuration shape below reflects the proposed +specification). +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +ZSTD_CODEC_NAME: Final = "zstd" +"""The `name` field value of the `zstd` codec.""" + +ZstdCodecName = Literal["zstd"] +"""Literal type of the `name` field of the `zstd` codec.""" + + +class ZstdCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `zstd` codec. + + Both fields are required per the proposed specification. + """ + + level: int + checksum: bool + + +class ZstdCodecObject(TypedDict): + """`zstd` codec metadata in object form.""" + + name: ZstdCodecName + configuration: ZstdCodecConfiguration + + +ZstdCodecMetadata = ZstdCodecObject +"""Permitted JSON shape for `zstd` codec metadata. + +Both `level` and `checksum` are required, so only the object form is +valid; the short-hand-name form is not permitted by the spec for this codec. +""" + +__all__ = [ + "ZSTD_CODEC_NAME", + "ZstdCodecConfiguration", + "ZstdCodecMetadata", + "ZstdCodecName", + "ZstdCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py new file mode 100644 index 0000000000..a9fe0c1f8f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py @@ -0,0 +1,49 @@ +"""Zarr v3 consolidated metadata types. + +There is no Zarr v3 specification for consolidated metadata. This module +models the inline-on-group convention used by the reference Python +implementation (and zarrs), where consolidated metadata is embedded as +an extension field on a group's `zarr.json`. + +This is a known non-core interoperability extension. Its +`{kind, must_understand, metadata}` payload is an unknown top-level JSON value +to the core document model; implementations that recognize the convention may +interpret it through this dedicated type. +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from typing_extensions import TypedDict + +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + + +class ZarrV3ConsolidatedMetadataJSON(TypedDict): + """ + Inline consolidated metadata embedded in a v3 group. + + The `metadata` map contains only v3 array and group entries. V2 entries + are excluded from this interoperability convention by design; the v3 core + specification does not define consolidated metadata. + """ + + kind: Literal["inline"] + must_understand: Literal[False] + metadata: Mapping[str, ZarrV3ArrayMetadataJSON | ZarrV3GroupMetadataJSON] + + +ZARR_V3_CONSOLIDATED_METADATA_KEY: Final = "consolidated_metadata" +"""The key under which consolidated metadata is embedded in a v3 group document. + +Unlike the v2 `.zmetadata` file, this is not a store key: consolidated metadata +is carried as an extension field inside the group's own `zarr.json`. Like its v2 +counterpart it is a reference-implementation convention, not a spec artifact. +""" + + +__all__ = [ + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + "ZarrV3ConsolidatedMetadataJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/__init__.py new file mode 100644 index 0000000000..180f9c500d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/__init__.py @@ -0,0 +1,105 @@ +""" +Zarr v3 data type spec types. + +Each v3 data type has its own submodule: + +- Core primitives: `bool`, `int8`/`16`/`32`/`64`, `uint8`/`16`/`32`/`64`, + `float16`/`32`/`64`, `complex64`/`128`, `raw` (for `r`) +- zarr-extensions: `bytes`, `string`, `numpy_datetime64`, `numpy_timedelta64`, + `struct` + +The two canonical types per dtype are re-exported here: + +- `DataTypeName` -- the literal type of the dtype's `data_type` string + (or, for named-config dtypes, the literal value of their `name` field) +- `FillValue` -- the permitted JSON shape of the `fill_value` field + +Named-config dtypes (`numpy_datetime64`, `numpy_timedelta64`, `struct`) also +expose their envelope TypedDict here. For configuration TypedDicts, branded +`HexFloat` / `Base64Bytes` types, and the corresponding validator +functions, import directly from the leaf submodule. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from zarr_metadata.v3.data_type.bool import BoolDataTypeName, BoolFillValue +from zarr_metadata.v3.data_type.bytes import BytesDataTypeName, BytesFillValue +from zarr_metadata.v3.data_type.complex64 import Complex64DataTypeName, Complex64FillValue +from zarr_metadata.v3.data_type.complex128 import ( + Complex128DataTypeName, + Complex128FillValue, +) +from zarr_metadata.v3.data_type.float16 import Float16DataTypeName, Float16FillValue +from zarr_metadata.v3.data_type.float32 import Float32DataTypeName, Float32FillValue +from zarr_metadata.v3.data_type.float64 import Float64DataTypeName, Float64FillValue +from zarr_metadata.v3.data_type.int8 import Int8DataTypeName, Int8FillValue +from zarr_metadata.v3.data_type.int16 import Int16DataTypeName, Int16FillValue +from zarr_metadata.v3.data_type.int32 import Int32DataTypeName, Int32FillValue +from zarr_metadata.v3.data_type.int64 import Int64DataTypeName, Int64FillValue +from zarr_metadata.v3.data_type.numpy_datetime64 import ( + NumpyDatetime64, + NumpyDatetime64DataTypeName, + NumpyDatetime64FillValue, +) +from zarr_metadata.v3.data_type.numpy_timedelta64 import ( + NumpyTimedelta64, + NumpyTimedelta64DataTypeName, + NumpyTimedelta64FillValue, +) +from zarr_metadata.v3.data_type.raw import RawBytesDataTypeName, RawBytesFillValue +from zarr_metadata.v3.data_type.string import StringDataTypeName, StringFillValue +from zarr_metadata.v3.data_type.struct import ( + Struct, + StructDataTypeName, + StructFillValue, +) +from zarr_metadata.v3.data_type.uint8 import Uint8DataTypeName, Uint8FillValue +from zarr_metadata.v3.data_type.uint16 import Uint16DataTypeName, Uint16FillValue +from zarr_metadata.v3.data_type.uint32 import Uint32DataTypeName, Uint32FillValue +from zarr_metadata.v3.data_type.uint64 import Uint64DataTypeName, Uint64FillValue + +__all__ = [ + "BoolDataTypeName", + "BoolFillValue", + "BytesDataTypeName", + "BytesFillValue", + "Complex64DataTypeName", + "Complex64FillValue", + "Complex128DataTypeName", + "Complex128FillValue", + "Float16DataTypeName", + "Float16FillValue", + "Float32DataTypeName", + "Float32FillValue", + "Float64DataTypeName", + "Float64FillValue", + "Int8DataTypeName", + "Int8FillValue", + "Int16DataTypeName", + "Int16FillValue", + "Int32DataTypeName", + "Int32FillValue", + "Int64DataTypeName", + "Int64FillValue", + "NumpyDatetime64", + "NumpyDatetime64DataTypeName", + "NumpyDatetime64FillValue", + "NumpyTimedelta64", + "NumpyTimedelta64DataTypeName", + "NumpyTimedelta64FillValue", + "RawBytesDataTypeName", + "RawBytesFillValue", + "StringDataTypeName", + "StringFillValue", + "Struct", + "StructDataTypeName", + "StructFillValue", + "Uint8DataTypeName", + "Uint8FillValue", + "Uint16DataTypeName", + "Uint16FillValue", + "Uint32DataTypeName", + "Uint32FillValue", + "Uint64DataTypeName", + "Uint64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bool.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bool.py new file mode 100644 index 0000000000..e36613a154 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bool.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `bool` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +BOOL_DATA_TYPE_NAME: Final = "bool" +"""The `data_type` value for the `bool` type.""" + +BoolDataTypeName = Literal["bool"] +"""Literal type of the `data_type` field for `bool`.""" + +BoolFillValue = bool +"""Permitted JSON shape of the `fill_value` field for `bool`: a JSON boolean.""" + + +__all__ = [ + "BOOL_DATA_TYPE_NAME", + "BoolDataTypeName", + "BoolFillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py new file mode 100644 index 0000000000..c7eed64f0f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py @@ -0,0 +1,48 @@ +""" +Zarr `bytes` data type (variable-length raw bytes, zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/bytes +""" + +import re +from typing import Final, Literal, NewType + +BYTES_DATA_TYPE_NAME: Final = "bytes" +"""The `data_type` value for the variable-length `bytes` type.""" + +BytesDataTypeName = Literal["bytes"] +"""Literal type of the `data_type` field for `bytes`.""" + +Base64Bytes = NewType("Base64Bytes", str) +"""A standard-alphabet base64-encoded byte sequence.""" + +_BASE64_RE: Final = re.compile(r"^[A-Za-z0-9+/]*={0,2}$") + + +def base64_bytes(value: str) -> Base64Bytes: + """Validate `value` as a Base64Bytes and brand it. + + Raises ValueError if `value` is not standard-alphabet base64 + (length must be a multiple of 4 once padded; only `A-Z`, `a-z`, + `0-9`, `+`, `/`, and trailing `=` padding are permitted). + """ + if len(value) % 4 != 0 or not _BASE64_RE.fullmatch(value): + raise ValueError(f"Expected standard-alphabet base64, got {value!r}") + return Base64Bytes(value) + + +BytesFillValue = tuple[int, ...] | Base64Bytes +"""Permitted JSON shape of the `fill_value` field for `bytes`. + +Either a JSON array of integers in `[0, 255]` (one per byte), or a +`Base64Bytes` string encoding the byte sequence. +""" + + +__all__ = [ + "BYTES_DATA_TYPE_NAME", + "Base64Bytes", + "BytesDataTypeName", + "BytesFillValue", + "base64_bytes", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py new file mode 100644 index 0000000000..780bbbb02f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py @@ -0,0 +1,37 @@ +""" +Zarr v3 `complex128` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +from zarr_metadata.v3.data_type.float64 import Float64FillValue + +COMPLEX128_DATA_TYPE_NAME: Final = "complex128" +"""The `data_type` value for the `complex128` type.""" + +Complex128DataTypeName = Literal["complex128"] +"""Literal type of the `data_type` field for `complex128`.""" + +Complex128Component = Float64FillValue +"""One real or imaginary component of a `complex128` fill value. + +Same shape as a `float64` fill value: a JSON number, a named sentinel, +or a `HexFloat64` string. +""" + +Complex128FillValue = tuple[Complex128Component, Complex128Component] +"""Permitted JSON shape of the `fill_value` field for `complex128`. + +A two-element JSON array `[real, imag]` where each component is a +`Complex128Component`. +""" + + +__all__ = [ + "COMPLEX128_DATA_TYPE_NAME", + "Complex128Component", + "Complex128DataTypeName", + "Complex128FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py new file mode 100644 index 0000000000..4aca608899 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py @@ -0,0 +1,37 @@ +""" +Zarr v3 `complex64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +from zarr_metadata.v3.data_type.float32 import Float32FillValue + +COMPLEX64_DATA_TYPE_NAME: Final = "complex64" +"""The `data_type` value for the `complex64` type.""" + +Complex64DataTypeName = Literal["complex64"] +"""Literal type of the `data_type` field for `complex64`.""" + +Complex64Component = Float32FillValue +"""One real or imaginary component of a `complex64` fill value. + +Same shape as a `float32` fill value: a JSON number, a named sentinel, +or a `HexFloat32` string. +""" + +Complex64FillValue = tuple[Complex64Component, Complex64Component] +"""Permitted JSON shape of the `fill_value` field for `complex64`. + +A two-element JSON array `[real, imag]` where each component is a +`Complex64Component`. +""" + + +__all__ = [ + "COMPLEX64_DATA_TYPE_NAME", + "Complex64Component", + "Complex64DataTypeName", + "Complex64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py new file mode 100644 index 0000000000..41eec441df --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py @@ -0,0 +1,71 @@ +""" +Zarr v3 `float16` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +import re +from typing import Final, Literal, NewType + +FLOAT16_DATA_TYPE_NAME: Final = "float16" +"""The `data_type` value for the `float16` type.""" + +Float16DataTypeName = Literal["float16"] +"""Literal type of the `data_type` field for `float16`.""" + +Float16SpecialFillValue = Literal["NaN", "Infinity", "-Infinity"] +"""Named non-finite fill values permitted by the spec for IEEE 754 floats.""" + +HexFloat16 = NewType("HexFloat16", str) +"""A 6-character hex string (`0x` + 4 hex digits) encoding the +unsigned-integer representation of a float16.""" + +_HEX_FLOAT16_RE: Final = re.compile(r"^0x[0-9a-fA-F]{4}$") + + +def hex_float16(value: str) -> HexFloat16: + """Validate `value` as a HexFloat16 and brand it. + + Raises ValueError if `value` is not exactly `0x` followed by 4 hex + digits. + """ + if not _HEX_FLOAT16_RE.fullmatch(value): + raise ValueError(f"Expected '0x' followed by 4 hex digits, got {value!r}") + return HexFloat16(value) + + +Float16FillValue = float | int | Float16SpecialFillValue | HexFloat16 +"""Permitted JSON shape of the `fill_value` field for `float16`. + +Either a JSON number, one of the named non-finite sentinels (`"NaN"`, +`"Infinity"`, `"-Infinity"`), or a `HexFloat16` (`0xYYYY` string encoding +the unsigned-integer representation of the IEEE 754 value). +""" + +CANONICAL_NAN_HEX_FLOAT16: Final = "0x7e00" +"""Canonical hex form of the float16 NaN sentinel `"NaN"`. + +Per spec the named `"NaN"` sentinel denotes the float with sign=0, the +most significant mantissa bit set, and all other mantissa bits zero +(the IEEE 754 default quiet NaN). Other NaN bit patterns must be +encoded with the explicit hex-string form. +""" + +CANONICAL_POSITIVE_INFINITY_HEX_FLOAT16: Final = "0x7c00" +"""Canonical hex form of the float16 `"Infinity"` sentinel.""" + +CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT16: Final = "0xfc00" +"""Canonical hex form of the float16 `"-Infinity"` sentinel.""" + + +__all__ = [ + "CANONICAL_NAN_HEX_FLOAT16", + "CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT16", + "CANONICAL_POSITIVE_INFINITY_HEX_FLOAT16", + "FLOAT16_DATA_TYPE_NAME", + "Float16DataTypeName", + "Float16FillValue", + "Float16SpecialFillValue", + "HexFloat16", + "hex_float16", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py new file mode 100644 index 0000000000..37b7d4f6e8 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py @@ -0,0 +1,71 @@ +""" +Zarr v3 `float32` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +import re +from typing import Final, Literal, NewType + +FLOAT32_DATA_TYPE_NAME: Final = "float32" +"""The `data_type` value for the `float32` type.""" + +Float32DataTypeName = Literal["float32"] +"""Literal type of the `data_type` field for `float32`.""" + +Float32SpecialFillValue = Literal["NaN", "Infinity", "-Infinity"] +"""Named non-finite fill values permitted by the spec for IEEE 754 floats.""" + +HexFloat32 = NewType("HexFloat32", str) +"""A 10-character hex string (`0x` + 8 hex digits) encoding the +unsigned-integer representation of a float32.""" + +_HEX_FLOAT32_RE: Final = re.compile(r"^0x[0-9a-fA-F]{8}$") + + +def hex_float32(value: str) -> HexFloat32: + """Validate `value` as a HexFloat32 and brand it. + + Raises ValueError if `value` is not exactly `0x` followed by 8 hex + digits. + """ + if not _HEX_FLOAT32_RE.fullmatch(value): + raise ValueError(f"Expected '0x' followed by 8 hex digits, got {value!r}") + return HexFloat32(value) + + +Float32FillValue = float | int | Float32SpecialFillValue | HexFloat32 +"""Permitted JSON shape of the `fill_value` field for `float32`. + +Either a JSON number, one of the named non-finite sentinels (`"NaN"`, +`"Infinity"`, `"-Infinity"`), or a `HexFloat32` (`0xYYYYYYYY` string +encoding the unsigned-integer representation of the IEEE 754 value). +""" + +CANONICAL_NAN_HEX_FLOAT32: Final = "0x7fc00000" +"""Canonical hex form of the float32 NaN sentinel `"NaN"`. + +Per spec the named `"NaN"` sentinel denotes the float with sign=0, the +most significant mantissa bit set, and all other mantissa bits zero +(the IEEE 754 default quiet NaN). Other NaN bit patterns must be +encoded with the explicit hex-string form. +""" + +CANONICAL_POSITIVE_INFINITY_HEX_FLOAT32: Final = "0x7f800000" +"""Canonical hex form of the float32 `"Infinity"` sentinel.""" + +CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT32: Final = "0xff800000" +"""Canonical hex form of the float32 `"-Infinity"` sentinel.""" + + +__all__ = [ + "CANONICAL_NAN_HEX_FLOAT32", + "CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT32", + "CANONICAL_POSITIVE_INFINITY_HEX_FLOAT32", + "FLOAT32_DATA_TYPE_NAME", + "Float32DataTypeName", + "Float32FillValue", + "Float32SpecialFillValue", + "HexFloat32", + "hex_float32", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py new file mode 100644 index 0000000000..9a5cf98288 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py @@ -0,0 +1,72 @@ +""" +Zarr v3 `float64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +import re +from typing import Final, Literal, NewType + +FLOAT64_DATA_TYPE_NAME: Final = "float64" +"""The `data_type` value for the `float64` type.""" + +Float64DataTypeName = Literal["float64"] +"""Literal type of the `data_type` field for `float64`.""" + +Float64SpecialFillValue = Literal["NaN", "Infinity", "-Infinity"] +"""Named non-finite fill values permitted by the spec for IEEE 754 floats.""" + +HexFloat64 = NewType("HexFloat64", str) +"""An 18-character hex string (`0x` + 16 hex digits) encoding the +unsigned-integer representation of a float64.""" + +_HEX_FLOAT64_RE: Final = re.compile(r"^0x[0-9a-fA-F]{16}$") + + +def hex_float64(value: str) -> HexFloat64: + """Validate `value` as a HexFloat64 and brand it. + + Raises ValueError if `value` is not exactly `0x` followed by 16 hex + digits. + """ + if not _HEX_FLOAT64_RE.fullmatch(value): + raise ValueError(f"Expected '0x' followed by 16 hex digits, got {value!r}") + return HexFloat64(value) + + +Float64FillValue = float | int | Float64SpecialFillValue | HexFloat64 +"""Permitted JSON shape of the `fill_value` field for `float64`. + +Either a JSON number, one of the named non-finite sentinels (`"NaN"`, +`"Infinity"`, `"-Infinity"`), or a `HexFloat64` (`0xYYYYYYYYYYYYYYYY` +string encoding the unsigned-integer representation of the IEEE 754 +value). +""" + +CANONICAL_NAN_HEX_FLOAT64: Final = "0x7ff8000000000000" +"""Canonical hex form of the float64 NaN sentinel `"NaN"`. + +Per spec the named `"NaN"` sentinel denotes the float with sign=0, the +most significant mantissa bit set, and all other mantissa bits zero +(the IEEE 754 default quiet NaN). Other NaN bit patterns must be +encoded with the explicit hex-string form. +""" + +CANONICAL_POSITIVE_INFINITY_HEX_FLOAT64: Final = "0x7ff0000000000000" +"""Canonical hex form of the float64 `"Infinity"` sentinel.""" + +CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT64: Final = "0xfff0000000000000" +"""Canonical hex form of the float64 `"-Infinity"` sentinel.""" + + +__all__ = [ + "CANONICAL_NAN_HEX_FLOAT64", + "CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT64", + "CANONICAL_POSITIVE_INFINITY_HEX_FLOAT64", + "FLOAT64_DATA_TYPE_NAME", + "Float64DataTypeName", + "Float64FillValue", + "Float64SpecialFillValue", + "HexFloat64", + "hex_float64", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int16.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int16.py new file mode 100644 index 0000000000..b76f06761a --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int16.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int16` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT16_DATA_TYPE_NAME: Final = "int16" +"""The `data_type` value for the `int16` type.""" + +Int16DataTypeName = Literal["int16"] +"""Literal type of the `data_type` field for `int16`.""" + +Int16FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int16`: a JSON integer in [-32768, 32767].""" + + +__all__ = [ + "INT16_DATA_TYPE_NAME", + "Int16DataTypeName", + "Int16FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int32.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int32.py new file mode 100644 index 0000000000..7b41ec6c54 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int32.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int32` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT32_DATA_TYPE_NAME: Final = "int32" +"""The `data_type` value for the `int32` type.""" + +Int32DataTypeName = Literal["int32"] +"""Literal type of the `data_type` field for `int32`.""" + +Int32FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int32`: a JSON integer in [-2**31, 2**31 - 1].""" + + +__all__ = [ + "INT32_DATA_TYPE_NAME", + "Int32DataTypeName", + "Int32FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int64.py new file mode 100644 index 0000000000..0005675c66 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int64.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT64_DATA_TYPE_NAME: Final = "int64" +"""The `data_type` value for the `int64` type.""" + +Int64DataTypeName = Literal["int64"] +"""Literal type of the `data_type` field for `int64`.""" + +Int64FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int64`: a JSON integer in [-2**63, 2**63 - 1].""" + + +__all__ = [ + "INT64_DATA_TYPE_NAME", + "Int64DataTypeName", + "Int64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int8.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int8.py new file mode 100644 index 0000000000..a5a16de761 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int8.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int8` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT8_DATA_TYPE_NAME: Final = "int8" +"""The `data_type` value for the `int8` type.""" + +Int8DataTypeName = Literal["int8"] +"""Literal type of the `data_type` field for `int8`.""" + +Int8FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int8`: a JSON integer in [-128, 127].""" + + +__all__ = [ + "INT8_DATA_TYPE_NAME", + "Int8DataTypeName", + "Int8FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py new file mode 100644 index 0000000000..8784160f71 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py @@ -0,0 +1,60 @@ +""" +Zarr `numpy.datetime64` data type (zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.datetime64 +""" + +from typing import Final, Literal + +from typing_extensions import ReadOnly, TypedDict + +NUMPY_DATETIME64_DATA_TYPE_NAME: Final = "numpy.datetime64" +"""The `name` field value of the `numpy.datetime64` data type.""" + +NumpyDatetime64DataTypeName = Literal["numpy.datetime64"] +"""Literal type of the `name` field of the `numpy.datetime64` data type.""" + +NumpyTimeUnit = Literal[ + "Y", "M", "W", "D", "h", "m", "s", "ms", "us", "μs", "ns", "ps", "fs", "as", "generic" +] +"""Time unit codes used by numpy.datetime64.""" + + +class NumpyDatetime64Configuration(TypedDict): + """ + Configuration for the `numpy.datetime64` data type. + + Attributes + ---------- + unit + A string encoding a unit of time. + scale_factor + The multiplier relative to the unit. + """ + + unit: ReadOnly[NumpyTimeUnit] + scale_factor: ReadOnly[int] + + +class NumpyDatetime64(TypedDict): + """`numpy.datetime64` data type metadata.""" + + name: NumpyDatetime64DataTypeName + configuration: NumpyDatetime64Configuration + + +NumpyDatetime64FillValue = int | Literal["NaT"] +"""Permitted JSON shape of the `fill_value` field for `numpy.datetime64`. + +Either a JSON integer (count of `unit * scale_factor` since the epoch), +or the string `"NaT"` (equivalent to the integer `-2**63`). +""" + +__all__ = [ + "NUMPY_DATETIME64_DATA_TYPE_NAME", + "NumpyDatetime64", + "NumpyDatetime64Configuration", + "NumpyDatetime64DataTypeName", + "NumpyDatetime64FillValue", + "NumpyTimeUnit", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py new file mode 100644 index 0000000000..f5c8c77bf8 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py @@ -0,0 +1,80 @@ +""" +Zarr `numpy.timedelta64` data type (zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.timedelta64 +""" + +from typing import Final, Literal + +from typing_extensions import ReadOnly, TypedDict + +NUMPY_TIMEDELTA64_DATA_TYPE_NAME: Final = "numpy.timedelta64" +"""The `name` field value of the `numpy.timedelta64` data type.""" + +NumpyTimedelta64DataTypeName = Literal["numpy.timedelta64"] +"""Literal type of the `name` field of the `numpy.timedelta64` data type.""" + +NumpyTimeUnit = Literal[ + "Y", "M", "W", "D", "h", "m", "s", "ms", "us", "μs", "ns", "ps", "fs", "as", "generic" +] +"""Time unit codes used by numpy.timedelta64.""" + +NUMPY_TIME_UNIT: Final = ( + "Y", + "M", + "W", + "D", + "h", + "m", + "s", + "ms", + "us", + "μs", + "ns", + "ps", + "fs", + "as", + "generic", +) +"""Runtime tuple of the permitted `numpy.timedelta64`/`numpy.datetime64` unit strings.""" + + +class NumpyTimedelta64Configuration(TypedDict): + """ + Configuration for the `numpy.timedelta64` data type. + + Attributes + ---------- + unit + A string encoding a unit of time. + scale_factor + The multiplier relative to the unit. + """ + + unit: ReadOnly[NumpyTimeUnit] + scale_factor: ReadOnly[int] + + +class NumpyTimedelta64(TypedDict): + """`numpy.timedelta64` data type metadata.""" + + name: NumpyTimedelta64DataTypeName + configuration: NumpyTimedelta64Configuration + + +NumpyTimedelta64FillValue = int | Literal["NaT"] +"""Permitted JSON shape of the `fill_value` field for `numpy.timedelta64`. + +Either a JSON integer (a count of `unit * scale_factor`), or the string +`"NaT"` (equivalent to the integer `-2**63`). +""" + +__all__ = [ + "NUMPY_TIMEDELTA64_DATA_TYPE_NAME", + "NUMPY_TIME_UNIT", + "NumpyTimeUnit", + "NumpyTimedelta64", + "NumpyTimedelta64Configuration", + "NumpyTimedelta64DataTypeName", + "NumpyTimedelta64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/raw.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/raw.py new file mode 100644 index 0000000000..c9c688c9fa --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/raw.py @@ -0,0 +1,45 @@ +""" +Zarr v3 `r` raw-bytes data type (parameterised by bit count). + +The `data_type` value is a string of the form `r` where `N` is a +positive multiple of 8 (e.g. `r8`, `r16`, `r24`). + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html +""" + +import re +from typing import Final, NewType + +RawBytesDataTypeName = NewType("RawBytesDataTypeName", str) +"""A spec-conformant `r` raw-bytes name (e.g. `"r8"`, `"r16"`).""" + +_RAW_BYTES_RE: Final = re.compile(r"^r(\d+)$") + + +def raw_bytes_dtype_name(value: str) -> RawBytesDataTypeName: + """Validate `value` as a `r` raw-bytes name and brand it. + + Raises ValueError if `value` is not `r` followed by a positive + multiple of 8. + """ + match = _RAW_BYTES_RE.fullmatch(value) + if match is None: + raise ValueError(f"Expected 'r' followed by a positive integer, got {value!r}") + bits = int(match.group(1)) + if bits == 0 or bits % 8 != 0: + raise ValueError(f"Expected 'r' where N is a positive multiple of 8, got {value!r}") + return RawBytesDataTypeName(value) + + +RawBytesFillValue = tuple[int, ...] +"""Permitted JSON shape of the `fill_value` field for `r`. + +A JSON array of N/8 integers in `[0, 255]` (one per byte). +""" + + +__all__ = [ + "RawBytesDataTypeName", + "RawBytesFillValue", + "raw_bytes_dtype_name", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/string.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/string.py new file mode 100644 index 0000000000..0a778ccecc --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/string.py @@ -0,0 +1,23 @@ +""" +Zarr `string` data type (variable-length utf-8, zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/string +""" + +from typing import Final, Literal + +STRING_DATA_TYPE_NAME: Final = "string" +"""The `data_type` value for the `string` type.""" + +StringDataTypeName = Literal["string"] +"""Literal type of the `data_type` field for `string`.""" + +StringFillValue = str +"""Permitted JSON shape of the `fill_value` field for `string`: a JSON unicode string.""" + + +__all__ = [ + "STRING_DATA_TYPE_NAME", + "StringDataTypeName", + "StringFillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py new file mode 100644 index 0000000000..b1b6b50308 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py @@ -0,0 +1,66 @@ +""" +Zarr `struct` data type (heterogeneous record, zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/blob/main/data-types/struct/README.md +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from typing_extensions import ReadOnly, TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +STRUCT_DATA_TYPE_NAME: Final = "struct" +"""The `name` field value of the `struct` data type.""" + +StructDataTypeName = Literal["struct"] +"""Literal type of the `name` field of the `struct` data type.""" + + +class StructField(TypedDict): + """ + A single field entry inside a structured dtype. + + Attributes + ---------- + name + The field name (must be unique within a struct and non-empty). + data_type + The field's data type. Recursive: may be a bare-string primitive + or a named-config envelope including another `struct`. + """ + + name: ReadOnly[str] + data_type: ReadOnly[ZarrV3MetadataFieldJSON] + + +class StructConfiguration(TypedDict): + """Configuration for the `struct` data type.""" + + fields: ReadOnly[tuple[StructField, ...]] + + +class Struct(TypedDict): + """`struct` data type metadata.""" + + name: StructDataTypeName + configuration: StructConfiguration + + +StructFillValue = Mapping[str, JSONValue] +"""Permitted JSON shape of the `fill_value` field for `struct`. + +A JSON object mapping each field name to that field's fill value. Field +fill values are themselves shaped per the field's `data_type`, recursively. +""" + +__all__ = [ + "STRUCT_DATA_TYPE_NAME", + "Struct", + "StructConfiguration", + "StructDataTypeName", + "StructField", + "StructFillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint16.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint16.py new file mode 100644 index 0000000000..37e35ec436 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint16.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint16` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT16_DATA_TYPE_NAME: Final = "uint16" +"""The `data_type` value for the `uint16` type.""" + +Uint16DataTypeName = Literal["uint16"] +"""Literal type of the `data_type` field for `uint16`.""" + +Uint16FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint16`: a JSON integer in [0, 65535].""" + + +__all__ = [ + "UINT16_DATA_TYPE_NAME", + "Uint16DataTypeName", + "Uint16FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint32.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint32.py new file mode 100644 index 0000000000..f6cd4d447e --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint32.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint32` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT32_DATA_TYPE_NAME: Final = "uint32" +"""The `data_type` value for the `uint32` type.""" + +Uint32DataTypeName = Literal["uint32"] +"""Literal type of the `data_type` field for `uint32`.""" + +Uint32FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint32`: a JSON integer in [0, 2**32 - 1].""" + + +__all__ = [ + "UINT32_DATA_TYPE_NAME", + "Uint32DataTypeName", + "Uint32FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint64.py new file mode 100644 index 0000000000..7151d2395a --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint64.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT64_DATA_TYPE_NAME: Final = "uint64" +"""The `data_type` value for the `uint64` type.""" + +Uint64DataTypeName = Literal["uint64"] +"""Literal type of the `data_type` field for `uint64`.""" + +Uint64FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint64`: a JSON integer in [0, 2**64 - 1].""" + + +__all__ = [ + "UINT64_DATA_TYPE_NAME", + "Uint64DataTypeName", + "Uint64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint8.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint8.py new file mode 100644 index 0000000000..787f1b7866 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint8.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint8` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT8_DATA_TYPE_NAME: Final = "uint8" +"""The `data_type` value for the `uint8` type.""" + +Uint8DataTypeName = Literal["uint8"] +"""Literal type of the `data_type` field for `uint8`.""" + +Uint8FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint8`: a JSON integer in [0, 255].""" + + +__all__ = [ + "UINT8_DATA_TYPE_NAME", + "Uint8DataTypeName", + "Uint8FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/group.py b/packages/zarr-metadata/src/zarr_metadata/v3/group.py new file mode 100644 index 0000000000..37bfdd6934 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/group.py @@ -0,0 +1,73 @@ +"""Zarr v3 group metadata types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#group-metadata +""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3.array import ZarrV3ExtensionField + + +class ZarrV3GroupMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): + """ + Zarr v3 group metadata document (the `zarr.json` content for a group). + + Extra keys may contain arbitrary JSON values. + + See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#group-metadata + """ + + zarr_format: Literal[3] + node_type: Literal["group"] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV3GroupMetadataJSONPartial(TypedDict, total=False, extra_items=ZarrV3ExtensionField): + """ + Partial form of `ZarrV3GroupMetadataJSON`: every field is `NotRequired`. + + Field annotations and `extra_items=` mirror `ZarrV3GroupMetadataJSON` exactly. + The only difference is `total=False`, which makes every key optional + at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v3 group metadata document — e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. + + The `NotRequired[...]` wrapper on `attributes` is intentional: keeping it + preserves byte-identical `__annotations__` with `ZarrV3GroupMetadataJSON` so the + `==` check in `tests/test_partial_equivalence.py` passes without + special-casing that field (PEP 655 explicitly permits `NotRequired` inside + `total=False`). + + Drift between this type and `ZarrV3GroupMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[3] + node_type: Literal["group"] + attributes: NotRequired[Mapping[str, JSONValue]] + + +ZarrV3GroupMetadataStoreKey = Literal["zarr.json"] +"""Literal type of the store key holding a v3 group's metadata document.""" + +ZARR_V3_GROUP_METADATA_STORE_KEY: Final[ZarrV3GroupMetadataStoreKey] = "zarr.json" +"""The store key a v3 group's metadata document is persisted under. + +v3 uses one key for both node types; the document's `node_type` field +distinguishes a group from an array. +""" + + +__all__ = [ + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "ZarrV3GroupMetadataJSON", + "ZarrV3GroupMetadataJSONPartial", + "ZarrV3GroupMetadataStoreKey", +] diff --git a/packages/zarr-metadata/tests/__init__.py b/packages/zarr-metadata/tests/__init__.py new file mode 100644 index 0000000000..d886440736 --- /dev/null +++ b/packages/zarr-metadata/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for zarr-metadata.""" diff --git a/packages/zarr-metadata/tests/model/__init__.py b/packages/zarr-metadata/tests/model/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/model/_cases.py b/packages/zarr-metadata/tests/model/_cases.py new file mode 100644 index 0000000000..15faa65539 --- /dev/null +++ b/packages/zarr-metadata/tests/model/_cases.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, Generic, TypeVar + +import pytest + +if TYPE_CHECKING: + from contextlib import AbstractContextManager + +TIn = TypeVar("TIn") +TOut = TypeVar("TOut") + + +@dataclass(frozen=True) +class Expect(Generic[TIn, TOut]): + """A test case with explicit input, expected output, and a human-readable id.""" + + input: TIn + output: TOut + id: str + + +@dataclass(frozen=True) +class ExpectFail(Generic[TIn]): + """A test case that should raise an exception. + + `msg` is a regex matched against the exception text (pytest's native + `match=` semantics). Leave it `None` to assert only the exception type. Set + `escape=True` when `msg` is a literal that contains regex metacharacters + such as `(`, `[`, or `.`; `escape` has no effect when `msg` is `None`. + """ + + input: TIn + exception: type[Exception] + id: str + msg: str | None = None + escape: bool = False + + def raises(self) -> AbstractContextManager[pytest.ExceptionInfo[Exception]]: + if self.msg is None: + return pytest.raises(self.exception) + pattern = re.escape(self.msg) if self.escape else self.msg + return pytest.raises(self.exception, match=pattern) + + +def mutate_nested_containers(value: object) -> None: + """Recursively mutate every mutable container reachable inside `value`. + + Adds a marker key to every dict and appends a marker to every list, + descending through tuples. Used to prove a `to_json` document shares no + mutable state with the model that produced it. + """ + if isinstance(value, dict): + for item in value.values(): + mutate_nested_containers(item) + value["__mutated__"] = "__mutated__" + elif isinstance(value, list): + for item in value: + mutate_nested_containers(item) + value.append("__mutated__") + elif isinstance(value, tuple): + for item in value: + mutate_nested_containers(item) diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py new file mode 100644 index 0000000000..95dc7aea3a --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -0,0 +1,1784 @@ +"""Tests for the metadata models in ``zarr_metadata.model``.""" + +import copy +import dataclasses +import json +from collections import UserDict +from collections.abc import Callable +from typing import TYPE_CHECKING, get_args + +import pytest +from typing_extensions import Unpack + +from tests.model._cases import Expect, ExpectFail, mutate_nested_containers +from zarr_metadata.model import ( + ARRAY_METADATA_OPTIONAL_KEYS_V3, + ARRAY_METADATA_REQUIRED_KEYS_V3, + ARRAY_METADATA_STANDARD_KEYS_V3, + UNSET, + MetadataValidationError, + ValidationProblem, + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadataPartial, + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadataPartial, + ZarrV3MetadataField, + ZarrV3NamedConfig, + is_array_metadata_v2, + is_array_metadata_v3, + is_json, + is_metadata_field_v3, + parse_array_metadata_v2, + parse_array_metadata_v3, + parse_json, + parse_metadata_field_v3, + validate_array_metadata_v2, + validate_array_metadata_v3, + validate_json, + validate_metadata_field_v3, +) +from zarr_metadata.model._validation import _prefix, arrays_to_tuples + +if TYPE_CHECKING: + from zarr_metadata._common import JSONValue + from zarr_metadata.v2 import ZarrV2CodecMetadata + +# --- public exports -------------------------------------------------------- + + +def test_guards_exported_from_package() -> None: + """The wire-type guard/parser functions are exported from the package.""" + import zarr_metadata.model + + for name in ( + "is_json", + "parse_json", + "is_metadata_field_v3", + "parse_metadata_field_v3", + "is_array_metadata_v3", + "parse_array_metadata_v3", + "is_array_metadata_v2", + "parse_array_metadata_v2", + ): + assert name in zarr_metadata.model.__all__ + assert hasattr(zarr_metadata.model, name) + + +# `ZARR_V3_CONSOLIDATED_METADATA_KEY` is deliberately absent: it names a key +# *inside* a v3 group document, not a store key, so it has no paired `Literal` +# and no `to_key_value` signature to appear in. See `test_v3_consolidated_key_ +# is_not_a_store_key`, which pins that distinction. +STORE_KEY_PAIRS = [ + ("ZARR_V2_ARRAY_METADATA_STORE_KEY", "ZarrV2ArrayMetadataStoreKey", "zarr_metadata.v2.array"), + ("ZARR_V3_ARRAY_METADATA_STORE_KEY", "ZarrV3ArrayMetadataStoreKey", "zarr_metadata.v3.array"), + ("ZARR_V2_ATTRIBUTES_STORE_KEY", "ZarrV2AttributesStoreKey", "zarr_metadata.v2.attributes"), + ("ZARR_V2_GROUP_METADATA_STORE_KEY", "ZarrV2GroupMetadataStoreKey", "zarr_metadata.v2.group"), + ("ZARR_V3_GROUP_METADATA_STORE_KEY", "ZarrV3GroupMetadataStoreKey", "zarr_metadata.v3.group"), + ( + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZarrV2ConsolidatedMetadataStoreKey", + "zarr_metadata.v2.consolidated", + ), +] + + +def test_store_key_pairs_exported_from_package() -> None: + """Each store-key constant is exported together with its Literal type + alias, and the pair cannot drift apart.""" + import zarr_metadata.model as m + + for const_name, alias_name, _ in STORE_KEY_PAIRS: + assert const_name in m.__all__ + assert alias_name in m.__all__ + assert (getattr(m, const_name),) == get_args(getattr(m, alias_name)) + + +def test_store_keys_are_defined_in_their_spec_modules() -> None: + """Store keys are facts about the on-disk specs, so each is defined in the + `v2`/`v3` module describing that document — not in the model layer, which + only re-exports them.""" + import importlib + + for const_name, alias_name, module_name in STORE_KEY_PAIRS: + module = importlib.import_module(module_name) + for name in (const_name, alias_name): + assert name in module.__all__, f"{name} should be exported by {module_name}" + + +def test_v3_consolidated_key_is_not_a_store_key() -> None: + """v3 consolidated metadata is embedded as a field inside the group's own + `zarr.json`, not persisted under its own store key. It therefore has no + paired `Literal` alias, unlike every true store key — which is why it is + excluded from `STORE_KEY_PAIRS` rather than merely forgotten.""" + import zarr_metadata.model as m + + assert "ZARR_V3_CONSOLIDATED_METADATA_KEY" in m.__all__ + assert not hasattr(m, "ZarrV3ConsolidatedMetadataKey") + assert m.ZARR_V3_CONSOLIDATED_METADATA_KEY not in { + getattr(m, const_name) for const_name, _, _ in STORE_KEY_PAIRS + } + + +def test_v3_node_store_keys_agree() -> None: + """v3 keys both node types' metadata under one store key, distinguished by + the document's `node_type`. The array and group constants are separately + typed but must name the same file; adjacency used to make that obvious, and + they now live in different modules.""" + import zarr_metadata.model as m + + assert m.ZARR_V3_ARRAY_METADATA_STORE_KEY == m.ZARR_V3_GROUP_METADATA_STORE_KEY + + +def test_validation_diagnostics_exported_from_package() -> None: + """The validation-diagnostic types and validators are exported from the package.""" + import zarr_metadata.model + + for name in ( + "ValidationProblem", + "MetadataValidationError", + "validate_json", + "validate_metadata_field_v3", + "validate_array_metadata_v3", + "validate_array_metadata_v2", + ): + assert name in zarr_metadata.model.__all__ + assert hasattr(zarr_metadata.model, name) + + +def test_expect_expectfail_smoke() -> None: + """The Expect/ExpectFail test-case dataclasses behave as expected.""" + e = Expect(input=1, output=2, id="x") + assert (e.input, e.output, e.id) == (1, 2, "x") + f = ExpectFail(input=1, exception=ValueError, id="y", msg="boom") + with f.raises(): + raise ValueError("boom") + + +def test_v3_from_json_error_lists_all_problems() -> None: + """A malformed v3 document surfaces every problem via MetadataValidationError.problems.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + del doc["shape"] + doc["data_type"] = 5 + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV3ArrayMetadata.from_json(doc) + locs = {p.loc for p in exc_info.value.problems} + assert ("shape",) in locs + assert ("data_type",) in locs + + +# --- JSON type / fill_value contract --------------------------------------- + + +def test_json_value_type_accepts_json_shapes() -> None: + # JSONValue is the package's public JSON type alias; assigning JSON-shaped + # values to it is valid. + """The JSONValue type alias accepts JSON-shaped values.""" + value: JSONValue = {"a": [1, 2.0, "x", True, None]} + assert value == {"a": [1, 2.0, "x", True, None]} + + +def test_string_nan_fill_value_roundtrips() -> None: + # Non-finite floats are represented as the spec strings ("NaN", "Infinity", + # "-Infinity") by the caller — the metadata layer does not interpret dtypes. + # The string form round-trips cleanly under default dataclass equality, + # unlike a raw float('nan') (which is an invalid fill_value the caller must + # not pass). + """A string 'NaN' fill_value round-trips cleanly (non-finite floats are the caller's responsibility).""" + m = ZarrV3ArrayMetadata.create_default(fill_value="NaN") + assert ZarrV3ArrayMetadata.from_json(m.to_json()) == m + assert ZarrV3ArrayMetadata.from_json(m.to_json()).fill_value == "NaN" + + +# --- ZarrV3NamedConfig.to_json ------------------------------------------------ + +ZARR_TO_JSON_CASES = [ + Expect( + ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": [1]}), + {"name": "regular", "configuration": {"chunk_shape": [1]}}, + id="with-configuration", + ), + Expect( + ZarrV3NamedConfig(name="bytes", configuration={}), + "bytes", + id="empty-configuration-shorthand", + ), +] + + +@pytest.mark.parametrize("case", ZARR_TO_JSON_CASES, ids=lambda c: c.id) +def test_zarr_metadata_v3_to_json(case: Expect[ZarrV3NamedConfig, object]) -> None: + """ZarrV3NamedConfig.to_json emits the canonical extension form.""" + assert case.input.to_json() == case.output + + +def test_zarr_metadata_v3_to_json_preserves_false_obligation() -> None: + """An empty optional extension stays an object so false is not lost.""" + model = ZarrV3NamedConfig(name="optional", configuration={}, must_understand=False) + assert model.to_json() == {"name": "optional", "must_understand": False} + + +# --- ZarrV3NamedConfig.from_json ----------------------------------------------- + +ZARR_FROM_JSON_CASES = [ + Expect("bytes", ZarrV3NamedConfig(name="bytes", configuration={}), id="bare-string"), + Expect( + {"name": "regular", "configuration": {"chunk_shape": [1]}}, + ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": (1,)}), + id="object-with-config", + ), + Expect( + {"name": "bytes"}, + ZarrV3NamedConfig(name="bytes", configuration={}), + id="object-without-config", + ), +] + + +@pytest.mark.parametrize("case", ZARR_FROM_JSON_CASES, ids=lambda c: c.id) +def test_zarr_metadata_v3_from_json(case: Expect[object, ZarrV3NamedConfig]) -> None: + """ZarrV3NamedConfig.from_json parses both the bare-string and object forms.""" + assert ZarrV3NamedConfig.from_json(case.input) == case.output + + +def test_zarr_metadata_v3_from_json_preserves_false_obligation() -> None: + """Explicit false is represented on the normalized model.""" + model = ZarrV3NamedConfig.from_json({"name": "optional", "must_understand": False}) + assert model.must_understand is False + + +# --- V3 baseline ----------------------------------------------------------- + + +def test_v3_to_json_emits_canonical_document() -> None: + """V3 to_json emits exactly the expected document (which covers every + spec-required key by construction).""" + out = ZarrV3ArrayMetadata.create_default( + shape=(10,), data_type=ZarrV3NamedConfig(name="int32", configuration={}) + ).to_json() + assert out == { + "zarr_format": 3, + "node_type": "array", + "shape": (10,), + "fill_value": 0, + "data_type": "int32", + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (10,)}}, + "codecs": ("bytes",), + "chunk_key_encoding": "default", + } + + +def test_v3_dimension_names_included_when_present() -> None: + """V3 to_json includes dimension_names when they are set.""" + out: dict[str, object] = dict( + ZarrV3ArrayMetadata.create_default(dimension_names=("x",)).to_json() + ) + assert out["dimension_names"] == ("x",) + + +def test_v3_dimension_names_omitted_when_none() -> None: + """V3 to_json omits dimension_names when they are UNSET.""" + out = ZarrV3ArrayMetadata.create_default(dimension_names=UNSET).to_json() + assert "dimension_names" not in out + + +# --- BUG 1: attributes gated on dimension_names ---------------------------- + + +def test_v3_attributes_included_when_dimension_names_is_none() -> None: + """Attributes must be emitted regardless of dimension_names. + + Regression: attributes were gated on ``dimension_names is not None``, + so non-empty attributes were silently dropped when there were no + dimension names. + """ + out: dict[str, object] = dict( + ZarrV3ArrayMetadata.create_default( + dimension_names=UNSET, attributes={"foo": "bar"} + ).to_json() + ) + assert out["attributes"] == {"foo": "bar"} + + +# --- BUG 2: single storage transformer dropped ----------------------------- + + +def test_v3_single_storage_transformer_included() -> None: + """A single storage transformer must be emitted. + + Regression: the guard used ``> 1`` instead of ``> 0``, dropping a + lone storage transformer. + """ + st = ZarrV3NamedConfig(name="some_transformer", configuration={}) + out: dict[str, object] = dict( + ZarrV3ArrayMetadata.create_default(storage_transformers=(st,)).to_json() + ) + assert out["storage_transformers"] == ("some_transformer",) + + +def test_v3_no_storage_transformers_omitted() -> None: + """V3 to_json omits storage_transformers when empty.""" + out = ZarrV3ArrayMetadata.create_default(storage_transformers=()).to_json() + assert "storage_transformers" not in out + + +# --- V3 extra fields ------------------------------------------------------- + + +def test_v3_extra_fields_merged() -> None: + """V3 to_json merges extra_fields into the top-level document.""" + out = ZarrV3ArrayMetadata.create_default( + extra_fields={"my_ext": {"must_understand": False}} + ).to_json() + assert out["my_ext"] == {"must_understand": False} + + +def test_v3_extra_fields_overlapping_standard_field_rejected() -> None: + """Constructing a V3 model with an extra field that collides with a standard key is rejected.""" + with pytest.raises(ValueError): + ZarrV3ArrayMetadata.create_default(extra_fields={"shape": {"must_understand": False}}) + + +# --- V3 key/value ---------------------------------------------------------- + + +def test_v3_to_key_value_is_valid_json_under_zarr_json() -> None: + """V3 to_key_value produces valid JSON bytes under the zarr.json key.""" + kv = ZarrV3ArrayMetadata.create_default(attributes={"a": 1}).to_key_value() + assert set(kv) == {"zarr.json"} + parsed = json.loads(kv["zarr.json"].decode("utf-8")) + assert parsed["zarr_format"] == 3 + assert parsed["attributes"] == {"a": 1} + + +# --- V3 standard-key sets -------------------------------------------------- + + +def test_standard_keys_is_union_of_required_and_optional() -> None: + """The standard-key set is the union of the required and optional key sets.""" + assert ( + ARRAY_METADATA_STANDARD_KEYS_V3 + == ARRAY_METADATA_REQUIRED_KEYS_V3 | ARRAY_METADATA_OPTIONAL_KEYS_V3 + ) + + +def test_standard_keys_contains_known_fields_and_excludes_extensions() -> None: + """The standard-key set contains known fields and excludes extension keys.""" + assert { + "zarr_format", + "node_type", + "shape", + "codecs", + } <= ARRAY_METADATA_STANDARD_KEYS_V3 + assert "my_ext" not in ARRAY_METADATA_STANDARD_KEYS_V3 + + +# --- create_default -------------------------------------------------------- + + +def test_v3_create_default_is_valid_empty_array() -> None: + """V3 create_default builds a structurally valid empty array that round-trips.""" + m = ZarrV3ArrayMetadata.create_default() + assert m.shape == () + assert m.data_type == ZarrV3NamedConfig(name="uint8", configuration={}) + assert m.fill_value == 0 + assert m.attributes == {} + assert m.extra_fields == {} + # the default document is structurally valid and round-trips + assert validate_array_metadata_v3(m.to_json()) == [] + assert ZarrV3ArrayMetadata.from_json(m.to_json()) == m + + +def test_v3_create_default_applies_overrides() -> None: + """V3 create_default applies keyword overrides over the defaults.""" + m = ZarrV3ArrayMetadata.create_default(shape=(4, 4), attributes={"a": 1}) + assert m.shape == (4, 4) + assert m.attributes == {"a": 1} + # un-overridden fields keep their defaults + assert m.data_type == ZarrV3NamedConfig(name="uint8", configuration={}) + + +def test_v2_create_default_is_valid_empty_array() -> None: + """V2 create_default builds a structurally valid empty array that round-trips.""" + m = ZarrV2ArrayMetadata.create_default() + assert m.shape == () + assert m.chunks == () + assert m.fill_value == 0 + assert m.compressor is None + assert m.filters is None + assert m.attributes is UNSET + assert validate_array_metadata_v2(m.to_json()) == [] + assert ZarrV2ArrayMetadata.from_json(m.to_json()) == m + + +def test_v2_create_default_applies_overrides() -> None: + """V2 create_default applies keyword overrides over the defaults.""" + m = ZarrV2ArrayMetadata.create_default(shape=(8,), attributes={"k": "v"}) + assert m.shape == (8,) + assert m.attributes == {"k": "v"} + assert m.dtype == "|u1" # default dtype unchanged + + +# --- V3 update ------------------------------------------------------------- + +# Cluster 3: update same-shape pairs across versions — parametrized + +UPDATE_NEW_INSTANCE_PARAMS = [ + pytest.param(ZarrV3ArrayMetadata, id="v3"), + pytest.param(ZarrV2ArrayMetadata, id="v2"), +] + + +@pytest.mark.parametrize("model_cls", UPDATE_NEW_INSTANCE_PARAMS) +def test_update_returns_new_instance( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], +) -> None: + """update returns a new instance with the field replaced, leaving the original unchanged.""" + base = model_cls.create_default(shape=(10,)) + updated = base.update(shape=(20,)) + assert updated.shape == (20,) + assert base.shape == (10,) # original unchanged + assert isinstance(updated, model_cls) + + +UPDATE_NO_ARGS_PARAMS = [ + pytest.param(ZarrV3ArrayMetadata, id="v3"), + pytest.param(ZarrV2ArrayMetadata, id="v2"), +] + + +@pytest.mark.parametrize("model_cls", UPDATE_NO_ARGS_PARAMS) +def test_update_no_args_returns_equal_model( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], +) -> None: + """update with no arguments returns a model equal to the original.""" + base = model_cls.create_default() + assert base.update() == base + + +# V3-only update tests — kept direct (extra_fields is v3-specific) + + +def test_update_can_replace_extra_fields() -> None: + """update can replace the extra_fields mapping.""" + base = ZarrV3ArrayMetadata.create_default(extra_fields={}) + updated = base.update(extra_fields={"my_ext": {"must_understand": False}}) + assert updated.extra_fields == {"my_ext": {"must_understand": False}} + + +def test_update_replaces_extra_fields_rather_than_merging() -> None: + """update replaces extra_fields wholesale rather than merging.""" + base = ZarrV3ArrayMetadata.create_default(extra_fields={"a": {"must_understand": False}}) + updated = base.update(extra_fields={"b": {"must_understand": True}}) + assert updated.extra_fields == {"b": {"must_understand": True}} + + +def test_partial_keys_match_settable_model_fields() -> None: + """The partial TypedDict must list exactly the constructor-settable fields. + + Guards against drift: adding/removing a settable field on the model + without updating ``ZarrV3ArrayMetadataPartial`` fails here. + """ + settable = {f.name for f in dataclasses.fields(ZarrV3ArrayMetadata) if f.init} + assert set(ZarrV3ArrayMetadataPartial.__annotations__) == settable + + +# --- V2 model -------------------------------------------------------------- + + +def test_v2_partial_keys_match_settable_model_fields() -> None: + """The v2 partial TypedDict must list exactly the settable fields.""" + settable = {f.name for f in dataclasses.fields(ZarrV2ArrayMetadata) if f.init} + assert set(ZarrV2ArrayMetadataPartial.__annotations__) == settable + + +def test_v2_to_key_value_splits_zarray_and_zattrs() -> None: + """V2 to_key_value splits the document into .zarray and .zattrs.""" + kv = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_key_value() + assert set(kv) == {".zarray", ".zattrs"} + zarray = json.loads(kv[".zarray"].decode("utf-8")) + zattrs = json.loads(kv[".zattrs"].decode("utf-8")) + assert zarray["zarr_format"] == 2 + assert zattrs == {"a": 1} + + +def test_v2_zarray_excludes_attributes() -> None: + """The on-disk ``.zarray`` document must not contain user attributes. + + In v2, attributes live only in the sibling ``.zattrs`` file. The bundled + ``ZarrV2ArrayMetadataJSON`` / ``to_json()`` carry attributes for convenience, but + ``to_key_value()`` must split them out. + """ + kv = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_key_value() + zarray = json.loads(kv[".zarray"].decode("utf-8")) + assert "attributes" not in zarray + + +def test_v2_to_json_still_includes_attributes() -> None: + """``to_json()`` is the bundled in-memory form and keeps attributes.""" + out: dict[str, object] = dict(ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_json()) + assert out["attributes"] == {"a": 1} + + +# --- arrays_to_tuples helper ---------------------------------------------- + +ARRAYS_TO_TUPLES_CASES = [ + Expect([1, 2, 3], (1, 2, 3), id="top-level-list"), + Expect({"a": [1, [2, 3]], "b": "x"}, {"a": (1, (2, 3)), "b": "x"}, id="nested-in-dict"), + Expect(5, 5, id="scalar-int"), + Expect("s", "s", id="scalar-str"), + Expect(None, None, id="scalar-none"), + Expect( + {"name": "bytes", "configuration": {"nums": [1, 2]}}, + {"name": "bytes", "configuration": {"nums": (1, 2)}}, + id="dict-keys-preserved", + ), +] + + +@pytest.mark.parametrize("case", ARRAYS_TO_TUPLES_CASES, ids=lambda c: c.id) +def test_arrays_to_tuples(case: Expect[object, object]) -> None: + """arrays_to_tuples recursively converts JSON arrays to tuples.""" + assert arrays_to_tuples(case.input) == case.output + + +# --- ZarrV3ArrayMetadata.from_json ---------------------------------------- + + +def test_v3_from_json_reconstructs_required_fields() -> None: + """V3 from_json reconstructs the required fields from a document.""" + doc = ZarrV3ArrayMetadata.create_default( + shape=(7,), + attributes={"a": 1}, + data_type=ZarrV3NamedConfig(name="int32", configuration={}), + ).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.shape == (7,) + assert model.data_type == ZarrV3NamedConfig(name="int32", configuration={}) + assert model.attributes == {"a": 1} + + +def test_v3_from_json_defaults_for_omitted_optionals() -> None: + """V3 from_json supplies defaults for omitted optional fields.""" + doc = ZarrV3ArrayMetadata.create_default( + attributes={}, storage_transformers=(), dimension_names=UNSET + ).to_json() + # to_json omits these entirely; from_json must restore defaults + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.attributes == {} + assert model.storage_transformers == () + assert model.dimension_names is UNSET + + +def test_v3_from_json_routes_unknown_keys_to_extra_fields() -> None: + """V3 from_json routes unknown top-level keys into extra_fields.""" + doc = ZarrV3ArrayMetadata.create_default( + extra_fields={"my_ext": {"must_understand": False}} + ).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.extra_fields == {"my_ext": {"must_understand": False}} + + +def test_v3_from_json_standard_keys_not_in_extra_fields() -> None: + """V3 from_json keeps standard keys out of extra_fields.""" + doc = ZarrV3ArrayMetadata.create_default( + shape=(10,), attributes={"a": 1}, dimension_names=("x",) + ).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.extra_fields == {} + + +def test_v3_from_json_nested_arrays_in_attributes_become_tuples() -> None: + """V3 from_json converts nested arrays in attributes into tuples.""" + doc = ZarrV3ArrayMetadata.create_default(attributes={"scale": [[1, 2], [3, 4]]}).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.attributes == {"scale": ((1, 2), (3, 4))} + + +# --- ZarrV3ArrayMetadata.from_key_value ---------------------------------- + + +def test_v3_from_key_value_parses_zarr_json() -> None: + """V3 from_key_value parses the zarr.json entry into a model.""" + kv = ZarrV3ArrayMetadata.create_default(shape=(3,)).to_key_value() + model = ZarrV3ArrayMetadata.from_key_value(kv) + assert model.shape == (3,) + + +# --- Cluster 2: from_key_value missing-key raises (parametrized) ----------- + +FROM_KEY_VALUE_MISSING_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ExpectFail({}, MetadataValidationError, id="v3-missing-zarr-json", msg="missing store key"), + id="v3-missing-zarr-json", + ), + pytest.param( + ZarrV2ArrayMetadata, + ExpectFail({}, MetadataValidationError, id="v2-missing-zarray", msg="missing store key"), + id="v2-missing-zarray", + ), +] + + +@pytest.mark.parametrize(("model_cls", "case"), FROM_KEY_VALUE_MISSING_PARAMS) +def test_from_key_value_missing_key_raises( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], + case: ExpectFail[dict[str, bytes]], +) -> None: + """from_key_value raises MetadataValidationError when the required store key is absent.""" + with case.raises(): + model_cls.from_key_value(case.input) + + +# --- Cluster 1: round-trips (model → json → model, parametrized) ----------- + +ROUNDTRIP_MODEL_JSON_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadata.create_default( + shape=(10,), + attributes={"a": 1}, + dimension_names=("x",), + storage_transformers=(ZarrV3NamedConfig(name="t", configuration={}),), + extra_fields={"ext": {"must_understand": False}}, + ), + id="v3-full", + ), + pytest.param( + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadata.create_default( + attributes={}, + dimension_names=UNSET, + storage_transformers=(), + extra_fields={}, + ), + id="v3-empty-optionals", + ), + pytest.param( + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadata.create_default(attributes={"a": 1}, filters=None, compressor=None), + id="v2-basic", + ), +] + + +@pytest.mark.parametrize(("model_cls", "model"), ROUNDTRIP_MODEL_JSON_PARAMS) +def test_roundtrip_model_json_model( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], + model: ZarrV3ArrayMetadata | ZarrV2ArrayMetadata, +) -> None: + """A model round-trips through to_json/from_json back to an equal model.""" + assert model_cls.from_json(model.to_json()) == model + + +# --- Round-trips (model → key_value → model, parametrized) ----------------- + +ROUNDTRIP_KEY_VALUE_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadata.create_default(attributes={"a": 1}), + id="v3", + ), + pytest.param( + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadata.create_default(attributes={"a": 1}), + id="v2", + ), +] + + +@pytest.mark.parametrize(("model_cls", "model"), ROUNDTRIP_KEY_VALUE_PARAMS) +def test_roundtrip_via_key_value( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], + model: ZarrV3ArrayMetadata | ZarrV2ArrayMetadata, +) -> None: + """A model round-trips through to_key_value/from_key_value back to an equal model.""" + assert model_cls.from_key_value(model.to_key_value()) == model + + +# --- Round-trips (json → model → json, direction distinct — kept direct) --- + + +def test_v3_roundtrip_json_model_json() -> None: + """A v3 document round-trips through from_json/to_json back to an equal document.""" + doc = ZarrV3ArrayMetadata.create_default( + shape=(10,), attributes={"a": 1}, dimension_names=("x",) + ).to_json() + assert ZarrV3ArrayMetadata.from_json(doc).to_json() == doc + + +def test_v2_roundtrip_json_model_json() -> None: + """A v2 document round-trips through from_json/to_json back to an equal document.""" + doc = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_json() + assert ZarrV2ArrayMetadata.from_json(doc).to_json() == doc + + +# --- to_json shares no mutable state with the model ------------------------ + +TO_JSON_NO_ALIASING_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata.create_default( + shape=(2,), + attributes={"a": {"b": [1]}}, + codecs=(ZarrV3NamedConfig(name="blosc", configuration={"opts": {"level": 1}}),), + extra_fields={"ext": {"must_understand": False, "cfg": {"x": [1]}}}, + ), + id="v3", + ), + pytest.param( + ZarrV2ArrayMetadata.create_default( + attributes={"a": {"b": [1]}}, + compressor={"id": "zstd", "opts": {"level": 1}}, + filters=({"id": "delta", "cfg": [1]},), + fill_value=[0, 0], + ), + id="v2", + ), +] + + +@pytest.mark.parametrize("model", TO_JSON_NO_ALIASING_PARAMS) +def test_to_json_shares_no_mutable_state_with_model( + model: ZarrV3ArrayMetadata | ZarrV2ArrayMetadata, +) -> None: + """Mutating a document returned by to_json leaves the model unchanged.""" + baseline = copy.deepcopy(model.to_json()) + mutate_nested_containers(model.to_json()) + assert model.to_json() == baseline + + +def test_v3_parser_accepts_bare_string_data_type() -> None: + """V3 from_json accepts a bare-string data_type and re-serializes it canonically.""" + doc = ZarrV3ArrayMetadata.create_default().to_json() + doc["data_type"] = "int32" + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.data_type == ZarrV3NamedConfig(name="int32", configuration={}) + assert model.to_json()["data_type"] == "int32" + + +@pytest.mark.parametrize("name", ["bytes", "ANY string", "urn:example:codec"]) +def test_metadata_field_accepts_any_string_name(name: str) -> None: + """The structural layer checks the name type, not syntax or registration.""" + assert validate_metadata_field_v3({"name": name}) == [] + + +@pytest.mark.parametrize("value", [0, 1, "false", None]) +def test_metadata_field_must_understand_must_be_boolean(value: object) -> None: + """must_understand is a JSON boolean, not a truthy scalar.""" + problems = validate_metadata_field_v3({"name": "x", "must_understand": value}) + assert [(problem.loc, problem.kind) for problem in problems] == [ + (("must_understand",), "invalid_type") + ] + + +def test_metadata_field_rejects_unknown_envelope_member() -> None: + """Unknown envelope keys cannot be silently discarded during normalization.""" + problems = validate_metadata_field_v3({"name": "x", "typo": 1}) + assert [(problem.loc, problem.kind) for problem in problems] == [(("typo",), "invalid_value")] + + +@pytest.mark.parametrize("field", ["codecs", "storage_transformers"]) +def test_optional_extension_points_allow_must_understand_false(field: str) -> None: + """Codecs and storage transformers may be explicitly ignorable.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc[field] = ({"name": "optional", "must_understand": False},) + assert validate_array_metadata_v3(doc) == [] + + +@pytest.mark.parametrize("field", ["data_type", "chunk_grid", "chunk_key_encoding"]) +def test_required_extension_points_reject_must_understand_false(field: str) -> None: + """Core extension points needed to locate or decode chunks cannot be ignored.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc[field] = {"name": "optional", "must_understand": False} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + ((field, "must_understand"), "invalid_value") + ] + + +def test_v3_codecs_cannot_be_empty() -> None: + """The core document requires at least one array-to-bytes codec.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["codecs"] = () + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + (("codecs",), "invalid_value") + ] + + +def test_v2_roundtrip_with_compressor_and_filters() -> None: + # Non-None compressor/filters must round-trip; extra assertion on .compressor. + """A v2 model with non-None compressor and filters round-trips.""" + compressor: ZarrV2CodecMetadata = {"id": "blosc", "clevel": 5} + filters: tuple[ZarrV2CodecMetadata, ...] = ({"id": "delta"},) + m = ZarrV2ArrayMetadata.create_default(compressor=compressor, filters=filters) + restored = ZarrV2ArrayMetadata.from_json(m.to_json()) + assert restored == m + assert restored.compressor == {"id": "blosc", "clevel": 5} + + +# --- ZarrV2ArrayMetadata.from_json ---------------------------------------- + + +def test_v2_from_json_reconstructs_fields() -> None: + """V2 from_json reconstructs the fields from a document.""" + doc = ZarrV2ArrayMetadata.create_default(shape=(4,), attributes={"a": 1}, dtype=" None: + """V2 from_json reads an absent attributes key as UNSET, distinct from an + explicit empty mapping.""" + absent = ZarrV2ArrayMetadata.from_json(ZarrV2ArrayMetadata.create_default().to_json()) + explicit = ZarrV2ArrayMetadata.from_json( + ZarrV2ArrayMetadata.create_default(attributes={}).to_json() + ) + assert absent.attributes is UNSET + assert explicit.attributes == {} + assert absent != explicit + + +# --- ZarrV2ArrayMetadata.from_key_value -------------------------------- + + +def test_v2_from_key_value_remerges_zattrs() -> None: + """V2 from_key_value re-merges .zattrs back into attributes.""" + kv = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}, shape=(10,)).to_key_value() + model = ZarrV2ArrayMetadata.from_key_value(kv) + assert model.attributes == {"a": 1} + assert model.shape == (10,) + + +@pytest.mark.parametrize("extra_key", ["attributes", "vendor_extension"]) +def test_v2_from_key_value_rejects_zarray_extra_members(extra_key: str) -> None: + """Raw `.zarray` documents reject every non-spec member.""" + doc: dict[str, object] = dict(ZarrV2ArrayMetadata.create_default().to_json()) + doc.pop("attributes", None) + doc[extra_key] = {} + + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ArrayMetadata.from_key_value({".zarray": json.dumps(doc).encode()}) + + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((extra_key,), "invalid_value") + ] + + +def test_v2_zattrs_presence_round_trips() -> None: + """The .zattrs file's presence is part of the store: an absent file reads + as UNSET and emits no .zattrs; an explicit empty file reads as {} and + emits .zattrs — the two stores stay distinct through a round-trip.""" + explicit_kv = dict(ZarrV2ArrayMetadata.create_default(attributes={}).to_key_value()) + assert ".zattrs" in explicit_kv + absent_kv = dict(explicit_kv) + del absent_kv[".zattrs"] + + absent = ZarrV2ArrayMetadata.from_key_value(absent_kv) + explicit = ZarrV2ArrayMetadata.from_key_value(explicit_kv) + assert absent.attributes is UNSET + assert explicit.attributes == {} + assert ".zattrs" not in absent.to_key_value() + assert ".zattrs" in explicit.to_key_value() + + +def test_v2_from_json_nested_arrays_in_attributes_become_tuples() -> None: + """V2 from_json converts nested arrays in attributes into tuples.""" + doc = ZarrV2ArrayMetadata.create_default(attributes={"axes": [[0, 1], [2, 3]]}).to_json() + model = ZarrV2ArrayMetadata.from_json(doc) + assert model.attributes == {"axes": ((0, 1), (2, 3))} + + +# --- scalar wire-type guards (is_/validate_/parse_) ------------------------ +# +# Each value is modelled once as Expect[object, frozenset[tuple[str | int, ...]]] +# where `output` is the set of expected problem locs validate_* must report — +# frozenset() means VALID. Valid iff output == frozenset(). + +JSON_VALIDATE_CASES: list[Expect[object, frozenset[tuple[str | int, ...]]]] = [ + Expect("s", frozenset(), id="str"), + Expect(1, frozenset(), id="int"), + Expect(1.5, frozenset(), id="float"), + Expect(True, frozenset(), id="bool"), + Expect(None, frozenset(), id="none"), + Expect({"a": [1, {"b": None}], "c": "x"}, frozenset(), id="nested-containers"), + Expect((1, 2, 3), frozenset(), id="tuple-array"), + Expect(float("nan"), frozenset({()}), id="nan"), + Expect(float("inf"), frozenset({()}), id="inf"), + Expect(float("-inf"), frozenset({()}), id="negative-inf"), + Expect(object(), frozenset({()}), id="object"), + Expect(b"abc", frozenset({()}), id="bytes"), + Expect(bytearray(b"abc"), frozenset({()}), id="bytearray"), + Expect({1: "x"}, frozenset({()}), id="non-str-key"), + Expect([1, object()], frozenset({(1,)}), id="non-json-list-item"), + Expect({"ok": object()}, frozenset({("ok",)}), id="non-json-value"), +] + + +@pytest.mark.parametrize("case", JSON_VALIDATE_CASES, ids=lambda c: c.id) +def test_is_json(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """is_json reports whether a value is JSON-serializable.""" + assert is_json(case.input) is (case.output == frozenset()) + + +@pytest.mark.parametrize("case", JSON_VALIDATE_CASES, ids=lambda c: c.id) +def test_validate_json(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """validate_json reports the problems (and their locs) for a value.""" + problems = validate_json(case.input) + assert (problems == []) is (case.output == frozenset()) + assert {p.loc for p in problems} >= case.output + + +@pytest.mark.parametrize("case", JSON_VALIDATE_CASES, ids=lambda c: c.id) +def test_parse_json(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """parse_json returns valid JSON values and raises on invalid ones.""" + if case.output == frozenset(): + parsed = parse_json(case.input) + assert arrays_to_tuples(parsed) == arrays_to_tuples(case.input) + else: + with pytest.raises(MetadataValidationError): + parse_json(case.input) + + +def test_parse_json_materializes_abstract_containers() -> None: + """Accepted Mapping and Sequence values normalize to JSON encoder containers.""" + value = UserDict({"values": range(3)}) + + parsed = parse_json(value) + + assert parsed == {"values": (0, 1, 2)} + assert type(parsed) is dict + assert type(parsed["values"]) is tuple + json.dumps(parsed, allow_nan=False) + + +def test_json_type_guard_rejects_abstract_sequence() -> None: + """A guard cannot narrow an abstract sequence that only the parser materializes.""" + assert not is_json(range(3)) + assert parse_json(range(3)) == (0, 1, 2) + + +def test_parse_metadata_field_materializes_abstract_containers() -> None: + """Named-config parsing produces canonical containers at every nesting level.""" + value = UserDict({"name": "example", "configuration": UserDict({"values": range(2)})}) + + parsed = parse_metadata_field_v3(value) + + assert isinstance(parsed, dict) + assert parsed == {"name": "example", "configuration": {"values": (0, 1)}} + assert type(parsed["configuration"]) is dict + + +def test_metadata_field_type_guard_rejects_abstract_mapping() -> None: + """A metadata-field guard only narrows concrete TypedDict-shaped objects.""" + value = UserDict({"name": "bytes"}) + + assert not is_metadata_field_v3(value) + assert parse_metadata_field_v3(value) == {"name": "bytes"} + + +def test_validate_json_reports_json_in_message() -> None: + """validate_json's message for a non-JSON value mentions JSON.""" + problems = validate_json(object()) + assert problems[0].loc == () + assert "JSON" in problems[0].message + + +METADATA_FIELD_VALIDATE_CASES: list[Expect[object, frozenset[tuple[str | int, ...]]]] = [ + Expect("bytes", frozenset(), id="bare-string"), + Expect({"name": "x", "configuration": {"a": 1}}, frozenset(), id="named-config"), + Expect({"name": "bytes"}, frozenset(), id="name-only"), + Expect(5, frozenset({()}), id="not-str-or-mapping"), + Expect({"configuration": {}}, frozenset({("name",)}), id="missing-name"), + Expect({"name": 3}, frozenset({("name",)}), id="non-str-name"), + Expect( + {"name": "x", "configuration": [1]}, + frozenset({("configuration",)}), + id="config-not-mapping", + ), + Expect( + {"name": "x", "configuration": {1: "y"}}, + frozenset({("configuration",)}), + id="config-non-str-key", + ), +] + + +@pytest.mark.parametrize("case", METADATA_FIELD_VALIDATE_CASES, ids=lambda c: c.id) +def test_is_metadata_field_v3(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """is_metadata_field_v3 reports whether a value is a v3 metadata field.""" + assert is_metadata_field_v3(case.input) is (case.output == frozenset()) + + +@pytest.mark.parametrize("case", METADATA_FIELD_VALIDATE_CASES, ids=lambda c: c.id) +def test_validate_metadata_field_v3( + case: Expect[object, frozenset[tuple[str | int, ...]]], +) -> None: + """validate_metadata_field_v3 reports the problems for a metadata-field value.""" + problems = validate_metadata_field_v3(case.input) + assert (problems == []) is (case.output == frozenset()) + assert {p.loc for p in problems} >= case.output + + +@pytest.mark.parametrize("case", METADATA_FIELD_VALIDATE_CASES, ids=lambda c: c.id) +def test_parse_metadata_field_v3( + case: Expect[object, frozenset[tuple[str | int, ...]]], +) -> None: + """parse_metadata_field_v3 returns valid fields and raises on invalid ones.""" + if case.output == frozenset(): + assert parse_metadata_field_v3(case.input) is case.input + else: + with pytest.raises(MetadataValidationError): + parse_metadata_field_v3(case.input) + + +# --- array-document wire-type guards (is_/validate_/parse_) ---------------- +# +# Each case starts from a valid document (built by `make`) and applies a +# mutation. `expected_locs` are loc paths `validate_*` must report for the +# invalid cases (a subset check, so accumulation of OTHER problems is allowed). + + +def _build_v3(**overrides: Unpack[ZarrV3ArrayMetadataPartial]) -> dict[str, object]: + return dict(ZarrV3ArrayMetadata.create_default(**overrides).to_json()) + + +def _build_v2(**overrides: Unpack[ZarrV2ArrayMetadataPartial]) -> dict[str, object]: + return dict(ZarrV2ArrayMetadata.create_default(**overrides).to_json()) + + +def _mutate(build: Callable[[], dict], mutate: Callable[[dict], object]) -> Callable[[], dict]: + def _factory() -> dict: + doc = build() + mutate(doc) + return doc + + return _factory + + +def _del(key: str) -> Callable[[dict], object]: + return lambda doc: doc.pop(key) + + +def _set(key: str, value: object) -> Callable[[dict], object]: + return lambda doc: doc.__setitem__(key, value) + + +V3_DOC_CASES: list[Expect[Callable[[], object], frozenset[tuple[str | int, ...]]]] = [ + Expect(_build_v3, frozenset(), id="valid"), + Expect( + lambda: _build_v3(shape=(10,), attributes={"a": 1}, dimension_names=("x",)), + frozenset(), + id="valid-with-attributes-and-dim-names", + ), + Expect( + lambda: _build_v3(extra_fields={"my_ext": {"must_understand": False}}), + frozenset(), + id="valid-with-extra-fields", + ), + Expect(_mutate(_build_v3, _del("shape")), frozenset({("shape",)}), id="missing-shape"), + Expect( + _mutate(_build_v3, _set("data_type", 5)), + frozenset({("data_type",)}), + id="bad-data-type", + ), + Expect( + _mutate(_build_v3, _set("shape", "not-a-shape")), + frozenset({("shape",)}), + id="shape-not-sequence", + ), + Expect( + _mutate(_build_v3, _set("shape", [1, "x"])), + frozenset({("shape",)}), + id="shape-non-int-item", + ), + Expect( + _mutate(_build_v3, _set("codecs", (5,))), + frozenset({("codecs", 0)}), + id="bad-codec-entry", + ), + Expect(lambda: [1, 2, 3], frozenset({()}), id="non-mapping-list"), + Expect(lambda: "nope", frozenset({()}), id="non-mapping-str"), + Expect( + _mutate(_mutate(_build_v3, _del("shape")), _set("data_type", 5)), + frozenset({("shape",), ("data_type",)}), + id="missing-shape-and-bad-data-type", + ), +] + +V2_DOC_CASES: list[Expect[Callable[[], object], frozenset[tuple[str | int, ...]]]] = [ + Expect(_build_v2, frozenset(), id="valid"), + Expect(lambda: _build_v2(attributes={"a": 1}), frozenset(), id="valid-with-attributes"), + Expect( + lambda: _build_v2(compressor=None, filters=None), + frozenset(), + id="valid-none-compressor-filters", + ), + Expect( + _mutate(_build_v2, _del("chunks")), + frozenset({("chunks",)}), + id="missing-chunks", + ), + Expect( + _mutate(_build_v2, _set("shape", [1, "x"])), + frozenset({("shape",)}), + id="bad-shape", + ), + Expect( + _mutate(_mutate(_build_v2, _del("chunks")), _set("shape", [1, "x"])), + frozenset({("chunks",), ("shape",)}), + id="missing-chunks-and-bad-shape", + ), +] + +ALL_DOC_CASES = [ + *( + pytest.param( + is_array_metadata_v3, + validate_array_metadata_v3, + parse_array_metadata_v3, + c, + id=f"v3-{c.id}", + ) + for c in V3_DOC_CASES + ), + *( + pytest.param( + is_array_metadata_v2, + validate_array_metadata_v2, + parse_array_metadata_v2, + c, + id=f"v2-{c.id}", + ) + for c in V2_DOC_CASES + ), +] + + +@pytest.mark.parametrize(("is_fn", "validate_fn", "parse_fn", "case"), ALL_DOC_CASES) +def test_array_metadata_guards( + is_fn: Callable[[object], bool], + validate_fn: Callable[[object], list[ValidationProblem]], + parse_fn: Callable[[object], object], + case: Expect[Callable[[], object], frozenset[tuple[str | int, ...]]], +) -> None: + """is_/validate_/parse_ array-metadata guards agree on validity and locs for each case.""" + doc = case.input() + valid = case.output == frozenset() + assert is_fn(doc) is valid + problems = validate_fn(doc) + assert (problems == []) is valid + assert {p.loc for p in problems} >= case.output + if valid: + assert parse_fn(doc) is doc + else: + with pytest.raises(MetadataValidationError): + parse_fn(doc) + + +# --- strict from_json validation ------------------------------------------- + + +FROM_JSON_REJECT_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ExpectFail(lambda: {"zarr_format": 3}, MetadataValidationError, id="x"), + id="v3-missing-required", + ), + pytest.param( + ZarrV3ArrayMetadata, + ExpectFail(_mutate(_build_v3, _set("data_type", 5)), MetadataValidationError, id="x"), + id="v3-bad-field-type", + ), + pytest.param( + ZarrV2ArrayMetadata, + ExpectFail(lambda: {"zarr_format": 2}, MetadataValidationError, id="x"), + id="v2-missing-required", + ), + pytest.param( + ZarrV3NamedConfig, + ExpectFail(lambda: 5, MetadataValidationError, id="x"), + id="zarr-metadata-bad-input", + ), +] + + +@pytest.mark.parametrize(("model", "case"), FROM_JSON_REJECT_PARAMS) +def test_from_json_rejects_malformed( + model: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata | ZarrV3NamedConfig], + case: ExpectFail[Callable[[], object]], +) -> None: + """from_json raises MetadataValidationError on a malformed document.""" + with case.raises(): + model.from_json(case.input()) + + +# --- ValidationProblem / MetadataValidationError / _prefix ----------------- +# Small structural tests — not "parametrize over inputs" shaped, kept direct. + + +def test_validation_problem_str_with_loc() -> None: + """ValidationProblem.__str__ renders a non-empty loc as a dotted path.""" + p = ValidationProblem(loc=("codecs", 0, "name"), message="expected str", kind="invalid_type") + assert str(p) == "codecs.0.name: expected str" + + +def test_validation_problem_str_empty_loc() -> None: + """ValidationProblem.__str__ renders an empty loc as .""" + p = ValidationProblem(loc=(), message="not a mapping", kind="invalid_type") + assert str(p) == ": not a mapping" + + +def test_validation_problem_is_frozen() -> None: + """ValidationProblem is immutable (frozen dataclass).""" + p = ValidationProblem(loc=("shape",), message="x", kind="invalid_type") + with pytest.raises(dataclasses.FrozenInstanceError): + # setattr: assigning to a frozen field is an intentional runtime error, + # spelled dynamically so it is not also a static type error. + setattr(p, "message", "y") # noqa: B010 + + +def test_metadata_validation_error_holds_problems() -> None: + """MetadataValidationError carries its problem list and renders them in its message.""" + problems = [ + ValidationProblem(loc=("shape",), message="missing required key", kind="missing_key"), + ValidationProblem( + loc=("data_type",), message="expected a metadata field", kind="invalid_type" + ), + ] + err = MetadataValidationError(problems) + assert err.problems == problems + assert "shape: missing required key" in str(err) + assert "data_type: expected a metadata field" in str(err) + + +def test_prefix_prepends_loc_head() -> None: + """_prefix prepends a loc head to each problem's loc.""" + problems = [ValidationProblem(loc=("name",), message="expected str", kind="invalid_type")] + prefixed = _prefix(0, problems) + assert prefixed == [ + ValidationProblem(loc=(0, "name"), message="expected str", kind="invalid_type") + ] + + +# --- Stricter v2/v3 field validation and error kinds ------------------------- + + +def test_v2_dtype_must_be_string_or_records() -> None: + """A non-string, non-records v2 dtype is rejected with an invalid_type problem.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dtype": 42} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dtype",), "invalid_type")] + + +def test_v2_structured_dtype_records_accepted() -> None: + """A structured v2 dtype (field records, optionally nested/shaped) validates.""" + dtype = (("a", " None: + """A field record with the wrong arity is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dtype": (("a",),)} + problems = validate_array_metadata_v2(doc) + assert [p.loc for p in problems] == [("dtype",)] + + +def test_v2_order_literal_enforced() -> None: + """An order other than 'C' or 'F' is rejected with an invalid_value problem.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"order": "Q"} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("order",), "invalid_value")] + + +def test_v2_compressor_must_be_codec_or_none() -> None: + """A compressor that is not null or a codec config mapping is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"compressor": "zlib"} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("compressor",), "invalid_type")] + + +def test_v2_compressor_requires_string_id() -> None: + """A compressor mapping without a string id is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"compressor": {"level": 3}} + problems = validate_array_metadata_v2(doc) + assert [p.loc for p in problems] == [("compressor",)] + + +def test_v2_filters_must_be_codec_sequence_or_none() -> None: + """Filters that are not null or a sequence of codec configs are rejected.""" + for bad in (7, (5,), "gzip"): + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"filters": bad} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("filters",), "invalid_type")], bad + + +def test_v2_shape_and_chunks_must_have_equal_rank() -> None: + """Raw v2 metadata requires one chunk length per array dimension.""" + doc = dict(ZarrV2ArrayMetadata.create_default(shape=(2, 3)).to_json()) + doc["chunks"] = (1,) + + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(doc)] == [ + (("chunks",), "invalid_value") + ] + with pytest.raises(MetadataValidationError, match="same number of dimensions"): + ZarrV2ArrayMetadata.from_key_value({".zarray": json.dumps(doc).encode()}) + + +def test_v2_filters_must_be_nonempty_when_present() -> None: + """A non-null v2 filter sequence contains one or more codec configurations.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) + doc["filters"] = () + + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(doc)] == [ + (("filters",), "invalid_value") + ] + with pytest.raises(MetadataValidationError, match="at least one filter"): + ZarrV2ArrayMetadata.from_key_value({".zarray": json.dumps(doc).encode()}) + + +def test_v2_dimension_separator_literal_enforced() -> None: + """A dimension_separator other than '.' or '/' is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dimension_separator": "-"} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dimension_separator",), "invalid_value")] + + +def test_v2_zarr_format_literal_enforced() -> None: + """A v2 document claiming zarr_format 3 is rejected with an invalid_value problem.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"zarr_format": 3} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("zarr_format",), "invalid_value")] + + +def test_v3_zarr_format_literal_enforced() -> None: + """A v3 document claiming zarr_format 2 is rejected with an invalid_value problem.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"zarr_format": 2} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("zarr_format",), "invalid_value")] + + +@pytest.mark.parametrize( + ("document", "validate"), + [ + pytest.param( + dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"zarr_format": 2.0}, + validate_array_metadata_v2, + id="v2", + ), + pytest.param( + dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"zarr_format": 3.0}, + validate_array_metadata_v3, + id="v3", + ), + ], +) +def test_array_zarr_format_rejects_float( + document: object, validate: Callable[[object], list[ValidationProblem]] +) -> None: + """Integer-valued floats do not satisfy integer format literals.""" + assert [(p.loc, p.kind) for p in validate(document)] == [(("zarr_format",), "invalid_value")] + + +def test_array_v2_rejects_unknown_document_member() -> None: + """The closed v2 merged-document shape rejects undeclared members.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"unexpected": 1} + + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(doc)] == [ + (("unexpected",), "invalid_value") + ] + + +def test_array_v3_from_json_materializes_abstract_containers() -> None: + """A flexible input mapping becomes the canonical dict/tuple model shape.""" + doc = UserDict(dict(ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json())) + doc["shape"] = range(2) + + model = ZarrV3ArrayMetadata.from_json(doc) + + assert model.shape == (0, 1) + assert type(model.shape) is tuple + + +def test_from_key_value_rejects_non_standard_json_constant() -> None: + """Store JSON decoding rejects JavaScript NaN/Infinity constants.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["fill_value"] = float("nan") + raw = json.dumps(doc) + + with pytest.raises(MetadataValidationError, match="invalid JSON"): + ZarrV3ArrayMetadata.from_key_value({"zarr.json": raw.encode()}) + + +def test_to_key_value_rejects_non_finite_model_value() -> None: + """Strict encoding prevents directly-constructed models from writing invalid JSON.""" + model = ZarrV3ArrayMetadata.create_default(fill_value=float("nan")) + + with pytest.raises(ValueError, match="JSON compliant"): + model.to_key_value() + + +def test_v3_node_type_literal_enforced() -> None: + """A v3 array document claiming node_type 'group' is rejected.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"node_type": "group"} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("node_type",), "invalid_value")] + + +def test_missing_key_kind_is_machine_readable() -> None: + """A missing required key is distinguishable by kind, without message matching.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + del doc["chunk_key_encoding"] + problems = validate_array_metadata_v3(doc) + assert problems == [ + ValidationProblem(("chunk_key_encoding",), "missing required key", "missing_key") + ] + + +# --- Unified error channels --------------------------------------------------- + + +def test_from_key_value_invalid_json_raises_metadata_error() -> None: + """Undecodable store bytes raise MetadataValidationError (kind invalid_json), not JSONDecodeError.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV3ArrayMetadata.from_key_value({"zarr.json": b"{not json"}) + assert [p.kind for p in exc_info.value.problems] == ["invalid_json"] + + +def test_from_key_value_invalid_utf8_raises_metadata_error() -> None: + """Invalid UTF-8 store bytes use the same invalid_json error channel.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV3ArrayMetadata.from_key_value({"zarr.json": b"\x80"}) + assert [p.kind for p in exc_info.value.problems] == ["invalid_json"] + + +def test_v2_from_key_value_scalar_root_raises_metadata_error() -> None: + """A scalar .zarray document fails through the unified metadata error channel.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ArrayMetadata.from_key_value({".zarray": b"null"}) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((), "invalid_type") + ] + + +def test_from_key_value_missing_key_kind() -> None: + """A missing store key surfaces as a missing_key problem at the store-key loc.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ArrayMetadata.from_key_value({}) + assert exc_info.value.problems == [ + ValidationProblem((".zarray",), "missing store key", "missing_key") + ] + + +def test_extra_fields_overlap_raises_metadata_error() -> None: + """The extra-fields overlap invariant raises MetadataValidationError (a ValueError).""" + with pytest.raises(MetadataValidationError, match="Extra fields") as exc_info: + ZarrV3ArrayMetadata.create_default(extra_fields={"shape": {"must_understand": False}}) + assert [p.kind for p in exc_info.value.problems] == ["invalid_value"] + + +def test_extension_point_fields_annotated_with_role_alias() -> None: + """Extension-point fields are annotated with ZarrV3MetadataField (the + logical role), not ZarrV3NamedConfig (the current serialized form), so a + future widening of the field union does not move annotation sites.""" + assert ZarrV3MetadataField is ZarrV3NamedConfig + annotations = ZarrV3ArrayMetadata.__annotations__ + for field_name in ("data_type", "chunk_grid", "chunk_key_encoding"): + assert annotations[field_name] == "ZarrV3MetadataField" + for field_name in ("codecs", "storage_transformers"): + assert annotations[field_name] == "tuple[ZarrV3MetadataField, ...]" + + +# --- Adversarial-probe fixes: documents that used to pass validation --------- + + +def test_shape_rejects_json_booleans() -> None: + """JSON booleans are not integers: shape/chunks containing true/false are + rejected (bool is an int subclass in Python, so isinstance alone passes).""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": (True, True)} + assert [p.loc for p in validate_array_metadata_v3(v3)] == [("shape",)] + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": (True,)} + assert [p.loc for p in validate_array_metadata_v2(v2)] == [("chunks",)] + + +def test_shape_rejects_negative_dimensions() -> None: + """Dimension lengths must be non-negative; a negative entry is invalid_value.""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": (-1,)} + assert [(p.loc, p.kind) for p in validate_array_metadata_v3(v3)] == [ + (("shape",), "invalid_value") + ] + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": (-5,)} + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(v2)] == [ + (("chunks",), "invalid_value") + ] + + +def test_dimension_names_length_must_match_shape() -> None: + """dimension_names must have one entry per dimension of shape.""" + doc = dict(ZarrV3ArrayMetadata.create_default(shape=(10,)).to_json()) | { + "dimension_names": ("x", "y", "z") + } + assert [(p.loc, p.kind) for p in validate_array_metadata_v3(doc)] == [ + (("dimension_names",), "invalid_value") + ] + + +def test_attributes_values_must_be_json() -> None: + """Attribute values are JSON-checked recursively (like fill_value), so a + non-serializable value is a validation problem, not a later TypeError.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"attributes": {"a": {1, 2}}} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("attributes", "a"), "invalid_type")] + + +def test_configuration_values_must_be_json() -> None: + """Configuration values are JSON-checked recursively, so an int-keyed dict + cannot pass validation and be silently rewritten by json.dumps.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | { + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": {1: 2}}} + } + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [ + (("chunk_grid", "configuration", "chunk_shape"), "invalid_type") + ] + + +def test_v3_extension_keys_must_be_strings() -> None: + """A non-string top-level key cannot be represented by a v3 document type.""" + doc: dict[object, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc[1] = {"must_understand": False} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + ((), "invalid_type") + ] + + +def test_v3_extension_values_must_be_json() -> None: + """Extension payloads are JSON-checked before a model is constructed.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["ext"] = {"must_understand": False, "payload": object()} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + (("ext", "payload"), "invalid_type") + ] + + +def test_v3_json_extension_without_waiver_is_preserved_as_must_understand() -> None: + """A JSON extension without an explicit false waiver remains must-understand.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["ext"] = 1 + parsed = parse_array_metadata_v3(doc) + assert is_array_metadata_v3(parsed) + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.extra_fields["ext"] == 1 + assert model.must_understand_fields == {"ext": 1} + + +def test_v2_codec_configuration_values_must_be_json() -> None: + """Non-JSON codec parameters are rejected for compressors and filters.""" + for field, value, expected_loc in ( + ("compressor", {"id": "x", "payload": object()}, ("compressor", "payload")), + ("filters", ({"id": "x", "payload": object()},), ("filters", 0, "payload")), + ): + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) + doc[field] = value + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v2(doc)] == [ + (expected_loc, "invalid_type") + ] + + +def test_dimension_sequences_reject_binary_values() -> None: + """Binary buffers are not JSON arrays even though they are integer sequences.""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": b"\x02"} + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": b"\x02"} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(v3)] == [ + (("shape",), "invalid_type") + ] + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v2(v2)] == [ + (("chunks",), "invalid_type") + ] + + +def test_array_parsers_normalize_json_lists_before_narrowing() -> None: + """Parsers return tuple-backed document types while guards reject raw list forms.""" + v3_raw = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json())) + v2_raw = json.loads(json.dumps(ZarrV2ArrayMetadata.create_default(shape=(2,)).to_json())) + + assert validate_array_metadata_v3(v3_raw) == [] + assert validate_array_metadata_v2(v2_raw) == [] + assert not is_array_metadata_v3(v3_raw) + assert not is_array_metadata_v2(v2_raw) + + v3_parsed = parse_array_metadata_v3(v3_raw) + v2_parsed = parse_array_metadata_v2(v2_raw) + assert isinstance(v3_parsed["shape"], tuple) + assert isinstance(v3_parsed["codecs"], tuple) + assert isinstance(v2_parsed["shape"], tuple) + assert isinstance(v2_parsed["chunks"], tuple) + + +def test_array_guards_reject_noncanonical_nested_json() -> None: + """Document guards cannot narrow values that only parsers can materialize.""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) + v3["fill_value"] = range(2) + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) + v2["fill_value"] = range(2) + + assert not is_array_metadata_v3(v3) + assert not is_array_metadata_v2(v2) + assert parse_array_metadata_v3(v3)["fill_value"] == (0, 1) + assert parse_array_metadata_v2(v2)["fill_value"] == (0, 1) + + +# --- must_understand partition (spec: MUST fail to open unrecognized fields) -- + + +def test_must_understand_fields_partition() -> None: + """must_understand_fields contains every extra field not explicitly waived + with must_understand: false, including implicitly-true and non-mapping + fields, so a reader can discharge the spec's fail-to-open duty by + subtracting the extensions it recognizes.""" + model = ZarrV3ArrayMetadata.create_default( + extra_fields={ + "ext_a": {"name": "a", "must_understand": False}, + "ext_b": {"name": "b"}, + "ext_c": {"name": "c", "must_understand": True}, + "ext_d": 123, + } + ) + assert set(model.must_understand_fields) == {"ext_b", "ext_c", "ext_d"} + recognized = {"ext_b"} + assert model.must_understand_fields.keys() - recognized == {"ext_c", "ext_d"} + + +def test_must_understand_fields_empty_when_all_waived() -> None: + """must_understand_fields is empty when every extra field is explicitly waived.""" + model = ZarrV3ArrayMetadata.create_default( + extra_fields={"ext_a": {"name": "a", "must_understand": False}} + ) + assert model.must_understand_fields == {} + + +def test_dimension_names_null_field_rejected() -> None: + """A dimension_names field whose VALUE is null is invalid: the spec permits + null as an element (an unnamed dimension), never as the field value — "not + specified" is spelled by omitting the key. Consumers bridging from an + in-memory None sentinel must drop the key, not write null.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"dimension_names": None} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dimension_names",), "invalid_type")] + # and the model's own None spelling correctly maps to key absence + assert ( + "dimension_names" not in ZarrV3ArrayMetadata.create_default(dimension_names=UNSET).to_json() + ) + + +# --- create_default derives the chunk grid from shape ------------------------ + + +def test_v3_create_default_chunk_grid_follows_shape() -> None: + """Overriding shape without chunk_grid derives a consistent default grid: + one chunk covering the array (chunk_shape == shape), instead of silently + keeping the scalar default's 0-d grid.""" + model = ZarrV3ArrayMetadata.create_default(shape=(100, 100)) + assert model.chunk_grid == ZarrV3NamedConfig( + name="regular", configuration={"chunk_shape": (100, 100)} + ) + + +def test_v3_create_default_explicit_chunk_grid_respected() -> None: + """An explicit chunk_grid override wins over the shape-derived default.""" + grid = ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": (10, 10)}) + model = ZarrV3ArrayMetadata.create_default(shape=(100, 100), chunk_grid=grid) + assert model.chunk_grid == grid + + +def test_v2_create_default_chunks_follow_shape() -> None: + """Overriding shape without chunks derives chunks == shape.""" + model = ZarrV2ArrayMetadata.create_default(shape=(100, 100)) + assert model.chunks == (100, 100) + + +def test_v2_create_default_explicit_chunks_respected() -> None: + """An explicit chunks override wins over the shape-derived default.""" + model = ZarrV2ArrayMetadata.create_default(shape=(100, 100), chunks=(10, 10)) + assert model.chunks == (10, 10) + + +def test_v3_create_default_zero_length_dimensions() -> None: + """chunk_shape == shape is spec-sound even with zero-length dimensions: + 'The chunk shape elements are non-zero when the corresponding dimensions + of the arrays have non-zero length' — the constraint is conditional, so a + zero chunk length is permitted exactly where the dimension is empty.""" + model = ZarrV3ArrayMetadata.create_default(shape=(0, 3)) + assert model.chunk_grid.configuration["chunk_shape"] == (0, 3) + + +def test_create_default_derivation_is_one_way() -> None: + """Overriding the chunk grid (v3) or chunks (v2) without shape leaves the + scalar default shape=() untouched: a user-supplied chunk_grid is an + extension point taken verbatim, and deriving shape from it would require + interpreting grid configurations, which the model layer never does.""" + grid = ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": (10, 10)}) + v3 = ZarrV3ArrayMetadata.create_default(chunk_grid=grid) + assert v3.shape == () + assert v3.chunk_grid == grid + v2 = ZarrV2ArrayMetadata.create_default(chunks=(10, 10)) + assert v2.shape == () + assert v2.chunks == (10, 10) + + +# --- v2 dimension_separator default (roborev job 426) ------------------------- + + +def test_v2_absent_dimension_separator_means_dot() -> None: + """A .zarray that omits dimension_separator uses the v2 convention default + '.', not '/': chunk keys of real-world default-separator v2 arrays look + like '0.0'. The model normalizes the absent key to an explicit '.' — a + semantics-preserving spelling normalization.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) + del doc["dimension_separator"] + model = ZarrV2ArrayMetadata.from_json(doc) + assert model.dimension_separator == "." + assert model.to_json()["dimension_separator"] == "." + + +def test_v2_from_key_value_without_separator_means_dot() -> None: + """The .zarray store-file path applies the same '.' default for an absent + dimension_separator key.""" + doc = { + k: v + for k, v in ZarrV2ArrayMetadata.create_default().to_json().items() + if k not in ("dimension_separator", "attributes") + } + import json as _json + + model = ZarrV2ArrayMetadata.from_key_value({".zarray": _json.dumps(doc).encode()}) + assert model.dimension_separator == "." + + +def test_v2_null_dimension_separator_rejected() -> None: + """dimension_separator may be absent, '.', or '/' — never null: the + document grammar has no null spelling for this field.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dimension_separator": None} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dimension_separator",), "invalid_value")] + + +def test_dimension_names_absent_and_all_null_are_distinct() -> None: + """An absent dimension_names field and an explicit all-null one are + semantically different documents: the explicit form says every dimension + has a name, which is null; absence says there are no dimension names. + The model preserves the distinction (UNSET vs a tuple of Nones), and both + spellings round-trip faithfully.""" + absent_doc = dict(ZarrV3ArrayMetadata.create_default(shape=(2, 3)).to_json()) + explicit_doc = absent_doc | {"dimension_names": (None, None)} + + absent = ZarrV3ArrayMetadata.from_json(absent_doc) + explicit = ZarrV3ArrayMetadata.from_json(explicit_doc) + + assert absent.dimension_names is UNSET + assert explicit.dimension_names == (None, None) + assert absent != explicit + assert "dimension_names" not in absent.to_json() + assert absent.to_json() == absent_doc + assert explicit.to_json() == explicit_doc diff --git a/packages/zarr-metadata/tests/model/test_group.py b/packages/zarr-metadata/tests/model/test_group.py new file mode 100644 index 0000000000..4b8c22b84d --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_group.py @@ -0,0 +1,572 @@ +"""Tests for the group and consolidated metadata models in `zarr_metadata.model`.""" + +import copy +import dataclasses +import json +from collections import UserDict +from collections.abc import Callable + +import pytest + +from tests.model._cases import mutate_nested_containers +from zarr_metadata.model import UNSET +from zarr_metadata.model._array import ZarrV3ArrayMetadata +from zarr_metadata.model._group import ( + ZarrV2ConsolidatedMetadata, + ZarrV2GroupMetadata, + ZarrV2GroupMetadataPartial, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3GroupMetadataPartial, +) +from zarr_metadata.model._validation import ( + MetadataValidationError, + ValidationProblem, + is_group_metadata_v2, + is_group_metadata_v3, + parse_group_metadata_v2, + parse_group_metadata_v3, + validate_group_metadata_v2, + validate_group_metadata_v3, +) + +# --- ZarrV3GroupMetadata --------------------------------------------------- + + +def test_group_v3_roundtrip() -> None: + """A v3 group document round-trips through the model unchanged.""" + doc = {"zarr_format": 3, "node_type": "group", "attributes": {"a": (1, 2)}} + model = ZarrV3GroupMetadata.from_json(doc) + assert model.to_json() == doc + + +def test_group_v3_omits_empty_attributes() -> None: + """to_json omits the attributes key when attributes is empty.""" + model = ZarrV3GroupMetadata.create_default() + assert "attributes" not in model.to_json() + + +def test_group_v3_lists_become_tuples() -> None: + """from_json converts JSON arrays in attributes to tuples.""" + doc = {"zarr_format": 3, "node_type": "group", "attributes": {"a": [1, 2]}} + model = ZarrV3GroupMetadata.from_json(doc) + assert model.attributes == {"a": (1, 2)} + + +def test_group_v3_extra_fields_roundtrip() -> None: + """Unknown top-level keys land in extra_fields and reappear in to_json.""" + doc = { + "zarr_format": 3, + "node_type": "group", + "my_extension": {"name": "thing", "must_understand": False}, + } + model = ZarrV3GroupMetadata.from_json(doc) + assert model.extra_fields == {"my_extension": {"name": "thing", "must_understand": False}} + assert model.to_json() == doc + + +def test_group_v3_json_extra_field_roundtrips_as_must_understand() -> None: + """A non-object extra field is preserved and implicitly requires understanding.""" + doc = {"zarr_format": 3, "node_type": "group", "ext": [1, 2]} + model = ZarrV3GroupMetadata.from_json(doc) + assert model.to_json()["ext"] == (1, 2) + assert model.must_understand_fields == {"ext": (1, 2)} + + +def test_group_v3_extra_fields_overlap_rejected() -> None: + """Constructing a v3 group model with extra_fields shadowing a standard key raises.""" + with pytest.raises(ValueError, match="Extra fields"): + ZarrV3GroupMetadata( + attributes={}, + consolidated_metadata=UNSET, + extra_fields={"node_type": {"name": "x", "must_understand": False}}, + ) + + +def test_group_v3_consolidated_extra_field_rejected() -> None: + """extra_fields may not shadow the consolidated_metadata convention key.""" + with pytest.raises(ValueError, match="Extra fields"): + ZarrV3GroupMetadata( + attributes={}, + consolidated_metadata=UNSET, + extra_fields={"consolidated_metadata": {"name": "x", "must_understand": False}}, + ) + + +def test_group_v3_missing_required_key() -> None: + """parse_group_metadata_v3 reports each missing required key.""" + with pytest.raises(MetadataValidationError, match="node_type"): + parse_group_metadata_v3({"zarr_format": 3}) + + +def test_group_v3_bad_attributes() -> None: + """parse_group_metadata_v3 rejects a non-mapping attributes value.""" + with pytest.raises(MetadataValidationError, match="attributes"): + parse_group_metadata_v3({"zarr_format": 3, "node_type": "group", "attributes": 5}) + + +@pytest.mark.parametrize( + ("document", "validate"), + [ + pytest.param( + {"zarr_format": 2.0}, + validate_group_metadata_v2, + id="v2", + ), + pytest.param( + {"zarr_format": 3.0, "node_type": "group"}, + validate_group_metadata_v3, + id="v3", + ), + ], +) +def test_group_zarr_format_rejects_float( + document: object, validate: Callable[[object], list[ValidationProblem]] +) -> None: + """Integer-valued floats do not satisfy integer format literals.""" + assert [(p.loc, p.kind) for p in validate(document)] == [(("zarr_format",), "invalid_value")] + + +def test_group_v2_rejects_unknown_document_member() -> None: + """The closed v2 merged-document shape rejects undeclared members.""" + assert [(p.loc, p.kind) for p in validate_group_metadata_v2({"zarr_format": 2, "x": 1})] == [ + (("x",), "invalid_value") + ] + + +@pytest.mark.parametrize( + ("parse", "document"), + [ + pytest.param(parse_group_metadata_v2, {"zarr_format": 2}, id="v2"), + pytest.param( + parse_group_metadata_v3, + {"zarr_format": 3, "node_type": "group"}, + id="v3", + ), + ], +) +def test_group_parser_materializes_abstract_mapping( + parse: Callable[[object], object], document: dict[str, object] +) -> None: + """A successful group parser always returns the declared concrete TypedDict shape.""" + parsed = parse(UserDict(document)) + + assert type(parsed) is dict + assert parsed == document + + +def test_group_guards_reject_noncanonical_nested_json() -> None: + """Document guards cannot narrow values that only parsers can materialize.""" + v3 = {"zarr_format": 3, "node_type": "group", "extension": range(2)} + v2 = {"zarr_format": 2, "attributes": {"values": range(2)}} + + assert not is_group_metadata_v3(v3) + assert not is_group_metadata_v2(v2) + assert parse_group_metadata_v3(v3)["extension"] == (0, 1) + assert parse_group_metadata_v2(v2)["attributes"] == {"values": (0, 1)} + + +def test_group_v3_extension_fields_are_validated() -> None: + """Group extension payloads must be JSON values with a must-understand flag.""" + doc = { + "zarr_format": 3, + "node_type": "group", + "ext": {"must_understand": False, "payload": object()}, + } + assert [(problem.loc, problem.kind) for problem in validate_group_metadata_v3(doc)] == [ + (("ext", "payload"), "invalid_type") + ] + + +def test_group_v3_key_value_roundtrip() -> None: + """from_key_value(to_key_value()) is the identity for v3 groups.""" + model = ZarrV3GroupMetadata.create_default(attributes={"a": 1}) + assert ZarrV3GroupMetadata.from_key_value(model.to_key_value()) == model + + +def test_group_v3_update() -> None: + """update replaces the given fields and returns a new instance.""" + base = ZarrV3GroupMetadata.create_default() + updated = base.update(attributes={"a": 1}) + assert updated.attributes == {"a": 1} + assert base.attributes == {} + + +# --- ZarrV2GroupMetadata --------------------------------------------------- + + +def test_group_v2_key_value_split() -> None: + """v2 to_key_value writes .zgroup and .zattrs; from_key_value merges them.""" + model = ZarrV2GroupMetadata.create_default(attributes={"a": 1}) + kv = model.to_key_value() + assert set(kv) == {".zgroup", ".zattrs"} + assert json.loads(kv[".zgroup"]) == {"zarr_format": 2} + assert ZarrV2GroupMetadata.from_key_value(kv) == model + + +@pytest.mark.parametrize("extra_key", ["attributes", "vendor_extension"]) +def test_v2_group_from_key_value_rejects_zgroup_extra_members(extra_key: str) -> None: + """Raw `.zgroup` documents reject every non-spec member.""" + doc: dict[str, object] = {"zarr_format": 2, extra_key: {}} + + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2GroupMetadata.from_key_value({".zgroup": json.dumps(doc).encode()}) + + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((extra_key,), "invalid_value") + ] + + +def test_group_v2_zattrs_presence_round_trips() -> None: + """A v2 group with no .zattrs file parses with UNSET attributes and emits + no .zattrs; an explicit empty .zattrs stays a file — the stores remain + distinct through a round-trip.""" + absent = ZarrV2GroupMetadata.from_key_value({".zgroup": b'{"zarr_format": 2}'}) + assert absent.attributes is UNSET + assert ".zattrs" not in absent.to_key_value() + explicit = ZarrV2GroupMetadata.from_key_value( + {".zgroup": b'{"zarr_format": 2}', ".zattrs": b"{}"} + ) + assert explicit.attributes == {} + assert ".zattrs" in explicit.to_key_value() + assert absent != explicit + + +def test_group_v2_json_roundtrip() -> None: + """A merged-form v2 group document round-trips through the model unchanged.""" + doc = {"zarr_format": 2, "attributes": {"a": 1}} + model = ZarrV2GroupMetadata.from_json(doc) + assert model.to_json() == doc + + +def test_group_v2_omits_empty_attributes() -> None: + """to_json omits the attributes key when attributes is empty.""" + assert "attributes" not in ZarrV2GroupMetadata.create_default().to_json() + + +def test_group_v2_not_a_mapping() -> None: + """parse_group_metadata_v2 rejects a non-mapping document.""" + with pytest.raises(MetadataValidationError, match="expected a mapping"): + parse_group_metadata_v2([1, 2, 3]) + + +def test_group_v2_missing_required_key() -> None: + """parse_group_metadata_v2 reports a missing zarr_format key.""" + with pytest.raises(MetadataValidationError, match="zarr_format"): + parse_group_metadata_v2({}) + + +# --- Partial TypedDict drift guards ----------------------------------------- + + +def test_group_partial_keys_match_settable_model_fields() -> None: + """Each group partial TypedDict must list exactly the settable model fields. + + Guards against drift: adding/removing a settable field on a group model + without updating its `*Partial` TypedDict fails here. + """ + for model_cls, partial_cls in ( + (ZarrV3GroupMetadata, ZarrV3GroupMetadataPartial), + (ZarrV2GroupMetadata, ZarrV2GroupMetadataPartial), + ): + settable = {f.name for f in dataclasses.fields(model_cls) if f.init} + assert set(partial_cls.__annotations__) == settable + + +# --- ZarrV3ConsolidatedMetadata -------------------------------------------- + + +def test_consolidated_v3_roundtrip() -> None: + """A v3 group with inline consolidated metadata round-trips, with child + entries parsed into array/group models.""" + child = ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json() + doc = { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": {"a": child, "g": {"zarr_format": 3, "node_type": "group"}}, + }, + } + model = ZarrV3GroupMetadata.from_json(doc) + assert isinstance(model.consolidated_metadata, ZarrV3ConsolidatedMetadata) + assert isinstance(model.consolidated_metadata.metadata["a"], ZarrV3ArrayMetadata) + assert isinstance(model.consolidated_metadata.metadata["g"], ZarrV3GroupMetadata) + assert model.to_json() == doc + + +def test_consolidated_v3_must_understand_true_rejected() -> None: + """ZarrV3ConsolidatedMetadata enforces must_understand=False at runtime.""" + with pytest.raises(ValueError, match="must_understand"): + ZarrV3ConsolidatedMetadata(must_understand=True, metadata={}) + + +def test_consolidated_v3_from_json_must_understand_true_rejected() -> None: + """from_json rejects a consolidated document carrying must_understand=true.""" + with pytest.raises(MetadataValidationError, match="must_understand"): + ZarrV3ConsolidatedMetadata.from_json( + {"kind": "inline", "must_understand": True, "metadata": {}} + ) + + +def test_consolidated_v3_entry_without_node_type_rejected() -> None: + """from_json rejects a consolidated entry lacking a recognizable node_type.""" + with pytest.raises(MetadataValidationError, match="node_type"): + ZarrV3ConsolidatedMetadata.from_json( + {"kind": "inline", "must_understand": False, "metadata": {"a": {"zarr_format": 3}}} + ) + + +def test_consolidated_v3_not_a_mapping() -> None: + """from_json rejects a non-mapping consolidated document.""" + with pytest.raises(MetadataValidationError, match="expected a mapping"): + ZarrV3ConsolidatedMetadata.from_json(5) + + +# --- ZarrV2ConsolidatedMetadata -------------------------------------------- + + +def test_consolidated_v2_verbatim_roundtrip() -> None: + """The v2 .zmetadata model holds the flat file-keyed map verbatim, + including nodes that have no .zattrs entry.""" + doc = { + "zarr_consolidated_format": 1, + "metadata": { + ".zgroup": {"zarr_format": 2}, + "a/.zarray": { + "zarr_format": 2, + "shape": (2,), + "chunks": (2,), + "dtype": "|u1", + "fill_value": 0, + "order": "C", + "compressor": None, + "filters": None, + }, + }, + } + model = ZarrV2ConsolidatedMetadata.from_json(doc) + assert model.to_json() == doc + + +def test_consolidated_v2_key_value_roundtrip() -> None: + """from_key_value(to_key_value()) is the identity for .zmetadata documents.""" + model = ZarrV2ConsolidatedMetadata.from_json( + {"zarr_consolidated_format": 1, "metadata": {".zgroup": {"zarr_format": 2}}} + ) + assert ZarrV2ConsolidatedMetadata.from_key_value(model.to_key_value()) == model + + +def test_consolidated_v2_lists_become_tuples() -> None: + """from_json converts JSON arrays inside entries to tuples.""" + doc = { + "zarr_consolidated_format": 1, + "metadata": {"a/.zarray": {"shape": [2, 3]}}, + } + model = ZarrV2ConsolidatedMetadata.from_json(doc) + assert model.metadata == {"a/.zarray": {"shape": (2, 3)}} + + +def test_consolidated_v2_envelope_validation() -> None: + """from_json rejects a .zmetadata document missing the metadata key.""" + with pytest.raises(MetadataValidationError, match="metadata"): + ZarrV2ConsolidatedMetadata.from_json({"zarr_consolidated_format": 1}) + + +def test_consolidated_v2_not_a_mapping() -> None: + """from_json rejects a non-mapping .zmetadata document.""" + with pytest.raises(MetadataValidationError, match="expected a mapping"): + ZarrV2ConsolidatedMetadata.from_json([1]) + + +def test_consolidated_v2_format_literal_enforced() -> None: + """A .zmetadata document must declare consolidated format 1.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ConsolidatedMetadata.from_json({"zarr_consolidated_format": 2, "metadata": {}}) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + (("zarr_consolidated_format",), "invalid_value") + ] + + +def test_consolidated_v2_metadata_values_must_be_json() -> None: + """Non-JSON values in the flat metadata map are rejected during ingestion.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ConsolidatedMetadata.from_json( + {"zarr_consolidated_format": 1, "metadata": {".zgroup": object()}} + ) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + (("metadata", ".zgroup"), "invalid_type") + ] + + +def test_group_v2_from_key_value_scalar_root_raises_metadata_error() -> None: + """A scalar .zgroup document fails through the unified metadata error channel.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2GroupMetadata.from_key_value({".zgroup": b"null"}) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((), "invalid_type") + ] + + +# --- Literal-value enforcement ----------------------------------------------- + + +def test_group_v3_literals_enforced() -> None: + """A v3 group doc with wrong zarr_format or node_type is rejected with invalid_value.""" + base = ZarrV3GroupMetadata.create_default().to_json() + for key, bad in (("zarr_format", 2), ("node_type", "array")): + problems = validate_group_metadata_v3(dict(base) | {key: bad}) + assert [(p.loc, p.kind) for p in problems] == [((key,), "invalid_value")], key + + +def test_group_v2_zarr_format_literal_enforced() -> None: + """A v2 group doc claiming zarr_format 3 is rejected with invalid_value.""" + problems = validate_group_metadata_v2({"zarr_format": 3}) + assert [(p.loc, p.kind) for p in problems] == [(("zarr_format",), "invalid_value")] + + +# --- Consolidated envelope validated by the group validator ------------------ + + +def test_group_v3_validator_agrees_with_from_json_on_consolidated() -> None: + """The group validator validates the consolidated envelope and entries, so + is_group_metadata_v3 never vouches for a document from_json would reject.""" + bad_docs = ( + # empty envelope: missing kind/must_understand/metadata + {"zarr_format": 3, "node_type": "group", "consolidated_metadata": {}}, + # entry without a recognizable node_type + { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": {"a": {"zarr_format": 3}}, + }, + }, + # must_understand: true + { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": True, + "metadata": {}, + }, + }, + ) + for doc in bad_docs: + assert validate_group_metadata_v3(doc) != [], doc + with pytest.raises(MetadataValidationError): + ZarrV3GroupMetadata.from_json(doc) + + +def test_group_v3_valid_consolidated_passes_validator() -> None: + """A well-formed consolidated group validates cleanly (control case).""" + child = ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json() + doc = { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": {"a": child, "g": {"zarr_format": 3, "node_type": "group"}}, + }, + } + assert validate_group_metadata_v3(doc) == [] + + +def test_v3_consolidated_rejects_unknown_envelope_member() -> None: + """The inline consolidated envelope is closed and never drops accepted members.""" + doc = { + "kind": "inline", + "must_understand": False, + "metadata": {}, + "unexpected": 1, + } + + with pytest.raises(MetadataValidationError, match="unexpected"): + ZarrV3ConsolidatedMetadata.from_json(doc) + + +def test_v2_consolidated_rejects_unknown_document_member() -> None: + """The v2 consolidated document is closed and never drops accepted members.""" + doc = {"zarr_consolidated_format": 1, "metadata": {}, "unexpected": 1} + + with pytest.raises(MetadataValidationError, match="unexpected"): + ZarrV2ConsolidatedMetadata.from_json(doc) + + +# --- must_understand partition ------------------------------------------------ + + +def test_group_must_understand_fields_partition() -> None: + """The group model partitions extra fields by the spec's implicit-true rule, + like the array model.""" + model = ZarrV3GroupMetadata.create_default( + extra_fields={ + "waived": {"name": "w", "must_understand": False}, + "implicit": {"name": "i"}, + } + ) + assert set(model.must_understand_fields) == {"implicit"} + + +def test_group_v3_null_consolidated_metadata_repaired_to_absence() -> None: + """consolidated_metadata: null was written by a historical zarr-python bug. + Those stores must remain readable, but the bug spelling is not honored: + it is read as absence (UNSET) and never written back — the round-trip + deliberately repairs the document rather than preserving the bug.""" + null_doc = {"zarr_format": 3, "node_type": "group", "consolidated_metadata": None} + assert validate_group_metadata_v3(null_doc) == [] + model = ZarrV3GroupMetadata.from_json(null_doc) + assert model.consolidated_metadata is UNSET + assert "consolidated_metadata" not in model.to_json() + assert model == ZarrV3GroupMetadata.from_json({"zarr_format": 3, "node_type": "group"}) + + +# --- to_json shares no mutable state with the model ------------------------ + +TO_JSON_NO_ALIASING_PARAMS = [ + pytest.param( + ZarrV3GroupMetadata.create_default( + attributes={"a": {"b": [1]}}, + consolidated_metadata=ZarrV3ConsolidatedMetadata( + metadata={ + "child": ZarrV3ArrayMetadata.create_default(attributes={"x": {"y": 1}}), + "grp": ZarrV3GroupMetadata.create_default(attributes={"x": {"y": 1}}), + } + ), + extra_fields={"ext": {"must_understand": False, "cfg": {"x": [1]}}}, + ), + id="v3-group", + ), + pytest.param( + ZarrV2GroupMetadata.create_default(attributes={"a": {"b": [1]}}), + id="v2-group", + ), + pytest.param( + ZarrV3ConsolidatedMetadata( + metadata={"child": ZarrV3ArrayMetadata.create_default(attributes={"x": {"y": 1}})} + ), + id="v3-consolidated", + ), + pytest.param( + ZarrV2ConsolidatedMetadata(metadata={"a/.zarray": {"nested": {"x": [1]}}}), + id="v2-consolidated", + ), +] + + +@pytest.mark.parametrize("model", TO_JSON_NO_ALIASING_PARAMS) +def test_to_json_shares_no_mutable_state_with_model( + model: ZarrV3GroupMetadata + | ZarrV2GroupMetadata + | ZarrV3ConsolidatedMetadata + | ZarrV2ConsolidatedMetadata, +) -> None: + """Mutating a document returned by to_json leaves the model unchanged.""" + baseline = copy.deepcopy(model.to_json()) + mutate_nested_containers(model.to_json()) + assert model.to_json() == baseline diff --git a/packages/zarr-metadata/tests/model/test_pydantic.py b/packages/zarr-metadata/tests/model/test_pydantic.py new file mode 100644 index 0000000000..e5714bb8fb --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_pydantic.py @@ -0,0 +1,302 @@ +"""Executable example: integrating the metadata models with pydantic (v2). + +Pydantic's native dataclass introspection CAN be made to work (see +`test_native_dataclass_introspection_is_possible_but_diverges`): the models +keep their annotation-only imports behind `TYPE_CHECKING`, so a bare +`TypeAdapter(ZarrV3ArrayMetadata)` raises `class-not-fully-defined`, but +`rebuild(_types_namespace=...)` with the names supplied resolves the schema. +It is still the wrong tool: it validates the MODEL SHAPE, not the DOCUMENT — +no `from_json` normalization (a bare-string `data_type` is rejected), and +pydantic's lax coercion silently re-opens holes the library's validators +close (`shape=[True, -5]` coerces to `(1, -5)`; a wrong `dimension_names` +count passes). The recommended integration delegates wholesale — treat the +model as an opaque value: + +- `InstanceOf` makes pydantic's core schema an is-instance check (no field + introspection), +- validation goes through `from_json` (the single source of truth for what + a well-formed document is, including normalization: bare-string metadata + fields, arrays-to-tuples), +- serialization goes through `to_json` (the canonical document form). + +`MetadataValidationError` subclasses `ValueError`, so pydantic converts a +failed parse into its own `ValidationError` with the loc-annotated problem +messages intact. +""" + +from collections.abc import Mapping +from typing import Annotated, Generic, TypeVar + +import pytest +from pydantic import ( + BaseModel, + BeforeValidator, + ConfigDict, + InstanceOf, + PlainSerializer, + PydanticSchemaGenerationError, + PydanticUserError, + TypeAdapter, + ValidationError, + model_validator, +) + +from zarr_metadata import JSONValue +from zarr_metadata.model import ZarrV3ArrayMetadata, ZarrV3NamedConfig + +# --- the integration (this is the example) ----------------------------------- + + +def _as_array_metadata_v3(value: object) -> ZarrV3ArrayMetadata: + """Accept an existing model instance or a raw metadata document.""" + if isinstance(value, ZarrV3ArrayMetadata): + return value + return ZarrV3ArrayMetadata.from_json(value) + + +# return_type is explicit because to_json's own annotation (`ZarrV3ArrayMetadataJSON`) +# is a TYPE_CHECKING-only name pydantic cannot resolve at runtime. +ArrayMetadataV3Field = Annotated[ + InstanceOf[ZarrV3ArrayMetadata], + BeforeValidator(_as_array_metadata_v3), + PlainSerializer(ZarrV3ArrayMetadata.to_json, return_type=dict), +] +"""A pydantic-ready field type for v3 array metadata. + +Validates raw documents via `from_json`, passes model instances through, +and serializes to the canonical document form via `to_json`. +""" + + +class ArrayManifest(BaseModel): + """Example consumer model: a named array with its metadata document.""" + + path: str + metadata: ArrayMetadataV3Field + + +# --- tests pinning the example ------------------------------------------------ + +VALID_DOC = { + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": "uint8", + "fill_value": 0, + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [5]}}, + "chunk_key_encoding": {"name": "default"}, + "codecs": [{"name": "bytes"}], +} + + +def test_raw_document_is_validated_into_a_model() -> None: + """A raw metadata document on a pydantic field is parsed by from_json, + with the library's normalization applied (tuples, canonical field form).""" + manifest = ArrayManifest.model_validate({"path": "a/b", "metadata": VALID_DOC}) + assert isinstance(manifest.metadata, ZarrV3ArrayMetadata) + assert manifest.metadata.shape == (10,) + assert manifest.metadata.data_type.name == "uint8" + + +def test_model_instance_passes_through() -> None: + """An already-constructed model instance is accepted unchanged.""" + model = ZarrV3ArrayMetadata.from_json(VALID_DOC) + manifest = ArrayManifest(path="a/b", metadata=model) + assert manifest.metadata is model + + +def test_invalid_document_surfaces_problems_in_validation_error() -> None: + """A structurally-invalid document fails pydantic validation, carrying the + loc-annotated problem messages from MetadataValidationError.""" + doc = dict(VALID_DOC) + del doc["chunk_key_encoding"] + with pytest.raises(ValidationError) as exc_info: + ArrayManifest.model_validate({"path": "a/b", "metadata": doc}) + assert "chunk_key_encoding: missing required key" in str(exc_info.value) + + +def test_dump_emits_canonical_document() -> None: + """model_dump serializes the field via to_json — the canonical document, + not pydantic's field-by-field view of the dataclass.""" + manifest = ArrayManifest.model_validate({"path": "a/b", "metadata": VALID_DOC}) + dumped = manifest.model_dump() + assert dumped["metadata"] == manifest.metadata.to_json() + # Empty configurations use the extension-definition shorthand form. + assert dumped["metadata"]["data_type"] == "uint8" + + +def test_json_roundtrip_through_pydantic() -> None: + """model_dump_json output re-validates to an equal manifest (JSON emits + tuples as arrays; from_json converts them back).""" + manifest = ArrayManifest.model_validate({"path": "a/b", "metadata": VALID_DOC}) + revived = ArrayManifest.model_validate_json(manifest.model_dump_json()) + assert revived == manifest + + +def test_type_adapter_standalone() -> None: + """The annotated alias also works without a BaseModel, via TypeAdapter.""" + adapter = TypeAdapter(ArrayMetadataV3Field) + model = adapter.validate_python(VALID_DOC) + assert isinstance(model, ZarrV3ArrayMetadata) + assert adapter.dump_python(model) == model.to_json() + + +# --- the road not taken: native dataclass introspection ---------------------- + + +def test_native_dataclass_introspection_is_not_supported() -> None: + """Pydantic cannot field-introspect the model dataclasses: the UNSET + sentinel (PEP 661, typing_extensions.Sentinel) in the optional-field + annotations has no pydantic schema (as of pydantic 2.13), so even the + rebuild-with-namespace recipe fails. Introspection was already the wrong + tool before the sentinel existed — it validated the model shape rather + than the document, and its lax coercion re-opened validator holes (e.g. + shape=[True, -5] coerced to (1, -5)) — so the delegation patterns above + are the only supported integrations. If this test ever fails because + pydantic learned to handle sentinels, revisit whether the introspection + path needs its divergences documented again.""" + from zarr_metadata._common import JSONValue + from zarr_metadata.model import UNSET + from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON, ZarrV3ExtensionField + + def build_and_use() -> None: + adapter = TypeAdapter(ZarrV3ArrayMetadata) + adapter.rebuild( + force=True, + _types_namespace={ + "JSONValue": JSONValue, + "ZarrV3ExtensionField": ZarrV3ExtensionField, + "ZarrV3MetadataFieldJSON": ZarrV3MetadataFieldJSON, + "ZarrV3ArrayMetadataJSON": ZarrV3ArrayMetadataJSON, + "ZarrV3NamedConfig": ZarrV3NamedConfig, + "ZarrV3MetadataField": ZarrV3NamedConfig, + "UNSET": UNSET, + }, + ) + adapter.validate_python({}) + + with pytest.raises((AttributeError, PydanticSchemaGenerationError, PydanticUserError)): + build_and_use() + + +# --- a first-class pydantic model, engine-backed (the pydantic-zarr pattern) -- +# +# When a consumer wants a real BaseModel — JSON schema generation, and +# generics for typed attributes, as in pydantic-zarr's ArraySpec — the model +# fields are pydantic-native, but validation and serialization still route +# through the library: a mode="before" validator canonicalizes every input +# document with from_json(...).to_json(), so the structural validators and +# normalization run BEFORE pydantic parses fields (no coercion divergence), +# and the document form is the bridge in both directions. + +AttrsT = TypeVar("AttrsT") + + +class NamedConfig(BaseModel): + """Pydantic mirror of a normalized metadata extension envelope.""" + + name: str + configuration: dict[str, JSONValue] = {} + must_understand: bool = True + + +class ArrayMetadataV3Spec(BaseModel, Generic[AttrsT]): + """A pydantic-native, attribute-typed view of a v3 array metadata document. + + The library is the engine: every input is canonicalized and structurally + validated by `ZarrV3ArrayMetadata.from_json` before pydantic sees the + fields, and `to_document` / `to_metadata_model` emit through the library. + """ + + model_config = ConfigDict(frozen=True) + + zarr_format: int = 3 + node_type: str = "array" + shape: tuple[int, ...] + data_type: NamedConfig + chunk_grid: NamedConfig + chunk_key_encoding: NamedConfig + fill_value: JSONValue + codecs: tuple[NamedConfig, ...] + attributes: AttrsT + dimension_names: tuple[str | None, ...] | None = None + storage_transformers: tuple[NamedConfig, ...] = () + + @model_validator(mode="before") + @classmethod + def _canonicalize(cls, data: object) -> object: + """Route every input document through the library's validation and + normalization; pydantic then parses only canonical documents.""" + if isinstance(data, Mapping): + doc = dict(ZarrV3ArrayMetadata.from_json(data).to_json()) + for key in ("data_type", "chunk_grid", "chunk_key_encoding"): + if isinstance(doc[key], str): + doc[key] = {"name": doc[key]} + for key in ("codecs", "storage_transformers"): + doc[key] = tuple( + {"name": item} if isinstance(item, str) else item for item in doc.get(key, ()) + ) + doc.setdefault("attributes", {}) + return doc + return data + + def to_metadata_model(self) -> ZarrV3ArrayMetadata: + """Bridge back to the canonical model, via the document form. + + In the document, "no dimension names" is key-absence, not null; the + pydantic-side None translates to dropping the key. + """ + doc = self.model_dump() + if doc["dimension_names"] is None: + del doc["dimension_names"] + return ZarrV3ArrayMetadata.from_json(doc) + + def to_document(self) -> dict[str, object]: + """The canonical document (omit-empty conventions applied).""" + return dict(self.to_metadata_model().to_json()) + + +class MicroscopyAttrs(BaseModel): + """Example of consumer-typed attributes, pydantic-zarr style.""" + + resolution_um: float + + +def test_spec_typed_attributes() -> None: + """The generic parameter types the attributes, so consumers get validated, + attribute-level access — the pydantic-zarr ArraySpec pattern.""" + doc = dict(VALID_DOC) | {"attributes": {"resolution_um": 0.5}} + spec = ArrayMetadataV3Spec[MicroscopyAttrs].model_validate(doc) + assert spec.attributes.resolution_um == 0.5 + assert spec.data_type == NamedConfig(name="uint8") + + +def test_spec_engine_validates_before_pydantic() -> None: + """The library's structural validation runs before pydantic's parsing, so + coercion cannot re-open validator holes (contrast with the native + introspection test above, where [True, -5] coerced to (1, -5)).""" + with pytest.raises(ValidationError, match="shape"): + ArrayMetadataV3Spec[MicroscopyAttrs].model_validate( + dict(VALID_DOC) | {"shape": [True, -5], "attributes": {"resolution_um": 0.5}} + ) + + +def test_spec_bridges_to_canonical_model_and_document() -> None: + """to_metadata_model / to_document round-trip through the document form, + and the emitted document matches what the library itself would emit.""" + doc = dict(VALID_DOC) | {"attributes": {"resolution_um": 0.5}} + spec = ArrayMetadataV3Spec[MicroscopyAttrs].model_validate(doc) + model = spec.to_metadata_model() + assert isinstance(model, ZarrV3ArrayMetadata) + assert spec.to_document() == dict(model.to_json()) + # and back: the document revalidates to an equal spec + assert ArrayMetadataV3Spec[MicroscopyAttrs].model_validate(spec.to_document()) == spec + + +def test_spec_json_schema_generation() -> None: + """A real BaseModel means model_json_schema works — the capability the + opaque InstanceOf pattern cannot provide.""" + schema = ArrayMetadataV3Spec[MicroscopyAttrs].model_json_schema() + assert schema["properties"]["shape"]["type"] == "array" + assert "MicroscopyAttrs" in schema["$defs"] diff --git a/packages/zarr-metadata/tests/model/test_pydantic_module.py b/packages/zarr-metadata/tests/model/test_pydantic_module.py new file mode 100644 index 0000000000..d15b3f118c --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_pydantic_module.py @@ -0,0 +1,264 @@ +"""Tests for `zarr_metadata.pydantic`, the optional pydantic field-type module. + +The hand-rolled recipes in `test_pydantic.py` document how the integration +works; this module ships it. Instances are the CORE model classes (no +parallel hierarchy), so values interoperate freely with non-pydantic code. +""" + +import json +import warnings + +import pytest +from jsonschema import Draft202012Validator +from pydantic import BaseModel, TypeAdapter, ValidationError + +import zarr_metadata.pydantic as zmp +from zarr_metadata.model import ( + ZarrV2ArrayMetadata, + ZarrV2ConsolidatedMetadata, + ZarrV2GroupMetadata, + ZarrV3ArrayMetadata, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3NamedConfig, +) + +V3_ARRAY_DOC = dict(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json()) +V2_ARRAY_DOC = dict(ZarrV2ArrayMetadata.create_default(shape=(4,), chunks=(2,)).to_json()) +V3_GROUP_DOC = {"zarr_format": 3, "node_type": "group", "attributes": {"a": 1}} +V2_GROUP_DOC = {"zarr_format": 2, "attributes": {"a": 1}} +V3_CONSOLIDATED_DOC = { + "kind": "inline", + "must_understand": False, + "metadata": {"a": dict(V3_ARRAY_DOC)}, +} +V2_CONSOLIDATED_DOC = { + "zarr_consolidated_format": 1, + "metadata": {".zgroup": {"zarr_format": 2}}, +} + +FIELD_CASES = [ + pytest.param(zmp.ZarrV3ArrayMetadata, ZarrV3ArrayMetadata, V3_ARRAY_DOC, id="array-v3"), + pytest.param(zmp.ZarrV2ArrayMetadata, ZarrV2ArrayMetadata, V2_ARRAY_DOC, id="array-v2"), + pytest.param(zmp.ZarrV3GroupMetadata, ZarrV3GroupMetadata, V3_GROUP_DOC, id="group-v3"), + pytest.param(zmp.ZarrV2GroupMetadata, ZarrV2GroupMetadata, V2_GROUP_DOC, id="group-v2"), + pytest.param( + zmp.ZarrV3ConsolidatedMetadata, + ZarrV3ConsolidatedMetadata, + V3_CONSOLIDATED_DOC, + id="consolidated-v3", + ), + pytest.param( + zmp.ZarrV2ConsolidatedMetadata, + ZarrV2ConsolidatedMetadata, + V2_CONSOLIDATED_DOC, + id="consolidated-v2", + ), + pytest.param(zmp.ZarrV3MetadataField, ZarrV3NamedConfig, {"name": "bytes"}, id="field-v3"), +] + + +@pytest.mark.parametrize(("field_type", "model_cls", "doc"), FIELD_CASES) +def test_field_type_validates_and_dumps_canonically( + field_type: object, model_cls: type, doc: dict[str, object] +) -> None: + """Each field type parses its raw document into the CORE model class, + passes existing instances through unchanged, and dumps the canonical + document via to_json.""" + adapter = TypeAdapter(field_type) + model = adapter.validate_python(doc) + assert type(model) is model_cls + assert adapter.validate_python(model) is model + assert adapter.dump_python(model) == model.to_json() + + +def test_core_instances_interoperate() -> None: + """A core model instance (e.g. handed out by zarr-python) drops straight + into a pydantic field — the reason the module ships Annotated aliases over + the core classes rather than pydantic-aware subclasses.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + + core = ZarrV3ArrayMetadata.from_json(V3_ARRAY_DOC) + manifest = Manifest(metadata=core) + assert manifest.metadata is core + + +def test_validation_error_carries_problems() -> None: + """A defective document fails with the library's loc-annotated messages.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + + doc = dict(V3_ARRAY_DOC) + del doc["chunk_key_encoding"] + with pytest.raises(ValidationError, match="chunk_key_encoding: missing required key"): + Manifest.model_validate({"metadata": doc}) + + +def test_json_schema_generation() -> None: + """model_json_schema works, describing the document form each field accepts.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + codec: zmp.ZarrV3MetadataField + + schema = Manifest.model_json_schema() + metadata_schema = schema["$defs"]["ZarrV3ArrayMetadataJSON"] + assert schema["properties"]["metadata"]["$ref"] == "#/$defs/ZarrV3ArrayMetadataJSON" + assert metadata_schema["required"] == [ + "zarr_format", + "node_type", + "data_type", + "shape", + "chunk_grid", + "chunk_key_encoding", + "fill_value", + "codecs", + ] + assert metadata_schema["properties"]["zarr_format"] == { + "const": 3, + "title": "Zarr Format", + "type": "integer", + } + assert schema["properties"]["codec"]["anyOf"] == [ + {"type": "string"}, + {"$ref": "#/$defs/ZarrV3NamedConfigJSON"}, + ] + + +def test_json_schema_generation_emits_no_warnings() -> None: + """Consumers can generate every public integration schema without warning filters.""" + field_types = ( + zmp.ZarrV3ArrayMetadata, + zmp.ZarrV2ArrayMetadata, + zmp.ZarrV3GroupMetadata, + zmp.ZarrV2GroupMetadata, + zmp.ZarrV3ConsolidatedMetadata, + zmp.ZarrV2ConsolidatedMetadata, + zmp.ZarrV3MetadataField, + ) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + for field_type in field_types: + TypeAdapter(field_type).json_schema() + + +def test_v2_recursive_structured_dtype_is_in_pydantic_schema() -> None: + """The schema accepts nested structured dtypes supported by the v2 specification.""" + doc = json.loads(json.dumps(V2_ARRAY_DOC)) + doc["dtype"] = [["outer", [["inner", " None: + adapter = TypeAdapter(field_type) + with pytest.raises(ValidationError): + adapter.validate_python(document) + assert list(Draft202012Validator(adapter.json_schema()).iter_errors(document)) + + +def test_v3_array_schema_rejects_empty_codecs() -> None: + """The generated schema mirrors the runtime non-empty codec pipeline rule.""" + doc = json.loads(json.dumps(V3_ARRAY_DOC)) + doc["codecs"] = [] + + _assert_runtime_and_schema_reject(zmp.ZarrV3ArrayMetadata, doc) + + +def test_array_schemas_reject_negative_dimensions() -> None: + """Both array schemas mirror the runtime non-negative dimension rule.""" + for field_type, source in ( + (zmp.ZarrV3ArrayMetadata, V3_ARRAY_DOC), + (zmp.ZarrV2ArrayMetadata, V2_ARRAY_DOC), + ): + doc = json.loads(json.dumps(source)) + doc["shape"] = [-1] + _assert_runtime_and_schema_reject(field_type, doc) + + +def test_v2_array_schema_rejects_empty_filters() -> None: + """The v2 schema mirrors the runtime one-or-more filter rule.""" + doc = json.loads(json.dumps(V2_ARRAY_DOC)) + doc["filters"] = [] + + _assert_runtime_and_schema_reject(zmp.ZarrV2ArrayMetadata, doc) + + +@pytest.mark.parametrize("field", ["data_type", "chunk_grid", "chunk_key_encoding"]) +def test_v3_array_schema_rejects_false_at_mandatory_extension_points(field: str) -> None: + """Mandatory v3 extension points cannot opt out of understanding.""" + doc = json.loads(json.dumps(V3_ARRAY_DOC)) + doc[field] = {"name": "example", "must_understand": False} + + _assert_runtime_and_schema_reject(zmp.ZarrV3ArrayMetadata, doc) + + +def test_metadata_field_schema_rejects_unknown_members() -> None: + """Named-configuration envelopes are closed in both runtime and schema validation.""" + _assert_runtime_and_schema_reject( + zmp.ZarrV3MetadataField, + {"name": "example", "unexpected": 1}, + ) + + +@pytest.mark.parametrize( + ("field_type", "source"), + [ + (zmp.ZarrV2ArrayMetadata, V2_ARRAY_DOC), + (zmp.ZarrV2GroupMetadata, V2_GROUP_DOC), + (zmp.ZarrV2ConsolidatedMetadata, V2_CONSOLIDATED_DOC), + ], +) +def test_v2_schema_rejects_unknown_document_members( + field_type: object, source: dict[str, object] +) -> None: + """Closed v2 merged documents expose their runtime boundary in JSON Schema.""" + doc = json.loads(json.dumps(source)) + doc["unexpected"] = 1 + + _assert_runtime_and_schema_reject(field_type, doc) + + +def test_v3_array_schema_allows_unknown_extension_fields() -> None: + """Schema constraints do not close the v3 top-level extension namespace.""" + doc = json.loads(json.dumps(V3_ARRAY_DOC)) + doc["vendor_extension"] = {"anything": [1, 2]} + adapter = TypeAdapter(zmp.ZarrV3ArrayMetadata) + + assert adapter.validate_python(doc).extra_fields == {"vendor_extension": {"anything": (1, 2)}} + assert Draft202012Validator(adapter.json_schema()).is_valid(doc) + + +def test_json_roundtrip() -> None: + """model_dump_json output re-validates to an equal pydantic model.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + + manifest = Manifest.model_validate({"metadata": V3_ARRAY_DOC}) + assert Manifest.model_validate_json(manifest.model_dump_json()) == manifest + + +def test_metadata_field_serializes_shorthand_and_false_object() -> None: + """The optional integration exposes the core model's canonical extension form.""" + adapter = TypeAdapter(zmp.ZarrV3MetadataField) + assert adapter.dump_python(adapter.validate_python({"name": "bytes"})) == "bytes" + assert adapter.dump_python( + adapter.validate_python({"name": "optional", "must_understand": False}) + ) == {"name": "optional", "must_understand": False} + + +def test_core_package_does_not_import_pydantic() -> None: + """Importing zarr_metadata (in a fresh interpreter) must not import + pydantic: the integration is opt-in via zarr_metadata.pydantic.""" + import subprocess + import sys + + code = "import sys, zarr_metadata; assert 'pydantic' not in sys.modules, 'leaked'" + subprocess.run([sys.executable, "-c", code], check=True) diff --git a/packages/zarr-metadata/tests/model/test_sentinel.py b/packages/zarr-metadata/tests/model/test_sentinel.py new file mode 100644 index 0000000000..252a4cdd30 --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_sentinel.py @@ -0,0 +1,89 @@ +"""Tests for the pickling and copying behavior of the `UNSET` sentinel. + +The sentinel's contract is identity, so it must never be reconstructed from +state. typing_extensions >= 4.16 pickles sentinels by reference (a lookup of +the sentinel's name on its defining module), which preserves the singleton +across process boundaries; these tests pin that behavior, since models hold +`UNSET` as field values and must survive pickling and deep-copying. + +The model round-trip tests compare whole structures: dataclass equality +compares every field, and `UNSET` compares by identity, so an impostor +sentinel produced by state-based pickling would fail the equality check. +""" + +from __future__ import annotations + +import copy +import pickle + +import pytest +from typing_extensions import Sentinel + +from zarr_metadata.model import ( + UNSET, + ZarrV2ArrayMetadata, + ZarrV2GroupMetadata, + ZarrV3ArrayMetadata, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, +) + +# Whole-model cases covering the states we know are problematic for +# serialization: every optional-key field in the UNSET (absent) state, the +# same fields in the present state (including present-but-empty, which must +# stay distinct from absent), and UNSET nested inside consolidated metadata. +MODEL_CASES = { + "array-v3-dimension-names-unset": ZarrV3ArrayMetadata.create_default(shape=(4,)), + "array-v3-dimension-names-set": ZarrV3ArrayMetadata.create_default(shape=(2, 2)).update( + dimension_names=("x", None) + ), + "array-v2-attributes-unset": ZarrV2ArrayMetadata.create_default(shape=(4,)), + "array-v2-attributes-empty": ZarrV2ArrayMetadata.create_default(shape=(4,), attributes={}), + "group-v2-attributes-unset": ZarrV2GroupMetadata.create_default(), + "group-v2-attributes-set": ZarrV2GroupMetadata.create_default(attributes={"a": 1}), + "group-v3-consolidated-unset": ZarrV3GroupMetadata.create_default(), + "group-v3-consolidated-with-unset-inside": ZarrV3GroupMetadata.create_default( + consolidated_metadata=ZarrV3ConsolidatedMetadata( + metadata={ + "child": ZarrV3ArrayMetadata.create_default(shape=(4,)), + "subgroup": ZarrV3GroupMetadata.create_default(), + } + ) + ), +} + + +def test_unset_pickle_round_trip_preserves_identity() -> None: + restored = pickle.loads(pickle.dumps(UNSET)) + assert restored is UNSET + + +def test_unset_copy_preserves_identity() -> None: + assert copy.copy(UNSET) is UNSET + assert copy.deepcopy(UNSET) is UNSET + + +@pytest.mark.parametrize("model", MODEL_CASES.values(), ids=MODEL_CASES.keys()) +def test_model_pickle_round_trip( + model: ZarrV2ArrayMetadata | ZarrV3ArrayMetadata | ZarrV2GroupMetadata | ZarrV3GroupMetadata, +) -> None: + restored = pickle.loads(pickle.dumps(model)) + assert restored == model + + +@pytest.mark.parametrize("model", MODEL_CASES.values(), ids=MODEL_CASES.keys()) +def test_model_deepcopy( + model: ZarrV2ArrayMetadata | ZarrV3ArrayMetadata | ZarrV2GroupMetadata | ZarrV3GroupMetadata, +) -> None: + assert copy.deepcopy(model) == model + + +def test_non_importable_sentinel_fails_to_pickle() -> None: + """Sentinels pickle by reference, never by state. A sentinel that is not + an importable attribute of its module has no reference to pickle, so + dumping it must fail loudly — a successful dump here would mean the + implementation regressed to state-based pickling, which would produce + identity-breaking impostor objects on the receiving side.""" + local_sentinel = Sentinel("local_sentinel") + with pytest.raises((pickle.PicklingError, TypeError)): + pickle.dumps(local_sentinel) diff --git a/packages/zarr-metadata/tests/test_partial_equivalence.py b/packages/zarr-metadata/tests/test_partial_equivalence.py new file mode 100644 index 0000000000..33492b2356 --- /dev/null +++ b/packages/zarr-metadata/tests/test_partial_equivalence.py @@ -0,0 +1,42 @@ +"""Drift-prevention tests for Partial* TypedDict variants. + +Each *Partial TypedDict in the package must declare the same fields +(with the same annotations) and the same extra_items setting as its +full counterpart. The only intentional difference is total=False +(i.e. every field becomes NotRequired). This test enforces that +invariant so adding a field to the full type without mirroring it +on the partial fails CI. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from zarr_metadata.v2.array import ZarrV2ArrayMetadataJSON, ZarrV2ArrayMetadataJSONPartial +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON, ZarrV2GroupMetadataJSONPartial +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON, ZarrV3ArrayMetadataJSONPartial +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataJSONPartial + +# (full, partial) pairs to check. Add new pairs here as more are introduced. +PAIRS: list[tuple[type, type]] = [ + (ZarrV3ArrayMetadataJSON, ZarrV3ArrayMetadataJSONPartial), + (ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataJSONPartial), + (ZarrV2ArrayMetadataJSON, ZarrV2ArrayMetadataJSONPartial), + (ZarrV2GroupMetadataJSON, ZarrV2GroupMetadataJSONPartial), +] + + +@pytest.mark.parametrize(("full", "partial"), PAIRS, ids=lambda p: p.__name__) +def test_partial_matches_full(full: Any, partial: Any) -> None: + """Partial TypedDict has identical fields and extra_items, only total differs.""" + assert full.__annotations__ == partial.__annotations__, ( + f"{partial.__name__} fields drifted from {full.__name__}: " + f"full={set(full.__annotations__)}, partial={set(partial.__annotations__)}" + ) + assert getattr(full, "__extra_items__", None) == getattr(partial, "__extra_items__", None), ( + f"{partial.__name__} extra_items differs from {full.__name__}" + ) + assert full.__total__ is True, f"{full.__name__} must be declared with total=True (default)" + assert partial.__total__ is False, f"{partial.__name__} must be declared with total=False" diff --git a/packages/zarr-metadata/tests/test_public_api.py b/packages/zarr-metadata/tests/test_public_api.py new file mode 100644 index 0000000000..6613aa394b --- /dev/null +++ b/packages/zarr-metadata/tests/test_public_api.py @@ -0,0 +1,488 @@ +"""Test that the curated front-door names are accessible from the top-level zarr_metadata package.""" + +import importlib +import pkgutil +import re +from typing import Literal, get_args, get_origin + +import zarr_metadata as zm + + +def _group_rank(s: str) -> int: + """RUF022 groups `__all__` as: SCREAMING_SNAKE (0), then TitleCase (1), then dunders (2). + + The exact intra-group ordering is ruff's own natural sort and is enforced by + ruff itself (pre-commit + CI); this test only asserts the grouping, not the + fragile tie-breaking, so it can't drift out of sync with ruff's implementation. + """ + if s.startswith("__") and s.endswith("__"): + return 2 + stripped = re.sub(r"[\d_]", "", s) + return 0 if stripped.isupper() else 1 + + +EXPECTED = [ + # Category A — metadata-document types + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayMetadataJSONPartial", + "ZarrV2ZArrayJSON", + "ZarrV2GroupMetadataJSON", + "ZarrV2GroupMetadataJSONPartial", + "ZarrV2ZGroupJSON", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2ZAttrsJSON", + "ZarrV2CodecMetadata", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ArrayMetadataJSONPartial", + "ZarrV3ExtensionField", + "ZarrV3GroupMetadataJSON", + "ZarrV3GroupMetadataJSONPartial", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3NamedConfigJSON", + "ZarrV3MetadataFieldJSON", + "JSONValue", + # Category A' — metadata models (in-memory dataclasses over the documents) + "ZarrV2ArrayMetadata", + "ZarrV2ArrayMetadataPartial", + "ZarrV3ArrayMetadata", + "ZarrV3ArrayMetadataPartial", + "ZarrV2GroupMetadata", + "ZarrV2GroupMetadataPartial", + "ZarrV3GroupMetadata", + "ZarrV3GroupMetadataPartial", + "ZarrV2ConsolidatedMetadata", + "ZarrV3ConsolidatedMetadata", + "ZarrV3NamedConfig", + "ZarrV3MetadataField", + "ValidationProblem", + "MetadataValidationError", + "ProblemKind", + "UNSET", + # Store keys — the names the documents are persisted under. Defined in the + # v2/v3 spec modules, re-exported through `zarr_metadata.model`. + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZarrV2ArrayMetadataStoreKey", + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZarrV2GroupMetadataStoreKey", + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZarrV2AttributesStoreKey", + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZarrV2ConsolidatedMetadataStoreKey", + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZarrV3ArrayMetadataStoreKey", + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "ZarrV3GroupMetadataStoreKey", + # Not a store key: v3 consolidated metadata is embedded in the group's own + # `zarr.json`, so it has no paired Literal alias. + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + # v2 data-type encoding union + "ZarrV2DataTypeMetadata", + # Category B — codec canonical unions + "BloscCodecMetadata", + "BytesCodecMetadata", + "CastValueCodecMetadata", + "Crc32cCodecMetadata", + "GzipCodecMetadata", + "ScaleOffsetCodecMetadata", + "ShardingIndexedCodecMetadata", + "TransposeCodecMetadata", + "ZstdCodecMetadata", + # Category C — grid/key canonical unions + "RegularChunkGridMetadata", + "RectilinearChunkGridMetadata", + "DefaultChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingMetadata", + # Category D — dtype trios + # bool + "BoolDataTypeName", + "BOOL_DATA_TYPE_NAME", + "BoolFillValue", + # int8/16/32/64 + "Int8DataTypeName", + "INT8_DATA_TYPE_NAME", + "Int8FillValue", + "Int16DataTypeName", + "INT16_DATA_TYPE_NAME", + "Int16FillValue", + "Int32DataTypeName", + "INT32_DATA_TYPE_NAME", + "Int32FillValue", + "Int64DataTypeName", + "INT64_DATA_TYPE_NAME", + "Int64FillValue", + # uint8/16/32/64 (actual casing is Uint, not UInt) + "Uint8DataTypeName", + "UINT8_DATA_TYPE_NAME", + "Uint8FillValue", + "Uint16DataTypeName", + "UINT16_DATA_TYPE_NAME", + "Uint16FillValue", + "Uint32DataTypeName", + "UINT32_DATA_TYPE_NAME", + "Uint32FillValue", + "Uint64DataTypeName", + "UINT64_DATA_TYPE_NAME", + "Uint64FillValue", + # float16/32/64 + "Float16DataTypeName", + "FLOAT16_DATA_TYPE_NAME", + "Float16FillValue", + "Float32DataTypeName", + "FLOAT32_DATA_TYPE_NAME", + "Float32FillValue", + "Float64DataTypeName", + "FLOAT64_DATA_TYPE_NAME", + "Float64FillValue", + # complex64/128 + "Complex64DataTypeName", + "COMPLEX64_DATA_TYPE_NAME", + "Complex64FillValue", + "Complex128DataTypeName", + "COMPLEX128_DATA_TYPE_NAME", + "Complex128FillValue", + # bytes + "BytesDataTypeName", + "BYTES_DATA_TYPE_NAME", + "BytesFillValue", + # string + "StringDataTypeName", + "STRING_DATA_TYPE_NAME", + "StringFillValue", + # numpy_datetime64 + "NumpyDatetime64DataTypeName", + "NUMPY_DATETIME64_DATA_TYPE_NAME", + "NumpyDatetime64FillValue", + # numpy_timedelta64 + "NumpyTimedelta64DataTypeName", + "NUMPY_TIMEDELTA64_DATA_TYPE_NAME", + "NumpyTimedelta64FillValue", + # struct + "StructDataTypeName", + "STRUCT_DATA_TYPE_NAME", + "StructFillValue", + # raw (no _DATA_TYPE_NAME constant) + "RawBytesDataTypeName", + "RawBytesFillValue", + # Category E — constant+Literal pairs + "ZARR_V2_ARRAY_ORDER", + "ZarrV2ArrayOrder", + "ZARR_V2_ARRAY_DIMENSION_SEPARATOR", + "ZarrV2ArrayDimensionSeparator", + "ENDIANNESS", + "Endianness", + "BYTES_CODEC_NAME", + "BytesCodecName", + "BLOSC_CODEC_NAME", + "BloscCodecName", + "BLOSC_CNAME", + "BloscCName", + "BLOSC_SHUFFLE", + "BloscShuffle", + "CAST_ROUNDING_MODE", + "CastRoundingMode", + "CAST_OUT_OF_RANGE_MODE", + "CastOutOfRangeMode", + "CAST_VALUE_CODEC_NAME", + "CastValueCodecName", + "CRC32C_CODEC_NAME", + "Crc32cCodecName", + "GZIP_CODEC_NAME", + "GzipCodecName", + "SCALE_OFFSET_CODEC_NAME", + "ScaleOffsetCodecName", + "SHARDING_INDEX_LOCATION", + "ShardingIndexLocation", + "SHARDING_INDEXED_CODEC_NAME", + "ShardingIndexedCodecName", + "TRANSPOSE_CODEC_NAME", + "TransposeCodecName", + "ZSTD_CODEC_NAME", + "ZstdCodecName", + "REGULAR_CHUNK_GRID_NAME", + "RegularChunkGridName", + "RECTILINEAR_CHUNK_GRID_NAME", + "RectilinearChunkGridName", + "DEFAULT_CHUNK_KEY_ENCODING_NAME", + "DefaultChunkKeyEncodingName", + "DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR", + "DefaultChunkKeyEncodingSeparator", + "V2_CHUNK_KEY_ENCODING_NAME", + "V2ChunkKeyEncodingName", + "V2_CHUNK_KEY_ENCODING_SEPARATOR", + "V2ChunkKeyEncodingSeparator", + "NUMPY_TIME_UNIT", + "NumpyTimeUnit", +] + + +def test_front_door_names_public() -> None: + missing = [n for n in EXPECTED if n not in zm.__all__ or not hasattr(zm, n)] + assert not missing, f"missing from top-level API: {missing}" + + +def test_front_door_is_exactly_expected() -> None: + """`__all__` must contain exactly the curated names (plus `__version__`). + + Guards against a name being promoted to the front door without a + corresponding, deliberate entry in `EXPECTED` — i.e. an accidental + addition to the public API surface. + """ + assert set(zm.__all__) - {"__version__"} == set(EXPECTED) + + +def test_all_is_grouped_and_unique() -> None: + ranks = [_group_rank(n) for n in zm.__all__] + assert ranks == sorted(ranks), "`__all__` groups out of order (SCREAMING, TitleCase, dunder)" + assert len(zm.__all__) == len(set(zm.__all__)) + + +# --- naming grammar --------------------------------------------------------- + +# Core document/model names: the format version comes first (`ZarrV2` / +# `ZarrV3`), then the CamelCase entity, then an optional role suffix +# (`JSON`, `JSONPartial`, `Partial`, `StoreKey`) — validated loosely here +# because `JSON` decomposes into single-letter words under any strict +# word-splitting regex. +_CORE_NAME = re.compile(r"^ZarrV[23](?:[A-Z][a-z0-9]*)+$") + +# Zarr v3 extension-entity names: the registered entity comes first (`Blosc`, +# `Uint8`, ... — `V2` here is the *entity name* of the v2-compatibility chunk +# key encoding, not a format-version marker, which is always spelled +# `ZarrV2`/`ZarrV3`), followed by exactly one role suffix. +_EXTENSION_ROLES = ( + "CodecConfiguration", + "CodecMetadata", + "CodecName", + "CodecObject", + "ChunkGridConfiguration", + "ChunkGridMetadata", + "ChunkGridName", + "ChunkGridObject", + "ChunkKeyEncodingConfiguration", + "ChunkKeyEncodingMetadata", + "ChunkKeyEncodingName", + "ChunkKeyEncodingObject", + "ChunkKeyEncodingSeparator", + "DataTypeName", + "FillValue", + "Configuration", + "Component", +) +_EXTENSION_NAME = re.compile(r"^(?:[A-Z][a-z0-9]*)+?(?:" + "|".join(_EXTENSION_ROLES) + r")$") + +# Standalone vocabulary: scalar Literal aliases, structural helper shapes, and +# the validation diagnostics. Closed by hand — a new name belongs here only if +# it is genuinely role-less; anything document- or entity-shaped must fit the +# grammars above instead. +_STANDALONE_VOCAB = frozenset( + { + "Base64Bytes", + "BloscCName", + "BloscShuffle", + "CastOutOfRangeMode", + "CastRoundingMode", + "Endianness", + "HexFloat16", + "HexFloat32", + "HexFloat64", + "JSONValue", + "MetadataValidationError", + "NumpyDatetime64", + "NumpyTimeUnit", + "NumpyTimedelta64", + "ProblemKind", + "RectilinearDimSpec", + "ScalarMap", + "ScalarMapEntry", + "ShardingIndexLocation", + "Struct", + "StructField", + "ValidationProblem", + } +) + + +def _iter_module_names() -> set[str]: + """Every public module in the package, including the top-level namespace.""" + module_names = {"zarr_metadata"} + for info in pkgutil.walk_packages(zm.__path__, prefix="zarr_metadata."): + if not any(part.startswith("_") for part in info.name.split(".")[1:]): + module_names.add(info.name) + return module_names + + +def _public_type_names() -> set[tuple[str, str]]: + """Every (module, CamelCase name) pair exported via a public `__all__`.""" + out: set[tuple[str, str]] = set() + for module_name in _iter_module_names(): + module = importlib.import_module(module_name) + for name in getattr(module, "__all__", ()): + if name.startswith("_") or name.isupper() or name.islower(): + continue + out.add((module_name, name)) + return out + + +def test_public_type_names_comply_with_naming_grammar() -> None: + """Every public type name parses against the package naming grammar: + version-first core names, entity-plus-role extension names, or the closed + standalone vocabulary.""" + exported = _public_type_names() + violations = [ + f"{module}.{name}" + for module, name in sorted(exported) + if name not in _STANDALONE_VOCAB + and not _CORE_NAME.match(name) + and not _EXTENSION_NAME.match(name) + ] + assert not violations, f"names outside the naming grammar: {violations}" + + +def test_standalone_vocab_is_not_stale() -> None: + """Every allowlisted vocabulary name is still actually exported.""" + exported_names = {name for _, name in _public_type_names()} + assert exported_names >= _STANDALONE_VOCAB + + +def test_promoted_pairs_drift() -> None: + """Each promoted runtime constant holds exactly the values of the `Literal` + type it manifests, so the two cannot drift apart.""" + pairs = [ + (zm.ENDIANNESS, zm.Endianness), + (zm.BLOSC_CNAME, zm.BloscCName), + (zm.BLOSC_SHUFFLE, zm.BloscShuffle), + (zm.SHARDING_INDEX_LOCATION, zm.ShardingIndexLocation), + (zm.NUMPY_TIME_UNIT, zm.NumpyTimeUnit), + (zm.CAST_ROUNDING_MODE, zm.CastRoundingMode), + (zm.CAST_OUT_OF_RANGE_MODE, zm.CastOutOfRangeMode), + (zm.ZARR_V2_ARRAY_ORDER, zm.ZarrV2ArrayOrder), + (zm.ZARR_V2_ARRAY_DIMENSION_SEPARATOR, zm.ZarrV2ArrayDimensionSeparator), + (zm.DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR, zm.DefaultChunkKeyEncodingSeparator), + (zm.V2_CHUNK_KEY_ENCODING_SEPARATOR, zm.V2ChunkKeyEncodingSeparator), + ] + for const, lit in pairs: + assert set(const) == set(get_args(lit)) + + +def constant_name_for(type_name: str) -> str: + """Derive a constant's name from the name of the type it manifests. + + The transformation is purely syntactic: split at each lowercase-to-uppercase + boundary and before an uppercase run that starts a new word, then uppercase. + Digit runs stay glued to the token they follow (`Uint8` -> `UINT8`, + `Crc32c` -> `CRC32C`), because a digit boundary in CamelCase does not mark a + word boundary in the spec vocabulary these names model. + + Consecutive capitals do not split, so acronym-adjacent names derive badly: + `ZarrV2ZArrayJSON` -> `ZARR_V2ZARRAY_JSON` and `...JSONPartial` -> + `...JSONPARTIAL`. Every such name in the package today is a `TypedDict` or + `TypeAliasType` that backs no constant, so none reaches this function — but + a future `Literal` spelled that way would silently be held to a bad name. + Splitting acronyms correctly needs a vocabulary, not a regex, so the rule + stays syntactic and this stays a known limit. + """ + return re.sub(r"(?<=[a-z0-9])(?=[A-Z][a-z])|(?<=[a-z])(?=[A-Z])", "_", type_name).upper() + + +def _literal_backed_constants() -> list[tuple[str, str, str]]: + """Every (module, constant, type) triple where a module-level SCREAMING_SNAKE + constant holds exactly the values of a `Literal` type in the same module. + + Pairing is by value, not by proximity: a constant manifests the type whose + members it enumerates. Constants with no such type (extension-field keys, + key sets, canonical bit patterns) are exempt from the naming rule and are + simply absent from the result. + """ + out: list[tuple[str, str, str]] = [] + for module_name in _iter_module_names(): + module = importlib.import_module(module_name) + literals = { + name: frozenset(get_args(obj)) + for name, obj in vars(module).items() + if not name.startswith("_") + and not name.isupper() + and get_origin(obj) is Literal + and get_args(obj) + } + if not literals: + continue + for const_name, value in vars(module).items(): + if const_name.startswith("_") or not const_name.isupper(): + continue + members = frozenset(value) if isinstance(value, tuple) else frozenset({value}) + if not all(isinstance(m, str) for m in members): + continue + matches = [t for t, args in literals.items() if args == members] + # A single unambiguous type means this constant manifests it. Ties + # (two Literals with identical members) carry no signal about which + # name the constant should take, so they are skipped. + if len(matches) == 1: + out.append((module_name, const_name, matches[0])) + return out + + +def _value_tied_constants() -> set[str]: + """Constants whose manifested type is ambiguous because two or more `Literal` + types in the same module share its exact members. + + These are invisible to the derivation check, so they are surfaced here and + counted, rather than silently dropped inside the pairing helper.""" + tied: set[str] = set() + for module_name in _iter_module_names(): + module = importlib.import_module(module_name) + literals = [ + frozenset(get_args(obj)) + for name, obj in vars(module).items() + if not name.startswith("_") + and not name.isupper() + and get_origin(obj) is Literal + and get_args(obj) + ] + for const_name, value in vars(module).items(): + if const_name.startswith("_") or not const_name.isupper(): + continue + members = frozenset(value) if isinstance(value, tuple) else frozenset({value}) + if not all(isinstance(m, str) for m in members): + continue + if sum(1 for args in literals if args == members) > 1: + tied.add(f"{module_name}.{const_name}") + return tied + + +# Constants whose `Literal` type cannot be identified by value because another +# `Literal` in the same module has identical members. Pairing is by value, so a +# tie carries no signal about which name the constant should take. These are +# checked by eye; the count below fails if the tied set grows silently. +KNOWN_VALUE_TIES = 9 + + +def test_constant_names_derive_from_their_type_names() -> None: + """Every `Literal`-backed constant whose type can be identified by value has + a name that is the mechanical transform of that type's name. + + Constants tied to more than one identically-valued `Literal` are exempt (see + `KNOWN_VALUE_TIES`), as are constants in private modules and those backing + no `Literal` at all — so this pins the rule for most of the package, not all + of it.""" + pairs = _literal_backed_constants() + assert pairs, "found no Literal-backed constants to check" + violations = [ + f"{module}: {const} should be {constant_name_for(type_name)} (manifests {type_name})" + for module, const, type_name in pairs + if const != constant_name_for(type_name) + ] + assert not violations, "constants whose names do not derive from their type:\n" + "\n".join( + violations + ) + + +def test_value_tied_constants_are_a_known_set() -> None: + """The derivation check cannot see constants whose type is ambiguous by + value. Pin how many there are, so the exempt set cannot grow unnoticed and + quietly shrink the rule's coverage.""" + tied = _value_tied_constants() + assert len(tied) == KNOWN_VALUE_TIES, ( + f"value-tied constants changed (expected {KNOWN_VALUE_TIES}, got {len(tied)}); " + f"these are unchecked by the derivation rule and must be named by hand:\n" + + "\n".join(sorted(tied)) + ) diff --git a/packages/zarr-metadata/tests/v2/__init__.py b/packages/zarr-metadata/tests/v2/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v2/array/__init__.py b/packages/zarr-metadata/tests/v2/array/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v2/array/blosc_compressor_with_filters.json b/packages/zarr-metadata/tests/v2/array/blosc_compressor_with_filters.json new file mode 100644 index 0000000000..d7c01563e0 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/array/blosc_compressor_with_filters.json @@ -0,0 +1,19 @@ +{ + "zarr_format": 2, + "shape": [200], + "chunks": [50], + "dtype": " None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v2/consolidated/__init__.py b/packages/zarr-metadata/tests/v2/consolidated/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v2/consolidated/minimal.json b/packages/zarr-metadata/tests/v2/consolidated/minimal.json new file mode 100644 index 0000000000..fa5db0a584 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/consolidated/minimal.json @@ -0,0 +1,4 @@ +{ + "zarr_consolidated_format": 1, + "metadata": {} +} diff --git a/packages/zarr-metadata/tests/v2/consolidated/test_fixtures.py b/packages/zarr-metadata/tests/v2/consolidated/test_fixtures.py new file mode 100644 index 0000000000..e802c5bef8 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/consolidated/test_fixtures.py @@ -0,0 +1,20 @@ +"""Decode v2 consolidated metadata fixtures via pydantic.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV2ConsolidatedMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v2/consolidated/with_array_and_group.json b/packages/zarr-metadata/tests/v2/consolidated/with_array_and_group.json new file mode 100644 index 0000000000..778ede2e66 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/consolidated/with_array_and_group.json @@ -0,0 +1,18 @@ +{ + "zarr_consolidated_format": 1, + "metadata": { + ".zgroup": {"zarr_format": 2}, + ".zattrs": {"description": "root group attrs"}, + "data/.zarray": { + "zarr_format": 2, + "shape": [100], + "chunks": [10], + "dtype": " None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/__init__.py b/packages/zarr-metadata/tests/v3/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/array/__init__.py b/packages/zarr-metadata/tests/v3/array/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/array/blosc_codec.json b/packages/zarr-metadata/tests/v3/array/blosc_codec.json new file mode 100644 index 0000000000..7681474264 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/blosc_codec.json @@ -0,0 +1,27 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [1024], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [256]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + { + "name": "blosc", + "configuration": { + "cname": "zstd", + "clevel": 5, + "shuffle": "shuffle", + "blocksize": 0, + "typesize": 4 + } + } + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/datatype_named_config.json b/packages/zarr-metadata/tests/v3/array/datatype_named_config.json new file mode 100644 index 0000000000..b98964f38e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/datatype_named_config.json @@ -0,0 +1,20 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": { + "name": "numpy.datetime64", + "configuration": {"unit": "ns", "scale_factor": 1} + }, + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/gzip_codec.json b/packages/zarr-metadata/tests/v3/array/gzip_codec.json new file mode 100644 index 0000000000..6c4455dcff --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/gzip_codec.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [128], + "data_type": "uint16", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [64]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "gzip", "configuration": {"level": 5}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/rectilinear_grid.json b/packages/zarr-metadata/tests/v3/array/rectilinear_grid.json new file mode 100644 index 0000000000..9a33b1469c --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/rectilinear_grid.json @@ -0,0 +1,23 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "data_type": "float64", + "chunk_grid": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [10, 20, 30, 40], + 50 + ] + } + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0.0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/rectilinear_grid_with_rle.json b/packages/zarr-metadata/tests/v3/array/rectilinear_grid_with_rle.json new file mode 100644 index 0000000000..c131554a36 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/rectilinear_grid_with_rle.json @@ -0,0 +1,24 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [60, 30], + "data_type": "int16", + "chunk_grid": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [[10, 5], 5, 5], + [15, 15] + ] + } + }, + "chunk_key_encoding": { + "name": "default", + "configuration": {"separator": "/"} + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/regular_grid_default_encoding.json b/packages/zarr-metadata/tests/v3/array/regular_grid_default_encoding.json new file mode 100644 index 0000000000..73eb742d9b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/regular_grid_default_encoding.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10, 10]} + }, + "chunk_key_encoding": { + "name": "default", + "configuration": {"separator": "/"} + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/regular_grid_v2_encoding.json b/packages/zarr-metadata/tests/v3/array/regular_grid_v2_encoding.json new file mode 100644 index 0000000000..6c09fdb954 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/regular_grid_v2_encoding.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [50], + "data_type": "uint8", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [25]} + }, + "chunk_key_encoding": { + "name": "v2", + "configuration": {"separator": "."} + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes"} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/sharding_indexed_codec.json b/packages/zarr-metadata/tests/v3/array/sharding_indexed_codec.json new file mode 100644 index 0000000000..271e4d75a1 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/sharding_indexed_codec.json @@ -0,0 +1,31 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [1024, 1024], + "data_type": "uint16", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [256, 256]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [64, 64], + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "gzip", "configuration": {"level": 1}} + ], + "index_codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ], + "index_location": "end" + } + } + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/test_fixtures.py b/packages/zarr-metadata/tests/v3/array/test_fixtures.py new file mode 100644 index 0000000000..c84cc4042b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/test_fixtures.py @@ -0,0 +1,27 @@ +"""Decode v3 array metadata fixtures via pydantic. + +Each `*.json` file in this directory is a representative on-disk +`zarr.json` that should validate cleanly as `ZarrV3ArrayMetadataJSON`. +Fixtures are named for the variant they exercise (regular vs rectilinear +grid, blosc/gzip/zstd/sharding_indexed codecs, named-config dtypes, optional +fields, extra fields). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV3ArrayMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/array/transpose_and_crc32c_codecs.json b/packages/zarr-metadata/tests/v3/array/transpose_and_crc32c_codecs.json new file mode 100644 index 0000000000..3276d5a471 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/transpose_and_crc32c_codecs.json @@ -0,0 +1,19 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10, 20, 30], + "data_type": "float32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [5, 10, 15]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": "NaN", + "codecs": [ + {"name": "transpose", "configuration": {"order": [2, 1, 0]}}, + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/with_extra_field.json b/packages/zarr-metadata/tests/v3/array/with_extra_field.json new file mode 100644 index 0000000000..bd7a9f5b45 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/with_extra_field.json @@ -0,0 +1,21 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ], + "my_custom_extension": { + "must_understand": false, + "purpose": "exercise the extra_items=ZarrV3ExtensionField path" + } +} diff --git a/packages/zarr-metadata/tests/v3/array/with_optionals.json b/packages/zarr-metadata/tests/v3/array/with_optionals.json new file mode 100644 index 0000000000..0c4c60986f --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/with_optionals.json @@ -0,0 +1,24 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10, 20, 30], + "data_type": "float64", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [5, 10, 15]} + }, + "chunk_key_encoding": { + "name": "default", + "configuration": {"separator": "/"} + }, + "fill_value": "NaN", + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ], + "attributes": { + "description": "fixture exercising optional fields", + "tags": ["test", "metadata"] + }, + "dimension_names": ["t", "y", "x"], + "storage_transformers": [] +} diff --git a/packages/zarr-metadata/tests/v3/array/zstd_codec.json b/packages/zarr-metadata/tests/v3/array/zstd_codec.json new file mode 100644 index 0000000000..03de6a9420 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/zstd_codec.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [128], + "data_type": "int8", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [64]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes"}, + {"name": "zstd", "configuration": {"level": 3, "checksum": false}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/__init__.py b/packages/zarr-metadata/tests/v3/chunk_grid/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/__init__.py b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/cases.json b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/cases.json new file mode 100644 index 0000000000..c01580c17a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/cases.json @@ -0,0 +1,32 @@ +{ + "explicit_per_dim": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [10, 20, 30, 40], + [50] + ] + } + }, + "uniform_dim_shorthand": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [10, 20, 30, 40], + 50 + ] + } + }, + "with_rle_pair": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [[10, 5], 5, 5], + [15, 15] + ] + } + } +} diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/test_fixtures.py new file mode 100644 index 0000000000..cdef26d0a3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate rectilinear chunk grid fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_grid.rectilinear import RectilinearChunkGridMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_grid(case: object) -> None: + TypeAdapter(RectilinearChunkGridMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/regular/__init__.py b/packages/zarr-metadata/tests/v3/chunk_grid/regular/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/regular/cases.json b/packages/zarr-metadata/tests/v3/chunk_grid/regular/cases.json new file mode 100644 index 0000000000..2ffdef9007 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/regular/cases.json @@ -0,0 +1,14 @@ +{ + "1d": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "2d": { + "name": "regular", + "configuration": {"chunk_shape": [10, 20]} + }, + "3d": { + "name": "regular", + "configuration": {"chunk_shape": [5, 10, 15]} + } +} diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/regular/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_grid/regular/test_fixtures.py new file mode 100644 index 0000000000..9fba28d3ce --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/regular/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate regular chunk grid fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_grid.regular import RegularChunkGridMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_grid(case: object) -> None: + TypeAdapter(RegularChunkGridMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/__init__.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/__init__.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/cases.json b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/cases.json new file mode 100644 index 0000000000..db9d8f61de --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/cases.json @@ -0,0 +1,14 @@ +{ + "no_configuration": { + "name": "default" + }, + "slash_separator": { + "name": "default", + "configuration": {"separator": "/"} + }, + "dot_separator": { + "name": "default", + "configuration": {"separator": "."} + }, + "short_hand_name": "default" +} diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/test_fixtures.py new file mode 100644 index 0000000000..6618df0dd0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate default chunk-key encoding fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_key_encoding.default import DefaultChunkKeyEncodingMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_key_encoding(case: object) -> None: + TypeAdapter(DefaultChunkKeyEncodingMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/__init__.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/cases.json b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/cases.json new file mode 100644 index 0000000000..4ba65a6730 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/cases.json @@ -0,0 +1,14 @@ +{ + "no_configuration": { + "name": "v2" + }, + "dot_separator": { + "name": "v2", + "configuration": {"separator": "."} + }, + "slash_separator": { + "name": "v2", + "configuration": {"separator": "/"} + }, + "short_hand_name": "v2" +} diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/test_fixtures.py new file mode 100644 index 0000000000..7f43495239 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate v2-compatibility chunk-key encoding fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_key_encoding.v2 import V2ChunkKeyEncodingMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_key_encoding(case: object) -> None: + TypeAdapter(V2ChunkKeyEncodingMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/__init__.py b/packages/zarr-metadata/tests/v3/codec/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/blosc/__init__.py b/packages/zarr-metadata/tests/v3/codec/blosc/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/blosc/cases.json b/packages/zarr-metadata/tests/v3/codec/blosc/cases.json new file mode 100644 index 0000000000..20b476764a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/blosc/cases.json @@ -0,0 +1,21 @@ +{ + "with_typesize": { + "name": "blosc", + "configuration": { + "cname": "zstd", + "clevel": 5, + "shuffle": "shuffle", + "blocksize": 0, + "typesize": 4 + } + }, + "no_typesize": { + "name": "blosc", + "configuration": { + "cname": "lz4", + "clevel": 1, + "shuffle": "noshuffle", + "blocksize": 0 + } + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/blosc/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/blosc/test_fixtures.py new file mode 100644 index 0000000000..bdac8c32b0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/blosc/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate blosc codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.blosc import BloscCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(BloscCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/bytes/__init__.py b/packages/zarr-metadata/tests/v3/codec/bytes/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/bytes/cases.json b/packages/zarr-metadata/tests/v3/codec/bytes/cases.json new file mode 100644 index 0000000000..0c30d70a67 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/bytes/cases.json @@ -0,0 +1,18 @@ +{ + "little_endian": { + "name": "bytes", + "configuration": {"endian": "little"} + }, + "big_endian": { + "name": "bytes", + "configuration": {"endian": "big"} + }, + "no_endian": { + "name": "bytes", + "configuration": {} + }, + "no_configuration": { + "name": "bytes" + }, + "short_hand_name": "bytes" +} diff --git a/packages/zarr-metadata/tests/v3/codec/bytes/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/bytes/test_fixtures.py new file mode 100644 index 0000000000..ec725e9ba0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/bytes/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate bytes codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.bytes import BytesCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(BytesCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/cast_value/__init__.py b/packages/zarr-metadata/tests/v3/codec/cast_value/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/cast_value/cases.json b/packages/zarr-metadata/tests/v3/codec/cast_value/cases.json new file mode 100644 index 0000000000..90771d5f76 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/cast_value/cases.json @@ -0,0 +1,60 @@ +{ + "minimal": { + "name": "cast_value", + "configuration": {"data_type": "uint8"} + }, + "named_config_dtype": { + "name": "cast_value", + "configuration": { + "data_type": { + "name": "numpy.datetime64", + "configuration": {"unit": "ns", "scale_factor": 1} + } + } + }, + "with_rounding": { + "name": "cast_value", + "configuration": { + "data_type": "int16", + "rounding": "towards-zero" + } + }, + "with_out_of_range_clamp": { + "name": "cast_value", + "configuration": { + "data_type": "int8", + "out_of_range": "clamp" + } + }, + "with_out_of_range_wrap": { + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "out_of_range": "wrap" + } + }, + "with_scalar_map_encode_only": { + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "scalar_map": { + "encode": [["NaN", 0]] + } + } + }, + "numpy_compat_full_example": { + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "rounding": "towards-zero", + "out_of_range": "wrap", + "scalar_map": { + "encode": [ + ["NaN", 0], + ["+Infinity", 0], + ["-Infinity", 0] + ] + } + } + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/cast_value/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/cast_value/test_fixtures.py new file mode 100644 index 0000000000..695e25f883 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/cast_value/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate cast_value codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.cast_value import CastValueCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(CastValueCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/crc32c/__init__.py b/packages/zarr-metadata/tests/v3/codec/crc32c/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/crc32c/cases.json b/packages/zarr-metadata/tests/v3/codec/crc32c/cases.json new file mode 100644 index 0000000000..af89eed012 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/crc32c/cases.json @@ -0,0 +1,10 @@ +{ + "no_configuration": { + "name": "crc32c" + }, + "empty_configuration": { + "name": "crc32c", + "configuration": {} + }, + "short_hand_name": "crc32c" +} diff --git a/packages/zarr-metadata/tests/v3/codec/crc32c/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/crc32c/test_fixtures.py new file mode 100644 index 0000000000..906daae6da --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/crc32c/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate crc32c codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.crc32c import Crc32cCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(Crc32cCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/gzip/__init__.py b/packages/zarr-metadata/tests/v3/codec/gzip/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/gzip/cases.json b/packages/zarr-metadata/tests/v3/codec/gzip/cases.json new file mode 100644 index 0000000000..7d5e1e6f94 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/gzip/cases.json @@ -0,0 +1,6 @@ +{ + "with_level": { + "name": "gzip", + "configuration": {"level": 5} + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/gzip/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/gzip/test_fixtures.py new file mode 100644 index 0000000000..e198971ee7 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/gzip/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate gzip codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.gzip import GzipCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(GzipCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/scale_offset/__init__.py b/packages/zarr-metadata/tests/v3/codec/scale_offset/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/scale_offset/cases.json b/packages/zarr-metadata/tests/v3/codec/scale_offset/cases.json new file mode 100644 index 0000000000..c96e214007 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/scale_offset/cases.json @@ -0,0 +1,26 @@ +{ + "no_configuration": { + "name": "scale_offset" + }, + "empty_configuration": { + "name": "scale_offset", + "configuration": {} + }, + "offset_only": { + "name": "scale_offset", + "configuration": {"offset": 5} + }, + "scale_only": { + "name": "scale_offset", + "configuration": {"scale": 0.1} + }, + "scale_and_offset": { + "name": "scale_offset", + "configuration": {"offset": 5, "scale": 0.1} + }, + "string_encoded_scalar": { + "name": "scale_offset", + "configuration": {"offset": "NaN"} + }, + "short_hand_name": "scale_offset" +} diff --git a/packages/zarr-metadata/tests/v3/codec/scale_offset/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/scale_offset/test_fixtures.py new file mode 100644 index 0000000000..e0e62b9d56 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/scale_offset/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate scale_offset codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.scale_offset import ScaleOffsetCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(ScaleOffsetCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/sharding_indexed/__init__.py b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/sharding_indexed/cases.json b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/cases.json new file mode 100644 index 0000000000..2862dae4a7 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/cases.json @@ -0,0 +1,30 @@ +{ + "with_index_location": { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [64, 64], + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "gzip", "configuration": {"level": 1}} + ], + "index_codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ], + "index_location": "end" + } + }, + "no_index_location": { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [128], + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ], + "index_codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ] + } + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/sharding_indexed/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/test_fixtures.py new file mode 100644 index 0000000000..e3e61e9e4d --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate sharding_indexed codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.sharding_indexed import ShardingIndexedCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(ShardingIndexedCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/transpose/__init__.py b/packages/zarr-metadata/tests/v3/codec/transpose/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/transpose/cases.json b/packages/zarr-metadata/tests/v3/codec/transpose/cases.json new file mode 100644 index 0000000000..6adcc6948a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/transpose/cases.json @@ -0,0 +1,6 @@ +{ + "reversed_3d": { + "name": "transpose", + "configuration": {"order": [2, 1, 0]} + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/transpose/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/transpose/test_fixtures.py new file mode 100644 index 0000000000..4bd7c99bc8 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/transpose/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate transpose codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.transpose import TransposeCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(TransposeCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/zstd/__init__.py b/packages/zarr-metadata/tests/v3/codec/zstd/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/zstd/cases.json b/packages/zarr-metadata/tests/v3/codec/zstd/cases.json new file mode 100644 index 0000000000..77733fe054 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/zstd/cases.json @@ -0,0 +1,6 @@ +{ + "default": { + "name": "zstd", + "configuration": {"level": 3, "checksum": false} + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/zstd/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/zstd/test_fixtures.py new file mode 100644 index 0000000000..a1981211a3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/zstd/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate zstd codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.zstd import ZstdCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(ZstdCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/consolidated/__init__.py b/packages/zarr-metadata/tests/v3/consolidated/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/consolidated/minimal.json b/packages/zarr-metadata/tests/v3/consolidated/minimal.json new file mode 100644 index 0000000000..1f2ab2ad61 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/consolidated/minimal.json @@ -0,0 +1,5 @@ +{ + "kind": "inline", + "must_understand": false, + "metadata": {} +} diff --git a/packages/zarr-metadata/tests/v3/consolidated/test_fixtures.py b/packages/zarr-metadata/tests/v3/consolidated/test_fixtures.py new file mode 100644 index 0000000000..d052b16986 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/consolidated/test_fixtures.py @@ -0,0 +1,20 @@ +"""Decode v3 consolidated metadata fixtures via pydantic.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV3ConsolidatedMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/consolidated/with_array_and_group.json b/packages/zarr-metadata/tests/v3/consolidated/with_array_and_group.json new file mode 100644 index 0000000000..65ac70f7ac --- /dev/null +++ b/packages/zarr-metadata/tests/v3/consolidated/with_array_and_group.json @@ -0,0 +1,27 @@ +{ + "kind": "inline", + "must_understand": false, + "metadata": { + "child_group": { + "zarr_format": 3, + "node_type": "group" + }, + "child_array": { + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] + } + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/__init__.py b/packages/zarr-metadata/tests/v3/data_type/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/bool/__init__.py b/packages/zarr-metadata/tests/v3/data_type/bool/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/bool/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/bool/fill_values.json new file mode 100644 index 0000000000..955baa58cc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bool/fill_values.json @@ -0,0 +1,4 @@ +{ + "true": true, + "false": false +} diff --git a/packages/zarr-metadata/tests/v3/data_type/bool/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/bool/test_fixtures.py new file mode 100644 index 0000000000..e924015b1d --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bool/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate bool fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.bool import BoolFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(BoolFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/__init__.py b/packages/zarr-metadata/tests/v3/data_type/bytes/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/bytes/fill_values.json new file mode 100644 index 0000000000..6e55b7313c --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bytes/fill_values.json @@ -0,0 +1,4 @@ +{ + "tuple": [1, 2, 3], + "base64": "AQID" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/bytes/test_fixtures.py new file mode 100644 index 0000000000..9ee62fb140 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bytes/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate variable-length bytes fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.bytes import BytesFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(BytesFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/bytes/test_validators.py new file mode 100644 index 0000000000..7f41d878f8 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bytes/test_validators.py @@ -0,0 +1,43 @@ +"""Cover the `base64_bytes` brand validator. + +The pydantic-driven fixture tests don't enforce the base64 alphabet or +length-multiple-of-4 constraint because `Base64Bytes` is a `NewType`, +which pydantic treats as plain `str`. Direct coverage of the validator +function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.bytes import base64_bytes + +VALID = [ + "", # empty is valid base64 (length 0, multiple of 4) + "AQID", # [1, 2, 3] + "AAAA", # [0, 0, 0] + "////", # [255, 255, 255] + "abcd", + "AB==", # padding + "ABC=", # padding +] +INVALID = [ + "AB", # length 2, not multiple of 4 + "ABC", # length 3, not multiple of 4 + "ABCDE", # length 5 + "AB-D", # url-safe alphabet, not standard + "AB_D", # url-safe alphabet, not standard + "AB!D", # not base64 char + "AB CD", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert base64_bytes(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="standard-alphabet base64"): + base64_bytes(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/complex128/__init__.py b/packages/zarr-metadata/tests/v3/data_type/complex128/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/complex128/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/complex128/fill_values.json new file mode 100644 index 0000000000..c30f15a55c --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex128/fill_values.json @@ -0,0 +1,7 @@ +{ + "numeric": [1.5, 2.5], + "zero": [0.0, 0.0], + "with_sentinel_components": ["-Infinity", "NaN"], + "mixed_numeric_and_sentinel": [1.0, "Infinity"], + "with_hex_components": ["0x7ff8000000000000", "0x0000000000000000"] +} diff --git a/packages/zarr-metadata/tests/v3/data_type/complex128/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/complex128/test_fixtures.py new file mode 100644 index 0000000000..3536dc6ef3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex128/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate complex128 fill-value fixtures. + +A v3 complex fill_value is a two-element JSON array `[real, imag]` where +each component is shaped per the corresponding float's fill value: a +number, one of the named sentinels (`"NaN"`, `"Infinity"`, +`"-Infinity"`), or a hex string of the underlying float's bits. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.complex128 import Complex128FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Complex128FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/complex64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/complex64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/complex64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/complex64/fill_values.json new file mode 100644 index 0000000000..65d302f496 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex64/fill_values.json @@ -0,0 +1,7 @@ +{ + "numeric": [1.5, 2.5], + "zero": [0.0, 0.0], + "with_sentinel_components": ["-Infinity", "NaN"], + "mixed_numeric_and_sentinel": [1.0, "Infinity"], + "with_hex_components": ["0x7fc00000", "0x00000000"] +} diff --git a/packages/zarr-metadata/tests/v3/data_type/complex64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/complex64/test_fixtures.py new file mode 100644 index 0000000000..83682c74b1 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex64/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate complex64 fill-value fixtures. + +A v3 complex fill_value is a two-element JSON array `[real, imag]` where +each component is shaped per the corresponding float's fill value: a +number, one of the named sentinels (`"NaN"`, `"Infinity"`, +`"-Infinity"`), or a hex string of the underlying float's bits. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.complex64 import Complex64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Complex64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/__init__.py b/packages/zarr-metadata/tests/v3/data_type/float16/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/float16/fill_values.json new file mode 100644 index 0000000000..07034ffba5 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float16/fill_values.json @@ -0,0 +1,8 @@ +{ + "zero": 0.0, + "nan": "NaN", + "infinity": "Infinity", + "neg_infinity": "-Infinity", + "hex_zero": "0x0000", + "hex_signaling_nan": "0x7d00" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/float16/test_fixtures.py new file mode 100644 index 0000000000..2241398fb3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float16/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate float16 fill-value fixtures. + +A v3 float fill_value is a JSON number, one of the named non-finite +sentinels (`"NaN"`, `"Infinity"`, `"-Infinity"`), or a hex string +(`"0xYYYY"`) encoding the unsigned-integer representation of the IEEE +754 value. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.float16 import Float16FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Float16FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/float16/test_validators.py new file mode 100644 index 0000000000..c710f27ea4 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float16/test_validators.py @@ -0,0 +1,34 @@ +"""Cover the `hex_float16` brand validator. + +The pydantic-driven fixture tests don't enforce hex format because +`HexFloat16` is a `NewType`, which pydantic treats as plain `str`. +Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.float16 import hex_float16 + +VALID = ["0x0000", "0x7c00", "0x7d00", "0xffff", "0xFFFF", "0xAbCd"] +INVALID = [ + "", + "0000", # missing 0x + "0x000", # too short + "0x00000", # too long + "0x000g", # non-hex char + "0X0000", # uppercase X + " 0x0000 ", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert hex_float16(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="Expected '0x'"): + hex_float16(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/__init__.py b/packages/zarr-metadata/tests/v3/data_type/float32/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/float32/fill_values.json new file mode 100644 index 0000000000..ed6502f85a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float32/fill_values.json @@ -0,0 +1,9 @@ +{ + "zero": 0.0, + "nan": "NaN", + "infinity": "Infinity", + "neg_infinity": "-Infinity", + "hex_zero": "0x00000000", + "hex_canonical_nan": "0x7fc00000", + "hex_signaling_nan": "0x7fa00000" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/float32/test_fixtures.py new file mode 100644 index 0000000000..bd943bd96e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float32/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate float32 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.float32 import Float32FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Float32FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/float32/test_validators.py new file mode 100644 index 0000000000..e859d91c26 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float32/test_validators.py @@ -0,0 +1,41 @@ +"""Cover the `hex_float32` brand validator. + +The pydantic-driven fixture tests don't enforce hex format because +`HexFloat32` is a `NewType`, which pydantic treats as plain `str`. +Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.float32 import hex_float32 + +VALID = [ + "0x00000000", + "0x7fc00000", # canonical NaN + "0x7fa00000", # signaling NaN + "0xffffffff", + "0xFFFFFFFF", + "0xDeadBeef", +] +INVALID = [ + "", + "00000000", # missing 0x + "0x0000000", # too short + "0x000000000", # too long + "0x0000000g", # non-hex char + "0X00000000", # uppercase X + " 0x00000000 ", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert hex_float32(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="Expected '0x'"): + hex_float32(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/float64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/float64/fill_values.json new file mode 100644 index 0000000000..76da958c63 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float64/fill_values.json @@ -0,0 +1,9 @@ +{ + "zero": 0.0, + "nan": "NaN", + "infinity": "Infinity", + "neg_infinity": "-Infinity", + "hex_zero": "0x0000000000000000", + "hex_canonical_nan": "0x7ff8000000000000", + "hex_signaling_nan": "0x7ff4000000000000" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/float64/test_fixtures.py new file mode 100644 index 0000000000..2e4566ae58 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float64/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate float64 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.float64 import Float64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Float64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/float64/test_validators.py new file mode 100644 index 0000000000..938bf2a1a5 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float64/test_validators.py @@ -0,0 +1,41 @@ +"""Cover the `hex_float64` brand validator. + +The pydantic-driven fixture tests don't enforce hex format because +`HexFloat64` is a `NewType`, which pydantic treats as plain `str`. +Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.float64 import hex_float64 + +VALID = [ + "0x0000000000000000", + "0x7ff8000000000000", # canonical NaN + "0x7ff4000000000000", # signaling NaN + "0xffffffffffffffff", + "0xFFFFFFFFFFFFFFFF", + "0xDeadBeefCafeBabe", +] +INVALID = [ + "", + "0000000000000000", # missing 0x + "0x000000000000000", # too short + "0x00000000000000000", # too long + "0x000000000000000g", # non-hex char + "0X0000000000000000", # uppercase X + " 0x0000000000000000 ", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert hex_float64(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="Expected '0x'"): + hex_float64(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/int16/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int16/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int16/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int16/fill_values.json new file mode 100644 index 0000000000..af8304c51b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int16/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -32768, + "max": 32767, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int16/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int16/test_fixtures.py new file mode 100644 index 0000000000..2149947c2d --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int16/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int16 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int16 import Int16FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int16FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/int32/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int32/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int32/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int32/fill_values.json new file mode 100644 index 0000000000..d0bf317770 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int32/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -2147483648, + "max": 2147483647, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int32/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int32/test_fixtures.py new file mode 100644 index 0000000000..b1dbb6d370 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int32/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int32 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int32 import Int32FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int32FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/int64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int64/fill_values.json new file mode 100644 index 0000000000..a97c5b3f34 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int64/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -9223372036854775808, + "max": 9223372036854775807, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int64/test_fixtures.py new file mode 100644 index 0000000000..957bf2296b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int64/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int64 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int64 import Int64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/int8/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int8/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int8/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int8/fill_values.json new file mode 100644 index 0000000000..716f347c19 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int8/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -128, + "max": 127, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int8/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int8/test_fixtures.py new file mode 100644 index 0000000000..ef9438dad0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int8/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int8 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int8 import Int8FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int8FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/data_type.json b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/data_type.json new file mode 100644 index 0000000000..f94c1b45da --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/data_type.json @@ -0,0 +1,7 @@ +{ + "name": "numpy.datetime64", + "configuration": { + "unit": "ns", + "scale_factor": 1 + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/fill_values.json new file mode 100644 index 0000000000..b628657396 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/fill_values.json @@ -0,0 +1,4 @@ +{ + "int": 12345, + "nat": "NaT" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/test_fixtures.py new file mode 100644 index 0000000000..7609b42d70 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate numpy.datetime64 dtype value and fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.numpy_datetime64 import ( + NumpyDatetime64, + NumpyDatetime64FillValue, +) + +DIR = Path(__file__).parent +FILL_VALUES: dict[str, object] = json.loads((DIR / "fill_values.json").read_text()) + + +def test_data_type() -> None: + TypeAdapter(NumpyDatetime64).validate_python(json.loads((DIR / "data_type.json").read_text())) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(NumpyDatetime64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/data_type.json b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/data_type.json new file mode 100644 index 0000000000..e49ec06e39 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/data_type.json @@ -0,0 +1,7 @@ +{ + "name": "numpy.timedelta64", + "configuration": { + "unit": "s", + "scale_factor": 1 + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/fill_values.json new file mode 100644 index 0000000000..cd3c94c077 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/fill_values.json @@ -0,0 +1,4 @@ +{ + "int": 42, + "nat": "NaT" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/test_fixtures.py new file mode 100644 index 0000000000..2a6c651582 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/test_fixtures.py @@ -0,0 +1,33 @@ +"""Validate numpy.timedelta64 dtype value and fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import get_args + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.numpy_timedelta64 import ( + NUMPY_TIME_UNIT, + NumpyTimedelta64, + NumpyTimedelta64FillValue, + NumpyTimeUnit, +) + +DIR = Path(__file__).parent +FILL_VALUES: dict[str, object] = json.loads((DIR / "fill_values.json").read_text()) + + +def test_data_type() -> None: + TypeAdapter(NumpyTimedelta64).validate_python(json.loads((DIR / "data_type.json").read_text())) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(NumpyTimedelta64FillValue).validate_python(case) + + +def test_time_unit_constant_matches_literal() -> None: + assert set(NUMPY_TIME_UNIT) == set(get_args(NumpyTimeUnit)) diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/__init__.py b/packages/zarr-metadata/tests/v3/data_type/raw/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/raw/fill_values.json new file mode 100644 index 0000000000..60cf0760fc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/raw/fill_values.json @@ -0,0 +1,3 @@ +{ + "all_zero_4_bytes": [0, 0, 0, 0] +} diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/raw/test_fixtures.py new file mode 100644 index 0000000000..ee35ebe267 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/raw/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate raw-bytes (`r`) fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.raw import RawBytesFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(RawBytesFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/raw/test_validators.py new file mode 100644 index 0000000000..c1524aed96 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/raw/test_validators.py @@ -0,0 +1,33 @@ +"""Cover the `raw_bytes_dtype_name` brand validator. + +The pydantic-driven fixture tests don't enforce the `r` shape +because `RawBytesDataTypeName` is a `NewType`, which pydantic treats +as plain `str`. Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.raw import raw_bytes_dtype_name + +VALID = ["r8", "r16", "r24", "r256", "r1024"] +INVALID_FORMAT = ["", "8", "R8", "r", "r-8", "r8 ", " r8", "r8r8"] +INVALID_BITS = ["r0", "r1", "r7", "r9", "r15", "r17"] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert raw_bytes_dtype_name(value) == value + + +@pytest.mark.parametrize("value", INVALID_FORMAT) +def test_invalid_format(value: str) -> None: + with pytest.raises(ValueError, match="Expected 'r' followed by"): + raw_bytes_dtype_name(value) + + +@pytest.mark.parametrize("value", INVALID_BITS) +def test_invalid_bit_count(value: str) -> None: + with pytest.raises(ValueError, match="positive multiple of 8"): + raw_bytes_dtype_name(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/string/__init__.py b/packages/zarr-metadata/tests/v3/data_type/string/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/string/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/string/fill_values.json new file mode 100644 index 0000000000..d9dfba1658 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/string/fill_values.json @@ -0,0 +1,6 @@ +{ + "empty": "", + "ascii": "hello", + "unicode": "héllo 世界", + "with_escapes": "line1\nline2\t\"quoted\"" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/string/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/string/test_fixtures.py new file mode 100644 index 0000000000..69a8038bdd --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/string/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate string fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.string import StringFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(StringFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/__init__.py b/packages/zarr-metadata/tests/v3/data_type/struct/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/data_type.json b/packages/zarr-metadata/tests/v3/data_type/struct/data_type.json new file mode 100644 index 0000000000..999326076e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/struct/data_type.json @@ -0,0 +1,16 @@ +{ + "name": "struct", + "configuration": { + "fields": [ + {"name": "x", "data_type": "float32"}, + {"name": "y", "data_type": "float32"}, + { + "name": "when", + "data_type": { + "name": "numpy.datetime64", + "configuration": {"unit": "ns", "scale_factor": 1} + } + } + ] + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/struct/fill_values.json new file mode 100644 index 0000000000..e658d70af0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/struct/fill_values.json @@ -0,0 +1,7 @@ +{ + "all_fields": { + "x": 0.0, + "y": 1.0, + "when": 0 + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/struct/test_fixtures.py new file mode 100644 index 0000000000..15e6257fc1 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/struct/test_fixtures.py @@ -0,0 +1,23 @@ +"""Validate struct dtype value and fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.struct import Struct, StructFillValue + +DIR = Path(__file__).parent +FILL_VALUES: dict[str, object] = json.loads((DIR / "fill_values.json").read_text()) + + +def test_data_type() -> None: + TypeAdapter(Struct).validate_python(json.loads((DIR / "data_type.json").read_text())) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(StructFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/test_dtype_names.py b/packages/zarr-metadata/tests/v3/data_type/test_dtype_names.py new file mode 100644 index 0000000000..152c1b5fdc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/test_dtype_names.py @@ -0,0 +1,61 @@ +"""Validate every primitive Zarr v3 data-type name string. + +Primitive dtypes are encoded as bare strings in the `data_type` field of a +v3 array metadata document (e.g. `"int32"`, `"float64"`). Each must +validate as its declared per-dtype `*Name` literal type. +""" + +from __future__ import annotations + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.bool import BOOL_DATA_TYPE_NAME, BoolDataTypeName +from zarr_metadata.v3.data_type.bytes import BYTES_DATA_TYPE_NAME, BytesDataTypeName +from zarr_metadata.v3.data_type.complex64 import COMPLEX64_DATA_TYPE_NAME, Complex64DataTypeName +from zarr_metadata.v3.data_type.complex128 import COMPLEX128_DATA_TYPE_NAME, Complex128DataTypeName +from zarr_metadata.v3.data_type.float16 import FLOAT16_DATA_TYPE_NAME, Float16DataTypeName +from zarr_metadata.v3.data_type.float32 import FLOAT32_DATA_TYPE_NAME, Float32DataTypeName +from zarr_metadata.v3.data_type.float64 import FLOAT64_DATA_TYPE_NAME, Float64DataTypeName +from zarr_metadata.v3.data_type.int8 import INT8_DATA_TYPE_NAME, Int8DataTypeName +from zarr_metadata.v3.data_type.int16 import INT16_DATA_TYPE_NAME, Int16DataTypeName +from zarr_metadata.v3.data_type.int32 import INT32_DATA_TYPE_NAME, Int32DataTypeName +from zarr_metadata.v3.data_type.int64 import INT64_DATA_TYPE_NAME, Int64DataTypeName +from zarr_metadata.v3.data_type.raw import raw_bytes_dtype_name +from zarr_metadata.v3.data_type.string import STRING_DATA_TYPE_NAME, StringDataTypeName +from zarr_metadata.v3.data_type.uint8 import UINT8_DATA_TYPE_NAME, Uint8DataTypeName +from zarr_metadata.v3.data_type.uint16 import UINT16_DATA_TYPE_NAME, Uint16DataTypeName +from zarr_metadata.v3.data_type.uint32 import UINT32_DATA_TYPE_NAME, Uint32DataTypeName +from zarr_metadata.v3.data_type.uint64 import UINT64_DATA_TYPE_NAME, Uint64DataTypeName + +# (name_string, per-dtype literal type) +PRIMITIVE_DTYPES = [ + (BOOL_DATA_TYPE_NAME, BoolDataTypeName), + (INT8_DATA_TYPE_NAME, Int8DataTypeName), + (INT16_DATA_TYPE_NAME, Int16DataTypeName), + (INT32_DATA_TYPE_NAME, Int32DataTypeName), + (INT64_DATA_TYPE_NAME, Int64DataTypeName), + (UINT8_DATA_TYPE_NAME, Uint8DataTypeName), + (UINT16_DATA_TYPE_NAME, Uint16DataTypeName), + (UINT32_DATA_TYPE_NAME, Uint32DataTypeName), + (UINT64_DATA_TYPE_NAME, Uint64DataTypeName), + (FLOAT16_DATA_TYPE_NAME, Float16DataTypeName), + (FLOAT32_DATA_TYPE_NAME, Float32DataTypeName), + (FLOAT64_DATA_TYPE_NAME, Float64DataTypeName), + (COMPLEX64_DATA_TYPE_NAME, Complex64DataTypeName), + (COMPLEX128_DATA_TYPE_NAME, Complex128DataTypeName), + (STRING_DATA_TYPE_NAME, StringDataTypeName), + (BYTES_DATA_TYPE_NAME, BytesDataTypeName), +] + + +@pytest.mark.parametrize(("name", "literal_type"), PRIMITIVE_DTYPES, ids=lambda x: str(x)) +def test_primitive_against_literal(name: str, literal_type: object) -> None: + """The dtype name validates against its declared Literal type.""" + TypeAdapter(literal_type).validate_python(name) + + +@pytest.mark.parametrize("raw_name", ["r8", "r16", "r24", "r256", "r1024"], ids=str) +def test_raw_bytes_name(raw_name: str) -> None: + """`r` names pass the raw_bytes_dtype_name validator.""" + raw_bytes_dtype_name(raw_name) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint16/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint16/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint16/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint16/fill_values.json new file mode 100644 index 0000000000..60934f030e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint16/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 65535 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint16/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint16/test_fixtures.py new file mode 100644 index 0000000000..f4afaafa8b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint16/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint16 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint16 import Uint16FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint16FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint32/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint32/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint32/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint32/fill_values.json new file mode 100644 index 0000000000..1b003f6fab --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint32/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 4294967295 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint32/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint32/test_fixtures.py new file mode 100644 index 0000000000..cf94a6a829 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint32/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint32 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint32 import Uint32FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint32FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint64/fill_values.json new file mode 100644 index 0000000000..145703c360 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint64/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 18446744073709551615 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint64/test_fixtures.py new file mode 100644 index 0000000000..71851cfeec --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint64/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint64 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint64 import Uint64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint8/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint8/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint8/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint8/fill_values.json new file mode 100644 index 0000000000..70e8d5d5bc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint8/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 255 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint8/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint8/test_fixtures.py new file mode 100644 index 0000000000..4866753971 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint8/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint8 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint8 import Uint8FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint8FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/group/__init__.py b/packages/zarr-metadata/tests/v3/group/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/group/minimal.json b/packages/zarr-metadata/tests/v3/group/minimal.json new file mode 100644 index 0000000000..7e86f1938a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/minimal.json @@ -0,0 +1,4 @@ +{ + "zarr_format": 3, + "node_type": "group" +} diff --git a/packages/zarr-metadata/tests/v3/group/test_fixtures.py b/packages/zarr-metadata/tests/v3/group/test_fixtures.py new file mode 100644 index 0000000000..ffcdedef2b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/test_fixtures.py @@ -0,0 +1,20 @@ +"""Decode v3 group metadata fixtures via pydantic.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV3GroupMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/group/with_attributes.json b/packages/zarr-metadata/tests/v3/group/with_attributes.json new file mode 100644 index 0000000000..69804b3db0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/with_attributes.json @@ -0,0 +1,8 @@ +{ + "zarr_format": 3, + "node_type": "group", + "attributes": { + "label": "root", + "spatial_units": ["meter", "meter"] + } +} diff --git a/packages/zarr-metadata/tests/v3/group/with_extra_field.json b/packages/zarr-metadata/tests/v3/group/with_extra_field.json new file mode 100644 index 0000000000..01696b53cf --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/with_extra_field.json @@ -0,0 +1,9 @@ +{ + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "must_understand": false, + "kind": "inline", + "metadata": {} + } +} diff --git a/pyproject.toml b/pyproject.toml index b1077e3e5d..4cfe02b0e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,11 +2,23 @@ requires = ["hatchling>=1.29.0", "hatch-vcs"] build-backend = "hatchling.build" +# An allowlist, not a blocklist: anything new — a subpackage under `packages/`, a +# config file in the repository root — stays out of the sdist unless it is named +# here. Beyond `src` and `tests`, the entries are what keeps the shipped test +# suite and docs build runnable from an unpacked sdist: `tests/test_docs.py` +# walks `docs/` and `testpaths` collects `docs/user-guide`; the pages under +# `docs/user-guide/examples/` pull their source out of `examples/` via pymdownx +# snippet includes; `mkdocs.yml` and `mkdocs_hooks.py` let `mkdocs build` run +# too. `pyproject.toml`, `README.md`, `LICENSE.txt` and `.gitignore` are added by +# hatchling itself. [tool.hatch.build.targets.sdist] -exclude = [ - "/.github", - "/bench", +include = [ + "/src", + "/tests", "/docs", + "/examples", + "/mkdocs.yml", + "/mkdocs_hooks.py", ] [project] @@ -29,15 +41,15 @@ maintainers = [ { name = "Tom Augspurger", email = "tom.w.augspurger@gmail.com" }, { name = "Deepak Cherian" } ] -requires-python = ">=3.11" -# If you add a new dependency here, please also add it to .pre-commit-config.yaml +requires-python = ">=3.12" dependencies = [ 'packaging>=22.0', - 'numpy>=2.0', + 'numpy>=2', 'numcodecs>=0.14', 'google-crc32c>=1.5', - 'typing_extensions>=4.12', + 'typing_extensions>=4.14', 'donfig>=0.8', + 'msgspec>=0.19', ] dynamic = [ @@ -52,9 +64,9 @@ classifiers = [ 'Topic :: Software Development :: Libraries :: Python Modules', 'Operating System :: Unix', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: 3.13', + 'Programming Language :: Python :: 3.14', ] license = "MIT" license-files = ["LICENSE.txt"] @@ -67,8 +79,9 @@ remote = [ "obstore>=0.5.1", ] gpu = [ - "cupy-cuda12x", + "cupy-cuda12x; sys_platform != 'darwin'", ] +cast-value-rs = ["cast-value-rs>=0.4.2"] cli = ["typer"] optional = ["universal-pathlib"] @@ -83,20 +96,30 @@ Discussions = "https://github.com/zarr-developers/zarr-python/discussions" documentation = "https://zarr.readthedocs.io/" homepage = "https://github.com/zarr-developers/zarr-python" +# Dev *tooling* is pinned to exact versions for reproducible CI: the hatch envs +# (see `tool.hatch.envs.*`) and bare `uv run` resolve these groups fresh from +# PyPI and do NOT consult uv.lock, so an unrelated tooling release can break CI +# without any change on our side (e.g. the pytest 9.1.0 `duplicate +# parametrization` regression). Runtime/integration deps (fsspec, obstore, s3fs, +# botocore, numcodecs, universal-pathlib) are intentionally left floating so the +# `optional` test matrix keeps exercising their latest releases; their floor and +# bleeding edge are covered by the `min_deps` and `upstream` hatch envs. Bump the +# pins deliberately, e.g. via dependabot or `uv lock --upgrade`. [dependency-groups] test = [ - "coverage>=7.10", - "pytest", - "pytest-asyncio", - "pytest-cov", - "pytest-accept", - "numpydoc", - "hypothesis", - "pytest-xdist", - "pytest-benchmark", - "pytest-codspeed", - "tomlkit", - "uv", + "coverage==7.15.4", + "pytest==9.1.1", + "pytest-asyncio==1.4.0", + "pytest-cov==7.1.0", + "pytest-accept==0.3.0", + "numpydoc==1.10.0", + "hypothesis==6.165.5", + "pytest-reportlog==1.0.0", + "pytest-xdist==3.8.0", + "pytest-benchmark==5.2.3", + "pytest-codspeed==5.0.3", + "tomlkit==0.15.1", + "uv==0.12.3", ] remote-tests = [ {include-group = "test"}, @@ -104,34 +127,37 @@ remote-tests = [ "obstore>=0.5.1", "botocore", "s3fs>=2023.10.0", - "moto[s3,server]", - "requests", + "moto[s3,server]==5.2.2", + "requests==2.34.2", +] +release = [ + "towncrier==25.8.0", ] docs = [ # Doc building - "mkdocs-material[imaging]>=9.6.14", - "mkdocs>=1.6.1", - "mkdocstrings>=0.29.1", - "mkdocstrings-python>=1.16.10", - "mike>=2.1.3", - "mkdocs-redirects>=1.2.0", - "markdown-exec[ansi]", - "griffe-inherited-docstrings", - "ruff", + "mkdocs-material[imaging]==9.7.7", + "mkdocs==1.6.1", + "mkdocstrings==1.0.6", + "mkdocstrings-python==2.0.5", + "mike==2.2.0", + "mkdocs-redirects==1.2.3", + "markdown-exec[ansi]==1.12.3", + "griffe-inherited-docstrings==1.1.3", + "ruff==0.16.2", # Changelog generation - "towncrier", + {include-group = "release"}, # Optional dependencies to run examples "numcodecs[msgpack]", "s3fs>=2023.10.0", - "astroid<4", - "pytest", + "astroid==4.3.0", + "pytest==9.1.1", ] dev = [ {include-group = "test"}, {include-group = "remote-tests"}, {include-group = "docs"}, "universal-pathlib", - "mypy", + "mypy==2.3.0", ] [tool.coverage.report] @@ -142,26 +168,30 @@ exclude_also = [ [tool.coverage.run] omit = [ "bench/compress_normal.py", - "src/zarr/testing/conftest.py", # only for downstream projects ] [tool.hatch] version.source = "vcs" +# Only consider zarr-python's own `v*` tags when deriving the version. Without +# this filter `git describe` matches the most recent tag of any shape, +# including the `zarr_metadata-v*` and `zarr_http_server-v*` tags used to +# release the subpackages under `packages/` — which would make a from-source +# build report e.g. a `0.2.x` version instead of `3.x`. +version.raw-options = { git_describe_command = "git describe --dirty --tags --long --match v*" } [tool.hatch.build] hooks.vcs.version-file = "src/zarr/_version.py" +[tool.hatch.envs.dev] +dependency-groups = ["dev"] + [tool.hatch.envs.test] dependency-groups = ["test"] [tool.hatch.envs.test.env-vars] -# Required to test with a pytest plugin; see https://pytest-cov.readthedocs.io/en/latest/plugins.html -COV_CORE_SOURCE = "src" -COV_CORE_CONFIG = ".coveragerc" -COV_CORE_DATAFILE = ".coverage.eager" [[tool.hatch.envs.test.matrix]] -python = ["3.11", "3.12", "3.13"] +python = ["3.12", "3.13", "3.14"] deps = ["minimal", "optional"] [tool.hatch.envs.test.overrides] @@ -169,38 +199,55 @@ matrix.deps.features = [ {value = "remote", if = ["optional"]}, {value = "optional", if = ["optional"]}, {value = "cli", if = ["optional"]}, + {value = "cast-value-rs", if = ["optional"]}, ] matrix.deps.dependency-groups = [ {value = "remote-tests", if = ["optional"]}, ] [tool.hatch.envs.test.scripts] -run-coverage = "pytest --cov-config=pyproject.toml --cov=src --cov-append --cov-report xml --junitxml=junit.xml -o junit_family=legacy" -run-coverage-html = "pytest --cov-config=pyproject.toml --cov=src --cov-append --cov-report html" -run = "run-coverage --no-cov --ignore tests/benchmarks" +run-coverage = [ + "coverage run --source=src -m pytest --ignore tests/benchmarks --junitxml=junit.xml -o junit_family=legacy {args:}", + "coverage xml", +] +run-coverage-html = [ + "coverage run --source=src -m pytest --ignore tests/benchmarks {args:}", + "coverage html", +] +run = "pytest --ignore tests/benchmarks" run-verbose = "run-coverage --verbose" -run-mypy = "mypy src" -run-hypothesis = "run-coverage -nauto --run-slow-hypothesis tests/test_properties.py tests/test_store/test_stateful*" +run-hypothesis = [ + "coverage run --source=src -m pytest -nauto --run-slow-hypothesis tests/test_properties.py tests/test_store/test_stateful* {args:}", + "coverage xml", +] run-benchmark = "pytest --benchmark-enable tests/benchmarks" +serve-coverage-html = "python -m http.server -d htmlcov 8000" list-env = "pip list" [tool.hatch.envs.gputest] template = "test" extra-dependencies = [ "universal_pathlib", + # Needed so tests/test_docs.py is collectable under `pytest -m gpu`; otherwise its + # module-level importorskip("pytest_examples") skips the whole module and the gpu + # docs example is never executed on GPU hardware. + "pytest-examples", ] features = ["gpu"] [[tool.hatch.envs.gputest.matrix]] -python = ["3.11", "3.12", "3.13"] +python = ["3.12", "3.13"] [tool.hatch.envs.gputest.scripts] -run-coverage = "pytest -m gpu --cov-config=pyproject.toml --cov=src --cov-report xml --junitxml=junit.xml -o junit_family=legacy --ignore tests/benchmarks" -run = "run-coverage --no-cov" +run-coverage = [ + "coverage run --source=src -m pytest -m gpu --junitxml=junit.xml -o junit_family=legacy --ignore tests/benchmarks {args:}", + "coverage xml", +] +run = "pytest -m gpu --ignore tests/benchmarks" [tool.hatch.envs.upstream] template = 'test' -python = "3.13" +python = "3.14" extra-dependencies = [ 'packaging @ git+https://github.com/pypa/packaging', 'numpy', # from scientific-python-nightly-wheels @@ -223,7 +270,7 @@ description = """Test environment for minimum supported dependencies See Spec 0000 for details and drop schedule: https://scientific-python.org/specs/spec-0000/ """ template = "test" -python = "3.11" +python = "3.12" features = ["remote"] dependency-groups = ["remote-tests"] extra-dependencies = [ @@ -232,16 +279,24 @@ extra-dependencies = [ 'numcodecs==0.14.*', # 0.14 needed for zarr3 codecs 'fsspec==2023.10.0', 's3fs==2023.10.0', - 'universal_pathlib==0.0.22', - 'typing_extensions==4.12.*', + 'universal_pathlib==0.2.0', + 'typing_extensions==4.14.*', 'donfig==0.8.*', 'obstore==0.5.*', + 'msgspec==0.19.*', ] +[tool.hatch.envs.default] +installer = "uv" + [tool.hatch.envs.docs] features = ['remote'] dependency-groups = ['docs'] +[tool.hatch.envs.docs.env-vars] +DISABLE_MKDOCS_2_WARNING = "true" +NO_MKDOCS_2_WARNING = "true" + [tool.hatch.envs.docs.scripts] serve = "mkdocs serve --watch src" build = "mkdocs build" @@ -251,9 +306,8 @@ readthedocs = "rm -rf $READTHEDOCS_OUTPUT/html && cp -r site $READTHEDOCS_OUTPUT [tool.hatch.envs.doctest] description = "Test environment for validating executable code blocks in documentation" features = ['remote'] -dependency-groups = ['test'] +dependency-groups = ['remote-tests'] extra-dependencies = [ - "s3fs>=2023.10.0", "pytest-examples", ] @@ -343,13 +397,16 @@ ignore = [ "tests/**" = ["ANN001", "ANN201", "RUF029", "SIM117", "SIM300"] [tool.mypy] -python_version = "3.11" +files = ["src", "tests"] +python_version = "3.12" ignore_missing_imports = true namespace_packages = false - +pretty = true +show_error_code_links = true +show_error_context = true strict = true warn_unreachable = true -enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] +enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool", "truthy-iterable"] [[tool.mypy.overrides]] module = [ @@ -359,7 +416,6 @@ module = [ "tests.test_config", "tests.test_store.test_zip", "tests.test_store.test_local", - "tests.test_store.test_fsspec", "tests.test_store.test_memory", "tests.test_codecs.test_codecs", "tests.test_metadata.*", @@ -375,6 +431,7 @@ strict = false # and fix the errors [[tool.mypy.overrides]] module = [ + "tests.test_store.test_fsspec", "tests.test_group", "tests.test_indexing", "tests.test_properties", @@ -384,11 +441,21 @@ module = [ ignore_errors = true [tool.pytest.ini_options] -minversion = "7" -testpaths = ["tests", "docs/user-guide"] +minversion = "9" +testpaths = ["src", "tests", "docs/user-guide"] log_cli_level = "INFO" log_level = "INFO" -xfail_strict = true +# Enables strict_config, strict_markers, strict_xfail, strict_parametrization_ids, and +# any strictness options added in future pytest releases. Note that the equivalent +# `--strict-config`/`--strict-markers` flags were silently ignored when passed via +# addopts before pytest 9.1 (pytest#14442), so this option is the reliable spelling. +strict = true +# Turn deadlocks into loud failures: if a single test exceeds this many seconds, dump +# every thread's traceback and kill the run (exit_on_timeout is new in pytest 9). Sized +# far above the slowest legitimate test (~20s locally; slower under coverage/Windows/ +# nightly stateful-hypothesis runs) so only a genuine hang can trip it. +faulthandler_timeout = 600 +faulthandler_exit_on_timeout = true asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" doctest_optionflags = [ @@ -400,7 +467,10 @@ addopts = [ "--benchmark-columns", "min,mean,stddev,outliers,rounds,iterations", "--benchmark-disable", # benchmark routines run as tests without benchmarking instrumentation "--durations", "10", - "-ra", "--strict-config", "--strict-markers", + "-ra", + "--doctest-modules", + "--ignore=tests/test_regression/scripts", + "--ignore=src/zarr/_cli", ] filterwarnings = [ "error", @@ -409,17 +479,30 @@ filterwarnings = [ # s3fs finalizers can fail during session cleanup when aiobotocore sessions are garbage # collected without being entered. This is a known issue in s3fs/aiobotocore, and pytest # per-test filterwarnings markers can't catch it (https://github.com/pytest-dev/pytest/issues/14096). - "ignore:Exception ignored in[\\s\\S]*Session was never entered:pytest.PytestUnraisableExceptionWarning", + "ignore:Exception ignored ((on calling weakref callback)|(in[\\s\\S]*Session was never entered)):pytest.PytestUnraisableExceptionWarning", + # pytest-asyncio implicitly creates an event loop in _get_event_loop_no_warn during + # fixture setup/teardown and never closes it (allocation site verified with + # PYTHONTRACEMALLOC: pytest_asyncio/plugin.py). When the garbage collector reclaims + # that loop (and its self-pipe socketpair: AF_UNIX family=1 on POSIX, emulated with + # AF_INET family=2 on Windows) mid-test, the unraisable hook fails whichever unrelated + # test happens to be running — the long-standing "random cross-file failure" in the + # pipeline suites. The message contains only the __del__ repr, so these patterns cannot + # scope to pytest-asyncio specifically: a loop/socketpair leak in zarr's own sync + # machinery would also be silenced. Accepted tradeoff — revisit if zarr.core.sync grows + # loop-lifecycle changes. + "ignore:Exception ignored in[\\s\\S]* Callable[..., T]: """Decorator for methods that issues warnings for positional arguments. @@ -104,7 +102,7 @@ def _reshape_view(arr: "NDArray[Any]", shape: tuple[int, ...]) -> "NDArray[Any]" If a view cannot be created (the array is not contiguous) on NumPy >= 2.1. """ if Version(np.__version__) >= Version("2.1"): - return arr.reshape(shape, copy=False) # type: ignore[call-overload, no-any-return] + return arr.reshape(shape, copy=False) else: arr.shape = shape return arr diff --git a/src/zarr/abc/codec.py b/src/zarr/abc/codec.py index 3ec5ec522b..34d349e6d1 100644 --- a/src/zarr/abc/codec.py +++ b/src/zarr/abc/codec.py @@ -2,7 +2,7 @@ from abc import abstractmethod from collections.abc import Mapping -from typing import TYPE_CHECKING, Generic, Protocol, TypeGuard, TypeVar, runtime_checkable +from typing import TYPE_CHECKING, Literal, Protocol, TypeGuard, runtime_checkable from typing_extensions import ReadOnly, TypedDict @@ -17,10 +17,10 @@ from zarr.abc.store import ByteGetter, ByteSetter, Store from zarr.core.array_spec import ArraySpec - from zarr.core.chunk_grids import ChunkGrid from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType from zarr.core.indexing import SelectorTuple from zarr.core.metadata import ArrayMetadata + from zarr.core.metadata.v3 import ChunkGridMetadata __all__ = [ "ArrayArrayCodec", @@ -32,16 +32,22 @@ "CodecInput", "CodecOutput", "CodecPipeline", + "GetResult", "SupportsSyncCodec", ] -CodecInput = TypeVar("CodecInput", bound=NDBuffer | Buffer) -CodecOutput = TypeVar("CodecOutput", bound=NDBuffer | Buffer) -TName = TypeVar("TName", bound=str, covariant=True) +class GetResult(TypedDict): + """Metadata about a store get operation.""" + status: Literal["present", "missing"] -class CodecJSON_V2(TypedDict, Generic[TName]): + +type CodecInput = NDBuffer | Buffer +type CodecOutput = NDBuffer | Buffer + + +class CodecJSON_V2[TName: str](TypedDict): """The JSON representation of a codec for Zarr V2""" id: ReadOnly[TName] @@ -61,23 +67,36 @@ def _check_codecjson_v2(data: object) -> TypeGuard[CodecJSON_V2[str]]: @runtime_checkable -class SupportsSyncCodec(Protocol): +class SupportsSyncCodec[CI: CodecInput, CO: CodecOutput](Protocol): """Protocol for codecs that support synchronous encode/decode. - Codecs implementing this protocol provide ``_decode_sync`` and ``_encode_sync`` + Codecs implementing this protocol provide `_decode_sync` and `_encode_sync` methods that perform encoding/decoding without requiring an async event loop. + + The type parameters mirror `BaseCodec`: `CI` is the decoded type and `CO` is + the encoded type. """ - def _decode_sync( - self, chunk_data: NDBuffer | Buffer, chunk_spec: ArraySpec - ) -> NDBuffer | Buffer: ... + def _decode_sync(self, chunk_data: CO, chunk_spec: ArraySpec) -> CI: ... + + def _encode_sync(self, chunk_data: CI, chunk_spec: ArraySpec) -> CO | None: ... + - def _encode_sync( - self, chunk_data: NDBuffer | Buffer, chunk_spec: ArraySpec - ) -> NDBuffer | Buffer | None: ... +def _codec_supports_sync(codec: object) -> bool: + """Whether `codec` can actually run on a synchronous (no event loop) path. + + Structural membership in `SupportsSyncCodec` is necessary but not always + sufficient: a codec can provide `_decode_sync`/`_encode_sync` whose ability + to run depends on runtime configuration the type system cannot see. + `ShardingCodec` is the canonical case — its sync methods delegate to its + configured inner and index codec chains, so they only work when every codec + in those chains is itself sync-capable. Such codecs opt out dynamically via + a `_sync_capable` attribute/property (absent means capable). + """ + return isinstance(codec, SupportsSyncCodec) and getattr(codec, "_sync_capable", True) -class BaseCodec(Metadata, Generic[CodecInput, CodecOutput]): +class BaseCodec[CI: CodecInput, CO: CodecOutput](Metadata): """Generic base class for codecs. Codecs can be registered via zarr.codecs.registry. @@ -88,7 +107,15 @@ class BaseCodec(Metadata, Generic[CodecInput, CodecOutput]): ArrayArrayCodec, ArrayBytesCodec or BytesBytesCodec for subclassing. """ - is_fixed_size: bool + # Whether this codec's encoded output is a fixed size given a fixed input + # size. Defaults to False (the conservative answer): a codec that does not + # explicitly opt in is treated as variable-size, which only disables + # size-dependent fast paths (e.g. the sharding bulk-decode), never + # correctness. Codecs with genuinely fixed-size output (BytesCodec, + # TransposeCodec, ...) override this with True. The default also keeps + # third-party / variable-length codecs (VLenUTF8, numcodecs wrappers) that + # never set the attribute from raising AttributeError where it is read. + is_fixed_size: bool = False @abstractmethod def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: @@ -140,7 +167,7 @@ def validate( *, shape: tuple[int, ...], dtype: ZDType[TBaseDType, TBaseScalar], - chunk_grid: ChunkGrid, + chunk_grid: ChunkGridMetadata, ) -> None: """Validates that the codec configuration is compatible with the array metadata. Raises errors when the codec configuration is not compatible. @@ -151,17 +178,17 @@ def validate( The array shape dtype : np.dtype[Any] The array data type - chunk_grid : ChunkGrid - The array chunk grid + chunk_grid : ChunkGridMetadata + The array chunk grid metadata """ - async def _decode_single(self, chunk_data: CodecOutput, chunk_spec: ArraySpec) -> CodecInput: + async def _decode_single(self, chunk_data: CO, chunk_spec: ArraySpec) -> CI: raise NotImplementedError # pragma: no cover async def decode( self, - chunks_and_specs: Iterable[tuple[CodecOutput | None, ArraySpec]], - ) -> Iterable[CodecInput | None]: + chunks_and_specs: Iterable[tuple[CO | None, ArraySpec]], + ) -> Iterable[CI | None]: """Decodes a batch of chunks. Chunks can be None in which case they are ignored by the codec. @@ -172,25 +199,23 @@ async def decode( Returns ------- - Iterable[CodecInput | None] + Iterable[CI | None] """ return await _batching_helper(self._decode_single, chunks_and_specs) - async def _encode_single( - self, chunk_data: CodecInput, chunk_spec: ArraySpec - ) -> CodecOutput | None: + async def _encode_single(self, chunk_data: CI, chunk_spec: ArraySpec) -> CO | None: raise NotImplementedError # pragma: no cover async def encode( self, - chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]], - ) -> Iterable[CodecOutput | None]: + chunks_and_specs: Iterable[tuple[CI | None, ArraySpec]], + ) -> Iterable[CO | None]: """Encodes a batch of chunks. Chunks can be None in which case they are ignored by the codec. Parameters ---------- - chunks_and_specs : Iterable[tuple[CodecInput | None, ArraySpec]] + chunks_and_specs : Iterable[tuple[CI | None, ArraySpec]] Ordered set of to-be-encoded chunks with their accompanying chunk spec. Returns @@ -357,7 +382,7 @@ def validate( *, shape: tuple[int, ...], dtype: ZDType[TBaseDType, TBaseScalar], - chunk_grid: ChunkGrid, + chunk_grid: ChunkGridMetadata, ) -> None: """Validates that all codec configurations are compatible with the array metadata. Raises errors when a codec configuration is not compatible. @@ -368,8 +393,8 @@ def validate( The array shape dtype : np.dtype[Any] The array data type - chunk_grid : ChunkGrid - The array chunk grid + chunk_grid : ChunkGridMetadata + The array chunk grid metadata """ ... @@ -433,13 +458,13 @@ async def read( batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], out: NDBuffer, drop_axes: tuple[int, ...] = (), - ) -> None: + ) -> tuple[GetResult, ...]: """Reads chunk data from the store, decodes it and writes it into an output array. Partial decoding may be utilized if the codecs and stores support it. Parameters ---------- - batch_info : Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple]] + batch_info : Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]] Ordered set of information about the chunks. The first slice selection determines which parts of the chunk will be fetched. The second slice selection determines where in the output array the chunk data will be written. @@ -451,6 +476,11 @@ async def read( ``out``) to the fill value for the array. out : NDBuffer + + Returns + ------- + tuple[GetResult, ...] + One result per chunk in ``batch_info``. """ ... @@ -467,7 +497,7 @@ async def write( Parameters ---------- - batch_info : Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple]] + batch_info : Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]] Ordered set of information about the chunks. The first slice selection determines which parts of the chunk will be encoded. The second slice selection determines where in the value array the chunk data is located. @@ -478,10 +508,10 @@ async def write( ... -async def _batching_helper( - func: Callable[[CodecInput, ArraySpec], Awaitable[CodecOutput | None]], - batch_info: Iterable[tuple[CodecInput | None, ArraySpec]], -) -> list[CodecOutput | None]: +async def _batching_helper[CI: CodecInput, CO: CodecOutput]( + func: Callable[[CI, ArraySpec], Awaitable[CO | None]], + batch_info: Iterable[tuple[CI | None, ArraySpec]], +) -> list[CO | None]: return await concurrent_map( list(batch_info), _noop_for_none(func), @@ -489,10 +519,10 @@ async def _batching_helper( ) -def _noop_for_none( - func: Callable[[CodecInput, ArraySpec], Awaitable[CodecOutput | None]], -) -> Callable[[CodecInput | None, ArraySpec], Awaitable[CodecOutput | None]]: - async def wrap(chunk: CodecInput | None, chunk_spec: ArraySpec) -> CodecOutput | None: +def _noop_for_none[CI: CodecInput, CO: CodecOutput]( + func: Callable[[CI, ArraySpec], Awaitable[CO | None]], +) -> Callable[[CI | None, ArraySpec], Awaitable[CO | None]]: + async def wrap(chunk: CI | None, chunk_spec: ArraySpec) -> CO | None: if chunk is None: return None return await func(chunk, chunk_spec) diff --git a/src/zarr/abc/numcodec.py b/src/zarr/abc/numcodec.py index 76eac1d898..d60422209a 100644 --- a/src/zarr/abc/numcodec.py +++ b/src/zarr/abc/numcodec.py @@ -1,6 +1,4 @@ -from typing import Any, Self, TypeGuard - -from typing_extensions import Protocol +from typing import Any, Protocol, Self, TypeGuard class Numcodec(Protocol): diff --git a/src/zarr/abc/store.py b/src/zarr/abc/store.py index d2ab353d43..af528ec533 100644 --- a/src/zarr/abc/store.py +++ b/src/zarr/abc/store.py @@ -1,18 +1,16 @@ from __future__ import annotations import asyncio -import json from abc import ABC, abstractmethod from dataclasses import dataclass +from functools import partial from itertools import starmap from typing import TYPE_CHECKING, Literal, Protocol, runtime_checkable -from zarr.core.sync import sync - if TYPE_CHECKING: - from collections.abc import AsyncGenerator, AsyncIterator, Iterable + from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Sequence from types import TracebackType - from typing import Any, Self, TypeAlias + from typing import Any, Self from zarr.core.buffer import Buffer, BufferPrototype @@ -24,6 +22,8 @@ "SupportsGetSync", "SupportsSetSync", "SupportsSyncStore", + "SyncByteGetter", + "SyncByteSetter", "set_or_delete", ] @@ -54,7 +54,7 @@ class SuffixByteRequest: """The number of bytes from the suffix to request.""" -ByteRequest: TypeAlias = RangeByteRequest | OffsetByteRequest | SuffixByteRequest +type ByteRequest = RangeByteRequest | OffsetByteRequest | SuffixByteRequest class Store(ABC): @@ -218,211 +218,6 @@ async def get( """ ... - async def _get_bytes( - self, key: str, *, prototype: BufferPrototype, byte_range: ByteRequest | None = None - ) -> bytes: - """ - Retrieve raw bytes from the store asynchronously. - - This is a convenience method that wraps ``get()`` and converts the result - to bytes. Use this when you need the raw byte content of a stored value. - - Parameters - ---------- - key : str - The key identifying the data to retrieve. - prototype : BufferPrototype - The buffer prototype to use for reading the data. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Can be a ``RangeByteRequest``, ``OffsetByteRequest``, or ``SuffixByteRequest``. - - Returns - ------- - bytes - The raw bytes stored at the given key. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - - See Also - -------- - get : Lower-level method that returns a Buffer object. - get_bytes : Synchronous version of this method. - get_json : Asynchronous method for retrieving and parsing JSON data. - - Examples - -------- - >>> store = await MemoryStore.open() - >>> await store.set("data", Buffer.from_bytes(b"hello world")) - >>> data = await store.get_bytes("data", prototype=default_buffer_prototype()) - >>> print(data) - b'hello world' - """ - buffer = await self.get(key, prototype, byte_range) - if buffer is None: - raise FileNotFoundError(key) - return buffer.to_bytes() - - def _get_bytes_sync( - self, key: str = "", *, prototype: BufferPrototype, byte_range: ByteRequest | None = None - ) -> bytes: - """ - Retrieve raw bytes from the store synchronously. - - This is a synchronous wrapper around ``get_bytes()``. It should only - be called from non-async code. For async contexts, use ``get_bytes()`` - instead. - - Parameters - ---------- - key : str, optional - The key identifying the data to retrieve. Defaults to an empty string. - prototype : BufferPrototype - The buffer prototype to use for reading the data. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Can be a ``RangeByteRequest``, ``OffsetByteRequest``, or ``SuffixByteRequest``. - - Returns - ------- - bytes - The raw bytes stored at the given key. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - - Warnings - -------- - Do not call this method from async functions. Use ``get_bytes()`` instead - to avoid blocking the event loop. - - See Also - -------- - get_bytes : Asynchronous version of this method. - get_json_sync : Synchronous method for retrieving and parsing JSON data. - - Examples - -------- - >>> store = MemoryStore() - >>> await store.set("data", Buffer.from_bytes(b"hello world")) - >>> data = store.get_bytes_sync("data", prototype=default_buffer_prototype()) - >>> print(data) - b'hello world' - """ - - return sync(self._get_bytes(key, prototype=prototype, byte_range=byte_range)) - - async def _get_json( - self, key: str, *, prototype: BufferPrototype, byte_range: ByteRequest | None = None - ) -> Any: - """ - Retrieve and parse JSON data from the store asynchronously. - - This is a convenience method that retrieves bytes from the store and - parses them as JSON. - - Parameters - ---------- - key : str - The key identifying the JSON data to retrieve. - prototype : BufferPrototype - The buffer prototype to use for reading the data. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Can be a ``RangeByteRequest``, ``OffsetByteRequest``, or ``SuffixByteRequest``. - Note: Using byte ranges with JSON may result in invalid JSON. - - Returns - ------- - Any - The parsed JSON data. This follows the behavior of ``json.loads()`` and - can be any JSON-serializable type: dict, list, str, int, float, bool, or None. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - json.JSONDecodeError - If the stored data is not valid JSON. - - See Also - -------- - get_bytes : Method for retrieving raw bytes. - get_json_sync : Synchronous version of this method. - - Examples - -------- - >>> store = await MemoryStore.open() - >>> metadata = {"zarr_format": 3, "node_type": "array"} - >>> await store.set("zarr.json", Buffer.from_bytes(json.dumps(metadata).encode())) - >>> data = await store.get_json("zarr.json", prototype=default_buffer_prototype()) - >>> print(data) - {'zarr_format': 3, 'node_type': 'array'} - """ - - return json.loads(await self._get_bytes(key, prototype=prototype, byte_range=byte_range)) - - def _get_json_sync( - self, key: str = "", *, prototype: BufferPrototype, byte_range: ByteRequest | None = None - ) -> Any: - """ - Retrieve and parse JSON data from the store synchronously. - - This is a synchronous wrapper around ``get_json()``. It should only - be called from non-async code. For async contexts, use ``get_json()`` - instead. - - Parameters - ---------- - key : str, optional - The key identifying the JSON data to retrieve. Defaults to an empty string. - prototype : BufferPrototype - The buffer prototype to use for reading the data. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Can be a ``RangeByteRequest``, ``OffsetByteRequest``, or ``SuffixByteRequest``. - Note: Using byte ranges with JSON may result in invalid JSON. - - Returns - ------- - Any - The parsed JSON data. This follows the behavior of ``json.loads()`` and - can be any JSON-serializable type: dict, list, str, int, float, bool, or None. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - json.JSONDecodeError - If the stored data is not valid JSON. - - Warnings - -------- - Do not call this method from async functions. Use ``get_json()`` instead - to avoid blocking the event loop. - - See Also - -------- - get_json : Asynchronous version of this method. - get_bytes_sync : Synchronous method for retrieving raw bytes without parsing. - - Examples - -------- - >>> store = MemoryStore() - >>> metadata = {"zarr_format": 3, "node_type": "array"} - >>> store.set("zarr.json", Buffer.from_bytes(json.dumps(metadata).encode())) - >>> data = store.get_json_sync("zarr.json", prototype=default_buffer_prototype()) - >>> print(data) - {'zarr_format': 3, 'node_type': 'array'} - """ - - return sync(self._get_json(key, prototype=prototype, byte_range=byte_range)) - @abstractmethod async def get_partial_values( self, @@ -616,6 +411,133 @@ async def _get_many( for req in requests: yield (req[0], await self.get(*req)) + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int = 10, + max_gap_bytes: int = 1 << 20, # 1 MiB + max_coalesced_bytes: int = 16 << 20, # 16 MiB + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + """Read many byte ranges from `key`. + + Yields one batch per underlying I/O operation, each a sequence of + `(input_index, Buffer | None)` tuples. Batches across yields arrive in + completion order, not input order. The default implementation built + into `Store` runs the coalescer over `self.get`, so subclasses get a + working implementation for free; stores that have a more efficient + backend (e.g. ranged HTTP, S3 byte-range fetches) should override. + + Parameters + ---------- + key + Storage key to read from. + byte_ranges + Input ranges. `None` means "the whole value". + prototype + Buffer prototype, forwarded to `self.get`. + max_concurrency + Maximum number of merged fetches in flight at once. + max_gap_bytes + Two `RangeByteRequest`s separated by at most this many bytes may + be merged into one fetch. + max_coalesced_bytes + Upper bound on the size of a single merged fetch. + + Raises + ------ + BaseExceptionGroup + Failures from underlying fetches are reported as a + `BaseExceptionGroup` (PEP 654) and should be handled with + `except*`. Inner exceptions include `FileNotFoundError` if any + fetch returns `None` (i.e. `key` is absent), and any exception + raised by `self.get` for the corresponding range. Pending + fetches are cancelled as soon as one task fails, so the group + typically contains a single non-`CancelledError` exception even + under high concurrency. + """ + # Local import: zarr.core._coalesce imports symbols from this module. + from zarr.core._coalesce import coalesced_get + + fetch = partial(self.get, key, prototype) + async for group in coalesced_get( + fetch, + byte_ranges, + max_concurrency=max_concurrency, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + yield group + + def get_ranges_sync( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_gap_bytes: int = 1 << 20, # 1 MiB + max_coalesced_bytes: int = 16 << 20, # 16 MiB + ) -> Sequence[tuple[int, Buffer | None]]: + """Synchronous, coalescing counterpart of `get_ranges`. + + Plans merged fetches with the same `coalesce_ranges` policy as the async + path, then issues one synchronous `get_sync` per merged group (or per + uncoalescable request) and slices results back into per-input buffers. + Used by the sync codec pipeline's partial-shard reads so they get the + same byte-range coalescing as the async path, without an event loop. + + Returns a list of `(input_index, Buffer | None)`. Raises + `BaseExceptionGroup` containing a `FileNotFoundError` if the key is + absent (matching `get_ranges`), so callers can handle a deleted shard + uniformly across the sync and async paths. + + Requires the store to implement `get_sync` (`SupportsGetSync`). + """ + from zarr.core._coalesce import coalesce_ranges + + if not isinstance(self, SupportsGetSync): + raise TypeError(f"{type(self).__name__} does not support synchronous reads") + + groups, uncoalescable = coalesce_ranges( + byte_ranges, max_gap_bytes=max_gap_bytes, max_coalesced_bytes=max_coalesced_bytes + ) + results: list[tuple[int, Buffer | None]] = [] + errors: list[BaseException] = [] + + def _get(req: ByteRequest | None) -> Buffer | None: + return self.get_sync(key, prototype=prototype, byte_range=req) + + for idx, req in uncoalescable: + buf = _get(req) + if buf is None: + errors.append(FileNotFoundError(key)) + else: + results.append((idx, buf)) + + for members in groups: + if len(members) == 1: + solo_idx, solo_req = members[0] + buf = _get(solo_req) + if buf is None: + errors.append(FileNotFoundError(key)) + else: + results.append((solo_idx, buf)) + continue + start = members[0][1].start + end = max(r.end for _, r in members) + big = _get(RangeByteRequest(start, end)) + if big is None: + errors.append(FileNotFoundError(key)) + continue + for member_idx, r in members: + results.append((member_idx, big[r.start - start : r.end - start])) + + if errors: + raise BaseExceptionGroup("chunk read failed", errors) + return results + async def getsize(self, key: str) -> int: """ Return the size, in bytes, of a value in a Store. @@ -683,6 +605,8 @@ async def getsize_prefix(self, prefix: str) -> int: from zarr.core.common import concurrent_map from zarr.core.config import config + if prefix != "" and not prefix.endswith("/"): + prefix += "/" keys = [(x,) async for x in self.list_prefix(prefix)] limit = config.get("async.concurrency") sizes = await concurrent_map(keys, self.getsize, limit=limit) @@ -709,8 +633,44 @@ async def delete(self) -> None: ... async def set_if_not_exists(self, default: Buffer) -> None: ... +@runtime_checkable +class SyncByteGetter(Protocol): + """A `ByteGetter` that can also fetch synchronously, without an event loop. + + Non-StorePath byte getters (e.g. the sharding codec's in-memory + `_ShardingByteGetter`) implement this so a synchronous codec pipeline can + take its sync fast path on them instead of scheduling one coroutine per + chunk. Note that `StorePath` also *has* a `get_sync` method (so it matches + this protocol structurally) but it only works when its store supports + synchronous IO — callers gate `StorePath` on the store's `SupportsGetSync` + instead of on this protocol. + """ + + def get_sync( + self, prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None + ) -> Buffer | None: ... + + +@runtime_checkable +class SyncByteSetter(SyncByteGetter, Protocol): + """A `ByteSetter` that can also write synchronously. See `SyncByteGetter`.""" + + def set_sync(self, value: Buffer) -> None: ... + + def delete_sync(self) -> None: ... + + @runtime_checkable class SupportsGetSync(Protocol): + """Store protocol for synchronous reads (`get_sync`). + + The store sync surface is all-or-nothing: a store implementing any of the + `*_sync` methods must implement all of them (`SupportsSyncStore`), because + consumers mix sync reads, writes, and deletes within one operation. + Capability-gated callers consult `_store_supports_sync_io` rather than the + individual protocols. + """ + def get_sync( self, key: str, @@ -722,16 +682,52 @@ def get_sync( @runtime_checkable class SupportsSetSync(Protocol): + """Store protocol for synchronous writes (`set_sync`). + + See `SupportsGetSync` for the all-or-nothing contract on the store sync + surface. + """ + def set_sync(self, key: str, value: Buffer) -> None: ... @runtime_checkable class SupportsDeleteSync(Protocol): + """Store protocol for synchronous deletes (`delete_sync`). + + See `SupportsGetSync` for the all-or-nothing contract on the store sync + surface. + """ + def delete_sync(self, key: str) -> None: ... @runtime_checkable -class SupportsSyncStore(SupportsGetSync, SupportsSetSync, SupportsDeleteSync, Protocol): ... +class SupportsSyncStore(SupportsGetSync, SupportsSetSync, SupportsDeleteSync, Protocol): + """The full store sync surface: `get_sync`, `set_sync`, and `delete_sync`.""" + + +def _store_supports_sync_io(store: object) -> bool: + """Whether `store` can serve the full synchronous IO surface right now. + + Structural membership in `SupportsSyncStore` is necessary but not always + sufficient: a store can present the `*_sync` methods while its ability to + run them depends on runtime state the type system cannot see. Wrapper + stores are the canonical case — `WrapperStore` delegates the sync methods + to the store it wraps, so they only work when the wrapped store is itself + sync-capable. Such stores opt out dynamically via a `_supports_sync_io` + attribute/property (absent means capable). + + This is an interim, private convention pending a formal sync/async store + architecture — the store-side twin of the codec-side `_sync_capable` + convention consulted by `zarr.abc.codec._codec_supports_sync`. + + Synchronous IO is all-or-nothing: consumers such as the fused codec + pipeline mix synchronous reads, writes, and deletes within one batch + (e.g. a partial-chunk write reads existing bytes and an all-fill chunk is + deleted), so a partial sync surface never satisfies this predicate. + """ + return isinstance(store, SupportsSyncStore) and getattr(store, "_supports_sync_io", True) async def set_or_delete(byte_setter: ByteSetter, value: Buffer | None) -> None: diff --git a/src/zarr/api/asynchronous.py b/src/zarr/api/asynchronous.py index 6164cda957..3bdc254ea5 100644 --- a/src/zarr/api/asynchronous.py +++ b/src/zarr/api/asynchronous.py @@ -3,7 +3,7 @@ import asyncio import dataclasses import warnings -from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypeAlias, TypedDict, cast +from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict, cast import numpy as np import numpy.typing as npt @@ -24,7 +24,7 @@ from zarr.core.common import ( JSON, AccessModeLiteral, - DimensionNames, + DimensionNamesLike, MemoryOrder, ZarrFormat, _default_zarr_format, @@ -61,7 +61,7 @@ from zarr.types import AnyArray, AnyAsyncArray # TODO: this type could use some more thought - ArrayLike: TypeAlias = AnyAsyncArray | AnyArray | npt.NDArray[Any] + type ArrayLike = AnyAsyncArray | AnyArray | npt.NDArray[Any] PathLike = str __all__ = [ @@ -103,11 +103,24 @@ def _infer_overwrite(mode: AccessModeLiteral) -> bool: """ - Check that an ``AccessModeLiteral`` is compatible with overwriting an existing Zarr node. + Check that an `AccessModeLiteral` is compatible with overwriting an existing Zarr node. """ return mode in _OVERWRITE_MODES +def _warn_unimplemented_kwargs(kwargs: dict[str, Any]) -> None: + """ + Emit a "not yet implemented" warning for each provided keyword argument that is not None. + + `kwargs` maps a keyword argument name to its supplied value. The `stacklevel` is chosen + so the warning points at the caller of the public API function (the same location as an + inline `warnings.warn(..., stacklevel=2)` would). + """ + for name, value in kwargs.items(): + if value is not None: + warnings.warn(f"{name} is not yet implemented", ZarrRuntimeWarning, stacklevel=3) + + def _get_shape_chunks(a: ArrayLike | Any) -> tuple[tuple[int, ...] | None, tuple[int, ...] | None]: """Helper function to get the shape and chunks from an array-like object""" shape = None @@ -134,6 +147,7 @@ class _LikeArgs(TypedDict): filters: NotRequired[tuple[Numcodec, ...] | None] compressor: NotRequired[CompressorLikev2] codecs: NotRequired[tuple[Codec, ...]] + fill_value: NotRequired[Any] def _like_args(a: ArrayLike) -> _LikeArgs: @@ -151,6 +165,7 @@ def _like_args(a: ArrayLike) -> _LikeArgs: new["dtype"] = a.dtype if isinstance(a, AsyncArray | Array): + new["fill_value"] = a.metadata.fill_value if isinstance(a.metadata, ArrayV2Metadata): new["order"] = a.order new["compressor"] = a.metadata.compressor @@ -169,22 +184,6 @@ def _like_args(a: ArrayLike) -> _LikeArgs: return new -def _handle_zarr_version_or_format( - *, zarr_version: ZarrFormat | None, zarr_format: ZarrFormat | None -) -> ZarrFormat | None: - """Handle the deprecated zarr_version kwarg and return zarr_format""" - if zarr_format is not None and zarr_version is not None and zarr_format != zarr_version: - raise ValueError( - f"zarr_format {zarr_format} does not match zarr_version {zarr_version}, please only set one" - ) - if zarr_version is not None: - warnings.warn( - "zarr_version is deprecated, use zarr_format", ZarrDeprecationWarning, stacklevel=2 - ) - return zarr_version - return zarr_format - - async def consolidate_metadata( store: StoreLike, path: str | None = None, @@ -195,7 +194,7 @@ async def consolidate_metadata( Upon completion, the metadata of the root node in the Zarr hierarchy will be updated to include all the metadata of child nodes. For Stores that do - not support consolidated metadata, this operation raises a ``TypeError``. + not support consolidated metadata, this operation raises a `TypeError`. Parameters ---------- @@ -216,10 +215,10 @@ async def consolidate_metadata( Returns ------- group: AsyncGroup - The group, with the ``consolidated_metadata`` field set to include + The group, with the `consolidated_metadata` field set to include the metadata of each child node. If the Store doesn't support consolidated metadata, this function raises a `TypeError`. - See ``Store.supports_consolidated_metadata``. + See `Store.supports_consolidated_metadata`. """ store_path = await make_store_path(store, path=path) @@ -289,7 +288,6 @@ async def load( store: StoreLike, path: str | None = None, zarr_format: ZarrFormat | None = None, - zarr_version: ZarrFormat | None = None, ) -> NDArrayLikeOrScalar | dict[str, NDArrayLikeOrScalar]: """Load data from an array or group into memory. @@ -311,18 +309,25 @@ async def load( See Also -------- - save + save, open Notes ----- If loading data from a group of arrays, data will not be immediately loaded into memory. Rather, arrays will be loaded into memory as they are requested. + + Unlike [`open`][zarr.open], which returns a lazy [`Array`][zarr.Array] or + [`Group`][zarr.Group] backed by the store, `load` eagerly reads the data and + returns it as an in-memory array (or a dict of arrays for a group). + The array type is NumPy by default, but follows the configured + buffer prototype (for example, CuPy for GPU use cases). + Use `open` when you want to read or write data incrementally without loading it + all into memory. """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) obj = await open(store=store, path=path, zarr_format=zarr_format) if isinstance(obj, AsyncArray): - return await obj.getitem(slice(None)) + return await obj.getitem(Ellipsis) else: raise NotImplementedError("loading groups not yet supported") @@ -331,7 +336,6 @@ async def open( *, store: StoreLike | None = None, mode: AccessModeLiteral | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, storage_options: dict[str, Any] | None = None, @@ -359,15 +363,26 @@ async def open( If using an fsspec URL to create the store, these will be passed to the backend implementation. Ignored otherwise. **kwargs - Additional parameters are passed through to [`zarr.creation.open_array`][] or - [`open_group`][zarr.api.asynchronous.open_group]. + Additional parameters are passed through to `zarr.open_array` or + `zarr.open_group`. Returns ------- z : array or group Return type depends on what exists in the given store. + + See Also + -------- + load + + Notes + ----- + `open` returns a lazy [`Array`][zarr.Array] or [`Group`][zarr.Group] backed by + the store, so data is read and written incrementally. Use [`load`][zarr.load] + instead when you want the data eagerly read into an in-memory array (a + NumPy array by default). """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) + if mode is None: if isinstance(store, (Store, StorePath)) and store.read_only: mode = "r" @@ -405,7 +420,7 @@ async def open_consolidated( *args: Any, use_consolidated: Literal[True] = True, **kwargs: Any ) -> AsyncGroup: """ - Alias for [`open_group`][zarr.api.asynchronous.open_group] with ``use_consolidated=True``. + Alias for [`open_group`][zarr.api.asynchronous.open_group] with `use_consolidated=True`. """ if use_consolidated is not True: raise TypeError( @@ -418,7 +433,6 @@ async def open_consolidated( async def save( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, **kwargs: Any, # TODO: type kwargs as valid args to save @@ -440,7 +454,6 @@ async def save( **kwargs NumPy arrays with data to save. """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) if len(args) == 0 and len(kwargs) == 0: raise ValueError("at least one array must be provided") @@ -454,7 +467,6 @@ async def save_array( store: StoreLike, arr: NDArrayLike, *, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, storage_options: dict[str, Any] | None = None, @@ -472,7 +484,7 @@ async def save_array( arr : ndarray NumPy array with data to save. zarr_format : {2, 3, None}, optional - The zarr format to use when saving. The default is ``None``, which will + The zarr format to use when saving. The default is `None`, which will use the default Zarr format defined in the global configuration object. path : str or None, optional The path within the store where the array will be saved. @@ -482,10 +494,8 @@ async def save_array( **kwargs Passed through to [`create`][zarr.api.asynchronous.create], e.g., compressor. """ - zarr_format = ( - _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - or _default_zarr_format() - ) + if zarr_format is None: + zarr_format = _default_zarr_format() if not isinstance(arr, NDArrayLike): raise TypeError("arr argument must be numpy or other NDArrayLike array") @@ -506,13 +516,12 @@ async def save_array( overwrite=overwrite, **kwargs, ) - await new.setitem(slice(None), arr) + await new.setitem(Ellipsis, arr) async def save_group( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, storage_options: dict[str, Any] | None = None, @@ -542,13 +551,8 @@ async def save_group( store_path = await make_store_path(store, path=path, mode="w", storage_options=storage_options) - zarr_format = ( - _handle_zarr_version_or_format( - zarr_version=zarr_version, - zarr_format=zarr_format, - ) - or _default_zarr_format() - ) + if zarr_format is None: + zarr_format = _default_zarr_format() for arg in args: if not isinstance(arg, NDArrayLike): @@ -662,7 +666,6 @@ async def group( cache_attrs: bool | None = None, # not used, default changed synchronizer: Any | None = None, # not used path: str | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # not used attributes: dict[str, JSON] | None = None, @@ -715,7 +718,6 @@ async def group( cache_attrs=cache_attrs, synchronizer=synchronizer, path=path, - zarr_version=zarr_version, zarr_format=zarr_format, meta_array=meta_array, attributes=attributes, @@ -743,12 +745,12 @@ async def create_group( path : str, optional Group path within store. overwrite : bool, optional - If True, pre-existing data at ``path`` will be deleted before + If True, pre-existing data at `path` will be deleted before creating the group. zarr_format : {2, 3, None}, optional The zarr format to use when saving. - If no ``zarr_format`` is provided, the default format will be used. - This default can be changed by modifying the value of ``default_zarr_format`` + If no `zarr_format` is provided, the default format will be used. + This default can be changed by modifying the value of `default_zarr_format` in [`zarr.config`][zarr.config]. storage_options : dict If using an fsspec URL to create the store, these will be passed to @@ -784,7 +786,6 @@ async def open_group( path: str | None = None, chunk_store: StoreLike | None = None, # not used storage_options: dict[str, Any] | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # not used attributes: dict[str, JSON] | None = None, @@ -827,17 +828,17 @@ async def open_group( Whether to use consolidated metadata. By default, consolidated metadata is used if it's present in the - store (in the ``zarr.json`` for Zarr format 3 and in the ``.zmetadata`` file + store (in the `zarr.json` for Zarr format 3 and in the `.zmetadata` file for Zarr format 2). - To explicitly require consolidated metadata, set ``use_consolidated=True``, + To explicitly require consolidated metadata, set `use_consolidated=True`, which will raise an exception if consolidated metadata is not found. - To explicitly *not* use consolidated metadata, set ``use_consolidated=False``, + To explicitly *not* use consolidated metadata, set `use_consolidated=False`, which will fall back to using the regular, non consolidated metadata. Zarr format 2 allowed configuring the key storing the consolidated metadata - (``.zmetadata`` by default). Specify the custom key as ``use_consolidated`` + (`.zmetadata` by default). Specify the custom key as `use_consolidated` to load consolidated metadata from a non-default key. Returns @@ -846,16 +847,14 @@ async def open_group( The new group. """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - - if cache_attrs is not None: - warnings.warn("cache_attrs is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if synchronizer is not None: - warnings.warn("synchronizer is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if meta_array is not None: - warnings.warn("meta_array is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if chunk_store is not None: - warnings.warn("chunk_store is not yet implemented", ZarrRuntimeWarning, stacklevel=2) + _warn_unimplemented_kwargs( + { + "cache_attrs": cache_attrs, + "synchronizer": synchronizer, + "meta_array": meta_array, + "chunk_store": chunk_store, + } + ) store_path = await make_store_path(store, mode=mode, storage_options=storage_options, path=path) if attributes is None: @@ -901,7 +900,6 @@ async def create( object_codec: Codec | None = None, # TODO: type has changed dimension_separator: Literal[".", "/"] | None = None, write_empty_chunks: bool | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # TODO: need type attributes: dict[str, JSON] | None = None, @@ -914,7 +912,7 @@ async def create( | None ) = None, codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, config: ArrayConfigLike | None = None, **kwargs: Any, @@ -926,27 +924,27 @@ async def create( shape : int or tuple of ints Array shape. chunks : int or tuple of ints, optional - Chunk shape. If True, will be guessed from ``shape`` and ``dtype``. If - False, will be set to ``shape``, i.e., single chunk for the whole array. + Chunk shape. If True, will be guessed from `shape` and `dtype`. If + False, will be set to `shape`, i.e., single chunk for the whole array. If an int, the chunk size in each dimension will be given by the value - of ``chunks``. Default is True. + of `chunks`. Default is True. dtype : str or dtype, optional NumPy dtype. compressor : Codec, optional Primary compressor to compress chunk data. - Zarr format 2 only. Zarr format 3 arrays should use ``codecs`` instead. + Zarr format 2 only. Zarr format 3 arrays should use `codecs` instead. - If neither ``compressor`` nor ``filters`` are provided, the default compressor + If neither `compressor` nor `filters` are provided, the default compressor [`zarr.codecs.ZstdCodec`][] is used. - If ``compressor`` is set to ``None``, no compression is used. + If `compressor` is set to `None`, no compression is used. fill_value : Any, optional Fill value for the array. order : {'C', 'F'}, optional - Deprecated in favor of the ``config`` keyword argument. - Pass ``{'order': }`` to ``create`` instead of using this parameter. + Deprecated in favor of the `config` keyword argument. + Pass `{'order': }` to `create` instead of using this parameter. Memory layout to be used within each chunk. - If not specified, the ``array.order`` parameter in the global config will be used. + If not specified, the `array.order` parameter in the global config will be used. store : StoreLike or None, default=None StoreLike object to open. See the [storage documentation in the user guide][user-guide-store-like] @@ -954,12 +952,12 @@ async def create( synchronizer : object, optional Array synchronizer. overwrite : bool, optional - If True, delete all pre-existing data in ``store`` at ``path`` before + If True, delete all pre-existing data in `store` at `path` before creating the array. path : str, optional Path under which array is stored. chunk_store : StoreLike or None, default=None - Separate storage for chunks. If not provided, ``store`` will be used + Separate storage for chunks. If not provided, `store` will be used for storage of both chunks and metadata. filters : Iterable[Codec] | Literal["auto"], optional Iterable of filters to apply to each chunk of the array, in order, before serializing that @@ -970,16 +968,16 @@ async def create( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of `"auto"` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters contains a single element which is a codec specific to that particular data type. - To create an array with no filters, provide an empty iterable or the value ``None``. + To create an array with no filters, provide an empty iterable or the value `None`. cache_metadata : bool, optional If True, array configuration metadata will be cached for the lifetime of the object. If False, array metadata will be reloaded @@ -995,17 +993,17 @@ async def create( A codec to encode object arrays, only needed if dtype=object. dimension_separator : {'.', '/'}, optional Separator placed between the dimensions of a chunk. - Zarr format 2 only. Zarr format 3 arrays should use ``chunk_key_encoding`` instead. + Zarr format 2 only. Zarr format 3 arrays should use `chunk_key_encoding` instead. write_empty_chunks : bool, optional - Deprecated in favor of the ``config`` keyword argument. - Pass ``{'write_empty_chunks': }`` to ``create`` instead of using this parameter. + Deprecated in favor of the `config` keyword argument. + Pass `{'write_empty_chunks': }` to `create` instead of using this parameter. If True, all chunks will be stored regardless of their contents. If False, each chunk is compared to the array's fill value prior to storing. If a chunk is uniformly equal to the fill value, then that chunk is not be stored, and the store entry for that chunk's key is deleted. zarr_format : {2, 3, None}, optional - The Zarr format to use when creating an array. The default is ``None``, + The Zarr format to use when creating an array. The default is `None`, which instructs Zarr to choose the default Zarr format value defined in the runtime configuration. meta_array : array-like, optional @@ -1018,15 +1016,15 @@ async def create( chunk_key_encoding : ChunkKeyEncoding, optional A specification of how the chunk keys are represented in storage. Zarr format 3 only. Zarr format 2 arrays should use `dimension_separator` instead. - Default is ``("default", "/")``. + Default is `("default", "/")`. codecs : Sequence of Codecs or dicts, optional An iterable of Codec or dict serializations of Codecs. Zarr V3 only. - The elements of ``codecs`` specify the transformation from array values to stored bytes. - Zarr format 3 only. Zarr format 2 arrays should use ``filters`` and ``compressor`` instead. + The elements of `codecs` specify the transformation from array values to stored bytes. + Zarr format 3 only. Zarr format 2 arrays should use `filters` and `compressor` instead. If no codecs are provided, default codecs will be used based on the data type of the array. - For most data types, the default codecs are the tuple ``(BytesCodec(), ZstdCodec())``; + For most data types, the default codecs are the tuple `(BytesCodec(), ZstdCodec())`; data types that require a special [`zarr.abc.codec.ArrayBytesCodec`][], like variable-length strings or bytes, will use the [`zarr.abc.codec.ArrayBytesCodec`][] required for the data type instead of [`zarr.codecs.BytesCodec`][]. dimension_names : Iterable[str | None] | None = None @@ -1043,25 +1041,20 @@ async def create( z : array The array. """ - zarr_format = ( - _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - or _default_zarr_format() - ) + if zarr_format is None: + zarr_format = _default_zarr_format() - if synchronizer is not None: - warnings.warn("synchronizer is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if chunk_store is not None: - warnings.warn("chunk_store is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if cache_metadata is not None: - warnings.warn("cache_metadata is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if cache_attrs is not None: - warnings.warn("cache_attrs is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if object_codec is not None: - warnings.warn("object_codec is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if read_only is not None: - warnings.warn("read_only is not yet implemented", ZarrRuntimeWarning, stacklevel=2) - if meta_array is not None: - warnings.warn("meta_array is not yet implemented", ZarrRuntimeWarning, stacklevel=2) + _warn_unimplemented_kwargs( + { + "synchronizer": synchronizer, + "chunk_store": chunk_store, + "cache_metadata": cache_metadata, + "cache_attrs": cache_attrs, + "object_codec": object_codec, + "read_only": read_only, + "meta_array": meta_array, + } + ) if write_empty_chunks is not None: _warn_write_empty_chunks_kwarg() @@ -1087,7 +1080,8 @@ async def create( store_path, shape=shape, chunks=chunks, - dtype=dtype, + # Legacy v2 behavior: an unspecified dtype defaults to float64. + dtype="float64" if dtype is None else dtype, compressor=compressor, fill_value=fill_value, overwrite=overwrite, @@ -1148,8 +1142,6 @@ async def empty_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: and these are not guaranteed to be stable from one access to the next. """ like_kwargs = _like_args(a) | kwargs - if isinstance(a, (AsyncArray | Array)): - like_kwargs.setdefault("fill_value", a.metadata.fill_value) return await empty(**like_kwargs) # type: ignore[arg-type] @@ -1192,8 +1184,6 @@ async def full_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: The new array. """ like_kwargs = _like_args(a) | kwargs - if isinstance(a, (AsyncArray | Array)): - like_kwargs.setdefault("fill_value", a.metadata.fill_value) return await full(**like_kwargs) # type: ignore[arg-type] @@ -1231,14 +1221,16 @@ async def ones_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: Array The new array. """ - like_kwargs = _like_args(a) | kwargs + like_args = _like_args(a) + # `ones` supplies its own fill_value, so drop any inherited from `a`. + like_args.pop("fill_value", None) + like_kwargs = like_args | kwargs return await ones(**like_kwargs) # type: ignore[arg-type] async def open_array( *, # note: this is a change from v2 store: StoreLike | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: PathLike = "", storage_options: dict[str, Any] | None = None, @@ -1252,8 +1244,6 @@ async def open_array( StoreLike object to open. See the [storage documentation in the user guide][user-guide-store-like] for a description of all valid StoreLike values. - zarr_version : {2, 3, None}, optional - The zarr format to use when saving. Deprecated in favor of zarr_format. zarr_format : {2, 3, None}, optional The zarr format to use when saving. path : str, optional @@ -1273,8 +1263,6 @@ async def open_array( mode = kwargs.pop("mode", None) store_path = await make_store_path(store, path=path, mode=mode, storage_options=storage_options) - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - if "write_empty_chunks" in kwargs: _warn_write_empty_chunks_kwarg() @@ -1304,7 +1292,9 @@ async def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AnyAsyncArray: path : str The path to the new array. **kwargs - Any keyword arguments to pass to the array constructor. + Additional keyword arguments passed to `open_array`. + If `mode` is omitted or `None`, it defaults to `"a"`. Pass `mode="r"` when + opening an existing array from a read-only store. Returns ------- @@ -1312,8 +1302,8 @@ async def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AnyAsyncArray: The opened array. """ like_kwargs = _like_args(a) | kwargs - if isinstance(a, (AsyncArray | Array)): - like_kwargs.setdefault("fill_value", a.metadata.fill_value) + if like_kwargs.get("mode") is None: + like_kwargs["mode"] = "a" return await open_array(path=path, **like_kwargs) # type: ignore[arg-type] @@ -1351,5 +1341,8 @@ async def zeros_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: Array The new array. """ - like_kwargs = _like_args(a) | kwargs + like_args = _like_args(a) + # `zeros` supplies its own fill_value, so drop any inherited from `a`. + like_args.pop("fill_value", None) + like_kwargs = like_args | kwargs return await zeros(**like_kwargs) # type: ignore[arg-type] diff --git a/src/zarr/api/synchronous.py b/src/zarr/api/synchronous.py index 1204eba3c9..30ddf9ce6a 100644 --- a/src/zarr/api/synchronous.py +++ b/src/zarr/api/synchronous.py @@ -33,7 +33,8 @@ from zarr.core.common import ( JSON, AccessModeLiteral, - DimensionNames, + ChunksLike, + DimensionNamesLike, MemoryOrder, ShapeLike, ZarrFormat, @@ -105,10 +106,10 @@ def consolidate_metadata( Returns ------- group: Group - The group, with the ``consolidated_metadata`` field set to include + The group, with the `consolidated_metadata` field set to include the metadata of each child node. If the Store doesn't support consolidated metadata, this function raises a `TypeError`. - See ``Store.supports_consolidated_metadata``. + See `Store.supports_consolidated_metadata`. """ return Group(sync(async_api.consolidate_metadata(store, path=path, zarr_format=zarr_format))) @@ -139,7 +140,6 @@ def load( store: StoreLike, path: str | None = None, zarr_format: ZarrFormat | None = None, - zarr_version: ZarrFormat | None = None, ) -> NDArrayLikeOrScalar | dict[str, NDArrayLikeOrScalar]: """Load data from an array or group into memory. @@ -161,23 +161,28 @@ def load( See Also -------- - save, savez + save, savez, open Notes ----- If loading data from a group of arrays, data will not be immediately loaded into memory. Rather, arrays will be loaded into memory as they are requested. + + Unlike [`open`][zarr.open], which returns a lazy [`Array`][zarr.Array] or + [`Group`][zarr.Group] backed by the store, `load` eagerly reads the data and + returns it as an in-memory array (or a dict of arrays for a group). + The array type is NumPy by default, but follows the configured + buffer prototype (for example, CuPy for GPU use cases). + Use `open` when you want to read or write data incrementally without loading it + all into memory. """ - return sync( - async_api.load(store=store, zarr_version=zarr_version, zarr_format=zarr_format, path=path) - ) + return sync(async_api.load(store=store, zarr_format=zarr_format, path=path)) def open( store: StoreLike | None = None, *, mode: AccessModeLiteral | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, storage_options: dict[str, Any] | None = None, @@ -205,19 +210,29 @@ def open( If using an fsspec URL to create the store, these will be passed to the backend implementation. Ignored otherwise. **kwargs - Additional parameters are passed through to [`zarr.creation.open_array`][] or - [`open_group`][zarr.api.asynchronous.open_group]. + Additional parameters are passed through to `zarr.open_array` or + `zarr.open_group`. Returns ------- z : array or group Return type depends on what exists in the given store. + + See Also + -------- + load + + Notes + ----- + `open` returns a lazy [`Array`][zarr.Array] or [`Group`][zarr.Group] backed by + the store, so data is read and written incrementally. Use [`load`][zarr.load] + instead when you want the data eagerly read into an in-memory array (a + NumPy array by default). """ obj = sync( async_api.open( store=store, mode=mode, - zarr_version=zarr_version, zarr_format=zarr_format, path=path, storage_options=storage_options, @@ -232,7 +247,7 @@ def open( def open_consolidated(*args: Any, use_consolidated: Literal[True] = True, **kwargs: Any) -> Group: """ - Alias for [`open_group`][zarr.api.synchronous.open_group] with ``use_consolidated=True``. + Alias for [`open_group`][zarr.api.synchronous.open_group] with `use_consolidated=True`. """ return Group( sync(async_api.open_consolidated(*args, use_consolidated=use_consolidated, **kwargs)) @@ -242,7 +257,6 @@ def open_consolidated(*args: Any, use_consolidated: Literal[True] = True, **kwar def save( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, **kwargs: Any, # TODO: type kwargs as valid args to async_api.save @@ -264,18 +278,13 @@ def save( **kwargs NumPy arrays with data to save. """ - return sync( - async_api.save( - store, *args, zarr_version=zarr_version, zarr_format=zarr_format, path=path, **kwargs - ) - ) + return sync(async_api.save(store, *args, zarr_format=zarr_format, path=path, **kwargs)) def save_array( store: StoreLike, arr: NDArrayLike, *, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, storage_options: dict[str, Any] | None = None, @@ -294,7 +303,7 @@ def save_array( arr : ndarray NumPy array with data to save. zarr_format : {2, 3, None}, optional - The zarr format to use when saving. The default is ``None``, which will + The zarr format to use when saving. The default is `None`, which will use the default Zarr format defined in the global configuration object. path : str or None, optional The path within the store where the array will be saved. @@ -308,7 +317,6 @@ def save_array( async_api.save_array( store=store, arr=arr, - zarr_version=zarr_version, zarr_format=zarr_format, path=path, storage_options=storage_options, @@ -320,7 +328,6 @@ def save_array( def save_group( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, storage_options: dict[str, Any] | None = None, @@ -353,7 +360,6 @@ def save_group( async_api.save_group( store, *args, - zarr_version=zarr_version, zarr_format=zarr_format, path=path, storage_options=storage_options, @@ -415,7 +421,6 @@ def group( cache_attrs: bool | None = None, # not used, default changed synchronizer: Any | None = None, # not used path: str | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # not used attributes: dict[str, JSON] | None = None, @@ -465,7 +470,6 @@ def group( cache_attrs=cache_attrs, synchronizer=synchronizer, path=path, - zarr_version=zarr_version, zarr_format=zarr_format, meta_array=meta_array, attributes=attributes, @@ -484,7 +488,6 @@ def open_group( path: str | None = None, chunk_store: StoreLike | None = None, # not used in async api storage_options: dict[str, Any] | None = None, # not used in async api - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # not used in async api attributes: dict[str, JSON] | None = None, @@ -527,17 +530,17 @@ def open_group( Whether to use consolidated metadata. By default, consolidated metadata is used if it's present in the - store (in the ``zarr.json`` for Zarr format 3 and in the ``.zmetadata`` file + store (in the `zarr.json` for Zarr format 3 and in the `.zmetadata` file for Zarr format 2). - To explicitly require consolidated metadata, set ``use_consolidated=True``, + To explicitly require consolidated metadata, set `use_consolidated=True`, which will raise an exception if consolidated metadata is not found. - To explicitly *not* use consolidated metadata, set ``use_consolidated=False``, + To explicitly *not* use consolidated metadata, set `use_consolidated=False`, which will fall back to using the regular, non consolidated metadata. Zarr format 2 allowed configuring the key storing the consolidated metadata - (``.zmetadata`` by default). Specify the custom key as ``use_consolidated`` + (`.zmetadata` by default). Specify the custom key as `use_consolidated` to load consolidated metadata from a non-default key. Returns @@ -555,7 +558,6 @@ def open_group( path=path, chunk_store=chunk_store, storage_options=storage_options, - zarr_version=zarr_version, zarr_format=zarr_format, meta_array=meta_array, attributes=attributes, @@ -585,12 +587,12 @@ def create_group( path : str, optional Group path within store. overwrite : bool, optional - If True, pre-existing data at ``path`` will be deleted before + If True, pre-existing data at `path` will be deleted before creating the group. zarr_format : {2, 3, None}, optional The zarr format to use when saving. - If no ``zarr_format`` is provided, the default format will be used. - This default can be changed by modifying the value of ``default_zarr_format`` + If no `zarr_format` is provided, the default format will be used. + This default can be changed by modifying the value of `default_zarr_format` in [`zarr.config`][zarr.config]. storage_options : dict If using an fsspec URL to create the store, these will be passed to @@ -636,7 +638,6 @@ def create( object_codec: Codec | None = None, # TODO: type has changed dimension_separator: Literal[".", "/"] | None = None, write_empty_chunks: bool | None = None, # TODO: default has changed - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # TODO: need type attributes: dict[str, JSON] | None = None, @@ -649,7 +650,7 @@ def create( | None ) = None, codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, config: ArrayConfigLike | None = None, **kwargs: Any, @@ -661,27 +662,27 @@ def create( shape : int or tuple of ints Array shape. chunks : int or tuple of ints, optional - Chunk shape. If True, will be guessed from ``shape`` and ``dtype``. If - False, will be set to ``shape``, i.e., single chunk for the whole array. + Chunk shape. If True, will be guessed from `shape` and `dtype`. If + False, will be set to `shape`, i.e., single chunk for the whole array. If an int, the chunk size in each dimension will be given by the value - of ``chunks``. Default is True. + of `chunks`. Default is True. dtype : str or dtype, optional NumPy dtype. compressor : Codec, optional Primary compressor to compress chunk data. - Zarr format 2 only. Zarr format 3 arrays should use ``codecs`` instead. + Zarr format 2 only. Zarr format 3 arrays should use `codecs` instead. - If neither ``compressor`` nor ``filters`` are provided, the default compressor + If neither `compressor` nor `filters` are provided, the default compressor [`zarr.codecs.ZstdCodec`][] is used. - If ``compressor`` is set to ``None``, no compression is used. + If `compressor` is set to `None`, no compression is used. fill_value : Any, optional Fill value for the array. order : {'C', 'F'}, optional - Deprecated in favor of the ``config`` keyword argument. - Pass ``{'order': }`` to ``create`` instead of using this parameter. + Deprecated in favor of the `config` keyword argument. + Pass `{'order': }` to `create` instead of using this parameter. Memory layout to be used within each chunk. - If not specified, the ``array.order`` parameter in the global config will be used. + If not specified, the `array.order` parameter in the global config will be used. store : StoreLike or None, default=None StoreLike object to open. See the [storage documentation in the user guide][user-guide-store-like] @@ -689,12 +690,12 @@ def create( synchronizer : object, optional Array synchronizer. overwrite : bool, optional - If True, delete all pre-existing data in ``store`` at ``path`` before + If True, delete all pre-existing data in `store` at `path` before creating the array. path : str, optional Path under which array is stored. chunk_store : StoreLike or None, default=None - Separate storage for chunks. If not provided, ``store`` will be used + Separate storage for chunks. If not provided, `store` will be used for storage of both chunks and metadata. filters : Iterable[Codec] | Literal["auto"], optional Iterable of filters to apply to each chunk of the array, in order, before serializing that @@ -705,16 +706,16 @@ def create( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of `"auto"` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters contains a single element which is a codec specific to that particular data type. - To create an array with no filters, provide an empty iterable or the value ``None``. + To create an array with no filters, provide an empty iterable or the value `None`. cache_metadata : bool, optional If True, array configuration metadata will be cached for the lifetime of the object. If False, array metadata will be reloaded @@ -730,17 +731,17 @@ def create( A codec to encode object arrays, only needed if dtype=object. dimension_separator : {'.', '/'}, optional Separator placed between the dimensions of a chunk. - Zarr format 2 only. Zarr format 3 arrays should use ``chunk_key_encoding`` instead. + Zarr format 2 only. Zarr format 3 arrays should use `chunk_key_encoding` instead. write_empty_chunks : bool, optional - Deprecated in favor of the ``config`` keyword argument. - Pass ``{'write_empty_chunks': }`` to ``create`` instead of using this parameter. + Deprecated in favor of the `config` keyword argument. + Pass `{'write_empty_chunks': }` to `create` instead of using this parameter. If True, all chunks will be stored regardless of their contents. If False, each chunk is compared to the array's fill value prior to storing. If a chunk is uniformly equal to the fill value, then that chunk is not be stored, and the store entry for that chunk's key is deleted. zarr_format : {2, 3, None}, optional - The Zarr format to use when creating an array. The default is ``None``, + The Zarr format to use when creating an array. The default is `None`, which instructs Zarr to choose the default Zarr format value defined in the runtime configuration. meta_array : array-like, optional @@ -753,15 +754,15 @@ def create( chunk_key_encoding : ChunkKeyEncoding, optional A specification of how the chunk keys are represented in storage. Zarr format 3 only. Zarr format 2 arrays should use `dimension_separator` instead. - Default is ``("default", "/")``. + Default is `("default", "/")`. codecs : Sequence of Codecs or dicts, optional An iterable of Codec or dict serializations of Codecs. Zarr V3 only. - The elements of ``codecs`` specify the transformation from array values to stored bytes. - Zarr format 3 only. Zarr format 2 arrays should use ``filters`` and ``compressor`` instead. + The elements of `codecs` specify the transformation from array values to stored bytes. + Zarr format 3 only. Zarr format 2 arrays should use `filters` and `compressor` instead. If no codecs are provided, default codecs will be used based on the data type of the array. - For most data types, the default codecs are the tuple ``(BytesCodec(), ZstdCodec())``; + For most data types, the default codecs are the tuple `(BytesCodec(), ZstdCodec())`; data types that require a special [`zarr.abc.codec.ArrayBytesCodec`][], like variable-length strings or bytes, will use the [`zarr.abc.codec.ArrayBytesCodec`][] required for the data type instead of [`zarr.codecs.BytesCodec`][]. dimension_names : Iterable[str | None] | None = None @@ -799,7 +800,6 @@ def create( object_codec=object_codec, dimension_separator=dimension_separator, write_empty_chunks=write_empty_chunks, - zarr_version=zarr_version, zarr_format=zarr_format, meta_array=meta_array, attributes=attributes, @@ -822,7 +822,7 @@ def create_array( shape: ShapeLike | None = None, dtype: ZDTypeLike | None = None, data: np.ndarray[Any, np.dtype[Any]] | None = None, - chunks: tuple[int, ...] | Literal["auto"] = "auto", + chunks: ChunksLike | Literal["auto"] = "auto", shards: ShardsLike | None = None, filters: FiltersLike = "auto", compressors: CompressorsLike = "auto", @@ -832,7 +832,7 @@ def create_array( zarr_format: ZarrFormat | None = 3, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, overwrite: bool = False, config: ArrayConfigLike | None = None, @@ -849,20 +849,24 @@ def create_array( [storage documentation in the user guide][user-guide-store-like] for a description of all valid StoreLike values. name : str or None, optional - The name of the array within the store. If ``name`` is ``None``, the array will be located + The name of the array within the store. If `name` is `None`, the array will be located at the root of the store. shape : ShapeLike, optional - Shape of the array. Must be ``None`` if ``data`` is provided. + Shape of the array. Must be `None` if `data` is provided. dtype : ZDTypeLike | None - Data type of the array. Must be ``None`` if ``data`` is provided. + Data type of the array. Must be `None` if `data` is provided. data : np.ndarray, optional Array-like data to use for initializing the array. If this parameter is provided, the - ``shape`` and ``dtype`` parameters must be ``None``. - chunks : tuple[int, ...] | Literal["auto"], default="auto" + `shape` and `dtype` parameters must be `None`. + chunks : tuple[int, ...] | Sequence[Sequence[int]] | Literal["auto"], default="auto" Chunk shape of the array. If chunks is "auto", a chunk shape is guessed based on the shape of the array and the dtype. + A nested list of per-dimension edge sizes creates a rectilinear grid. + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. shards : tuple[int, ...], optional - Shard shape of the array. The default value of ``None`` results in no sharding at all. + Shard shape of the array. The default value of `None` results in no sharding at all. filters : Iterable[Codec] | Literal["auto"], optional Iterable of filters to apply to each chunk of the array, in order, before serializing that chunk to bytes. @@ -873,56 +877,56 @@ def create_array( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of `"auto"` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters contains a single element which is a codec specific to that particular data type. - To create an array with no filters, provide an empty iterable or the value ``None``. + To create an array with no filters, provide an empty iterable or the value `None`. compressors : Iterable[Codec], optional List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes. For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. - If no ``compressors`` are provided, a default set of compressors will be used. - These defaults can be changed by modifying the value of ``array.v3_default_compressors`` + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + If no `compressors` are provided, a default set of compressors will be used. + These defaults can be changed by modifying the value of `array.v3_default_compressors` in [`zarr.config`][zarr.config]. - Use ``None`` to omit default compressors. + Use `None` to omit default compressors. For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. - If no ``compressor`` is provided, a default compressor will be used. + If no `compressor` is provided, a default compressor will be used. in [`zarr.config`][zarr.config]. - Use ``None`` to omit the default compressor. + Use `None` to omit the default compressor. serializer : dict[str, JSON] | ArrayBytesCodec, optional Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. - If no ``serializer`` is provided, a default serializer will be used. - These defaults can be changed by modifying the value of ``array.v3_default_serializer`` + If no `serializer` is provided, a default serializer will be used. + These defaults can be changed by modifying the value of `array.v3_default_serializer` in [`zarr.config`][zarr.config]. fill_value : Any, optional Fill value for the array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory - order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. - If no ``order`` is provided, a default order will be used. - This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config]. + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If no `order` is provided, a default order will be used. + This default can be changed by modifying the value of `array.order` in [`zarr.config`][zarr.config]. zarr_format : {2, 3}, optional The zarr format to use when saving. attributes : dict, optional Attributes for the array. chunk_key_encoding : ChunkKeyEncodingLike, optional A specification of how the chunk keys are represented in storage. - For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. - For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. dimension_names : Iterable[str], optional The names of the dimensions (default is None). Zarr format 3 only. Zarr format 2 arrays should not use this parameter. @@ -931,13 +935,13 @@ def create_array( Ignored otherwise. overwrite : bool, default False Whether to overwrite an array with the same name in the store, if one exists. - If ``True``, all existing paths in the store will be deleted. + If `True`, all existing paths in the store will be deleted. config : ArrayConfigLike, optional Runtime configuration for the array. write_data : bool - If a pre-existing array-like object was provided to this function via the ``data`` parameter - then ``write_data`` determines whether the values in that array-like object should be - written to the Zarr array created by this function. If ``write_data`` is ``False``, then the + If a pre-existing array-like object was provided to this function via the `data` parameter + then `write_data` determines whether the values in that array-like object should be + written to the Zarr array created by this function. If `write_data` is `False`, then the array will be left empty. Returns @@ -993,8 +997,8 @@ def from_array( data: AnyArray | npt.ArrayLike, write_data: bool = True, name: str | None = None, - chunks: Literal["auto", "keep"] | tuple[int, ...] = "keep", - shards: ShardsLike | None | Literal["keep"] = "keep", + chunks: ChunksLike | Literal["auto", "keep"] = "keep", + shards: ShardsLike | Literal["keep"] | None = "keep", filters: FiltersLike | Literal["keep"] = "keep", compressors: CompressorsLike | Literal["keep"] = "keep", serializer: SerializerLike | Literal["keep"] = "keep", @@ -1003,7 +1007,7 @@ def from_array( zarr_format: ZarrFormat | None = None, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, overwrite: bool = False, config: ArrayConfigLike | None = None, @@ -1020,18 +1024,22 @@ def from_array( The array to copy. write_data : bool, default True Whether to copy the data from the input array to the new array. - If ``write_data`` is ``False``, the new array will be created with the same metadata as the + If `write_data` is `False`, the new array will be created with the same metadata as the input array, but without any data. name : str or None, optional - The name of the array within the store. If ``name`` is ``None``, the array will be located + The name of the array within the store. If `name` is `None`, the array will be located at the root of the store. - chunks : tuple[int, ...] or "auto" or "keep", optional + chunks : tuple[int, ...] or Sequence[Sequence[int]] or "auto" or "keep", optional Chunk shape of the array. Following values are supported: - "auto": Automatically determine the chunk shape based on the array's shape and dtype. - - "keep": Retain the chunk shape of the data array if it is a zarr Array. - - tuple[int, ...]: A tuple of integers representing the chunk shape. + - "keep": Retain the chunk grid of the data array if it is a zarr Array. + - tuple[int, ...]: A tuple of integers representing the chunk shape (regular grid). + - Sequence[Sequence[int]]: Per-dimension chunk edge lists (rectilinear grid). + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. If not specified, defaults to "keep" if data is a zarr Array, otherwise "auto". shards : tuple[int, ...], optional @@ -1053,24 +1061,24 @@ def from_array( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"keep"`` instructs Zarr to infer ``filters`` from ``data``. - If that inference is not possible, Zarr will fall back to the behavior specified by ``"auto"``, + The default value of `"keep"` instructs Zarr to infer `filters` from `data`. + If that inference is not possible, Zarr will fall back to the behavior specified by `"auto"`, which is to choose default filters based on the data type of the array and the Zarr format specified. - For all data types in Zarr V3, and most data types in Zarr V2, the default filters are the empty tuple ``()``. + For all data types in Zarr V3, and most data types in Zarr V2, the default filters are the empty tuple `()`. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters is a tuple with a single element which is a codec specific to that particular data type. - To create an array with no filters, provide an empty iterable or the value ``None``. + To create an array with no filters, provide an empty iterable or the value `None`. compressors : Iterable[Codec] or "auto" or "keep", optional List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes. For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. + returns another bytestream. Multiple compressors may be provided for Zarr format 3. For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. @@ -1081,28 +1089,28 @@ def from_array( - "auto": Automatically determine the compressors based on the array's dtype. - "keep": Retain the compressors of the input array if it is a zarr Array. - If no ``compressors`` are provided, defaults to "keep" if data is a zarr Array, otherwise "auto". + If no `compressors` are provided, defaults to "keep" if data is a zarr Array, otherwise "auto". serializer : dict[str, JSON] | ArrayBytesCodec or "auto" or "keep", optional Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. Following values are supported: - - dict[str, JSON]: A dict representation of an ``ArrayBytesCodec``. - - ArrayBytesCodec: An instance of ``ArrayBytesCodec``. + - dict[str, JSON]: A dict representation of an `ArrayBytesCodec`. + - ArrayBytesCodec: An instance of `ArrayBytesCodec`. - "auto": a default serializer will be used. These defaults can be changed by modifying the value of - ``array.v3_default_serializer`` in [`zarr.config`][zarr.config]. + `array.v3_default_serializer` in [`zarr.config`][zarr.config]. - "keep": Retain the serializer of the input array if it is a zarr Array. fill_value : Any, optional Fill value for the array. If not specified, defaults to the fill value of the data array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory - order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. If not specified, defaults to the memory order of the data array. zarr_format : {2, 3}, optional The zarr format to use when saving. @@ -1112,8 +1120,8 @@ def from_array( If not specified, defaults to the attributes of the data array. chunk_key_encoding : ChunkKeyEncoding, optional A specification of how the chunk keys are represented in storage. - For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. - For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. If not specified and the data array has the same zarr format as the target array, the chunk key encoding of the data array is used. dimension_names : Iterable[str | None] | None @@ -1137,63 +1145,45 @@ def from_array( -------- Create an array from an existing Array: - ```python - import zarr - store = zarr.storage.MemoryStore() - store2 = zarr.storage.LocalStore('example_from_array.zarr') - arr = zarr.create_array( - store=store, - shape=(100,100), - chunks=(10,10), - dtype='int32', - fill_value=0) - arr2 = zarr.from_array(store2, data=arr, overwrite=True) - # - ``` + >>> import asyncio + >>> import zarr + >>> store = zarr.storage.LocalStore("example_from_array.zarr") + >>> arr = zarr.create_array( + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="int32", + ... fill_value=0 + ... ) + >>> arr2 = zarr.from_array(store, data=arr, overwrite=True) + >>> arr2 + + >>> asyncio.run(store.clear()) # Remove files generated by test Create an array from an existing NumPy array: - ```python - import zarr - import numpy as np - arr3 = zarr.from_array( - zarr.storage.MemoryStore(), - data=np.arange(10000, dtype='i4').reshape(100, 100), - ) - # - ``` + >>> import numpy as np + >>> zarr.from_array({}, data=np.arange(10000, dtype="i4").reshape(100, 100)) + Create an array from any array-like object: - ```python - import zarr - arr4 = zarr.from_array( - zarr.storage.MemoryStore(), - data=[[1, 2], [3, 4]], - ) - # - arr4[...] - # array([[1, 2],[3, 4]]) - ``` + >>> arr3 = zarr.from_array({}, data=[[1, 2], [3, 4]]) + >>> arr3 + + >>> arr3[...] + array([[1, 2], [3, 4]]) Create an array from an existing Array without copying the data: - ```python - import zarr - arr4 = zarr.from_array( - zarr.storage.MemoryStore(), - data=[[1, 2], [3, 4]], - ) - arr5 = zarr.from_array( - zarr.storage.MemoryStore(), - data=arr4, - write_data=False, - ) - # - arr5[...] - # array([[0, 0],[0, 0]]) - ``` + >>> arr4 = zarr.from_array({}, data=[[1, 2], [3, 4]]) + >>> arr5 = zarr.from_array({}, data=arr4, write_data=False) + >>> arr5 + + >>> arr5[...] + array([[0, 0], [0, 0]]) """ + return Array( sync( zarr.core.array.from_array( @@ -1356,7 +1346,6 @@ def ones_like(a: ArrayLike, **kwargs: Any) -> AnyArray: def open_array( store: StoreLike | None = None, *, - zarr_version: ZarrFormat | None = None, zarr_format: ZarrFormat | None = None, path: PathLike = "", storage_options: dict[str, Any] | None = None, @@ -1370,8 +1359,6 @@ def open_array( StoreLike object to open. See the [storage documentation in the user guide][user-guide-store-like] for a description of all valid StoreLike values. - zarr_version : {2, 3, None}, optional - The zarr format to use when saving. Deprecated in favor of zarr_format. zarr_format : {2, 3, None}, optional The zarr format to use when saving. path : str, optional @@ -1392,7 +1379,6 @@ def open_array( sync( async_api.open_array( store=store, - zarr_version=zarr_version, zarr_format=zarr_format, path=path, storage_options=storage_options, @@ -1413,11 +1399,13 @@ def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AnyArray: path : str The path to the new array. **kwargs - Any keyword arguments to pass to the array constructor. + Additional keyword arguments passed to `open_array`. + If `mode` is omitted or `None`, it defaults to `"a"`. Pass `mode="r"` when + opening an existing array from a read-only store. Returns ------- - AsyncArray + Array The opened array. """ return Array(sync(async_api.open_like(a, path=path, **kwargs))) diff --git a/src/zarr/codecs/__init__.py b/src/zarr/codecs/__init__.py index 4c621290e7..9a1b47b351 100644 --- a/src/zarr/codecs/__init__.py +++ b/src/zarr/codecs/__init__.py @@ -2,6 +2,7 @@ from zarr.codecs.blosc import BloscCname, BloscCodec, BloscShuffle from zarr.codecs.bytes import BytesCodec, Endian +from zarr.codecs.cast_value import CastValue from zarr.codecs.crc32c_ import Crc32cCodec from zarr.codecs.gzip import GzipCodec from zarr.codecs.numcodecs import ( @@ -27,7 +28,8 @@ Zlib, Zstd, ) -from zarr.codecs.sharding import ShardingCodec, ShardingCodecIndexLocation +from zarr.codecs.scale_offset import ScaleOffset +from zarr.codecs.sharding import ShardingCodec, ShardingCodecIndexLocation, SubchunkWriteOrder from zarr.codecs.transpose import TransposeCodec from zarr.codecs.vlen_utf8 import VLenBytesCodec, VLenUTF8Codec from zarr.codecs.zstd import ZstdCodec @@ -38,11 +40,14 @@ "BloscCodec", "BloscShuffle", "BytesCodec", + "CastValue", "Crc32cCodec", "Endian", "GzipCodec", + "ScaleOffset", "ShardingCodec", "ShardingCodecIndexLocation", + "SubchunkWriteOrder", "TransposeCodec", "VLenBytesCodec", "VLenUTF8Codec", @@ -50,12 +55,14 @@ ] register_codec("blosc", BloscCodec) +register_codec("cast_value", CastValue) register_codec("bytes", BytesCodec) # compatibility with earlier versions of ZEP1 register_codec("endian", BytesCodec) register_codec("crc32c", Crc32cCodec) register_codec("gzip", GzipCodec) +register_codec("scale_offset", ScaleOffset) register_codec("sharding_indexed", ShardingCodec) register_codec("zstd", ZstdCodec) register_codec("vlen-utf8", VLenUTF8Codec) diff --git a/src/zarr/codecs/_deprecated_enum.py b/src/zarr/codecs/_deprecated_enum.py new file mode 100644 index 0000000000..5538ae26f6 --- /dev/null +++ b/src/zarr/codecs/_deprecated_enum.py @@ -0,0 +1,59 @@ +"""Helpers for deprecating string-valued enums in favor of literal strings. + +See PR #3963 for context on the deprecation pattern. +""" + +from __future__ import annotations + +import warnings +from enum import Enum + + +class _DeprecatedStrEnumMeta(type): + """ + Metaclass for legacy enum-like classes. Accessing a member name on the + class (e.g. `LegacyShim.foo`) emits a `DeprecationWarning` and returns + the equivalent string. Members are declared by setting a `_members` + class attribute mapping each member name to its string value. + """ + + _members: dict[str, str] + + def __getattr__(cls, name: str) -> str: + members: dict[str, str] = type.__getattribute__(cls, "_members") + if name in members: + warnings.warn( + f"{cls.__name__}.{name} is deprecated; pass the string {members[name]!r} instead.", + DeprecationWarning, + stacklevel=2, + ) + return members[name] + raise AttributeError(name) + + +def _coerce_enum_input(value: object, param_name: str, codec_name: str) -> object: + """ + If `value` is a real `enum.Enum` instance, emit a deprecation warning + naming `codec_name` and return `value.value`. Otherwise return `value` + unchanged. The third argument lets the warning text name the actual + codec (e.g. `BloscCodec`, `BytesCodec`, `ShardingCodec`). + + Note that zarr's own legacy classes (e.g. `ShardingCodecIndexLocation`) + never reach the `Enum` branch here: they no longer inherit from `Enum`, + and member access on them already returns a plain string (with its own + warning) via `_DeprecatedStrEnumMeta`. This branch exists for enum + instances defined *outside* zarr — in particular `str`-mixin enums that + downstream code defined to mirror zarr's old enums, which the old + `parse_enum`-based codepath accepted because they are `str` instances. + Coercing them to `value.value` keeps the stored attribute a plain string + and gives those callers a migration warning. + """ + if isinstance(value, Enum): + warnings.warn( + f"Passing an enum to {codec_name}(..., {param_name}=...) is deprecated; " + "pass the equivalent literal string instead.", + DeprecationWarning, + stacklevel=3, + ) + return value.value + return value diff --git a/src/zarr/codecs/_v2.py b/src/zarr/codecs/_v2.py index 3c6c99c21c..7fdf408d1d 100644 --- a/src/zarr/codecs/_v2.py +++ b/src/zarr/codecs/_v2.py @@ -23,7 +23,7 @@ class V2Codec(ArrayBytesCodec): is_fixed_size = False - async def _decode_single( + def _decode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, @@ -31,14 +31,14 @@ async def _decode_single( cdata = chunk_bytes.as_array_like() # decompress if self.compressor: - chunk = await asyncio.to_thread(self.compressor.decode, cdata) + chunk = self.compressor.decode(cdata) else: chunk = cdata # apply filters if self.filters: for f in reversed(self.filters): - chunk = await asyncio.to_thread(f.decode, chunk) + chunk = f.decode(chunk) # view as numpy array with correct dtype chunk = ensure_ndarray_like(chunk) @@ -70,7 +70,7 @@ async def _decode_single( return get_ndbuffer_class().from_ndarray_like(chunk) - async def _encode_single( + def _encode_sync( self, chunk_array: NDBuffer, chunk_spec: ArraySpec, @@ -83,18 +83,32 @@ async def _encode_single( # apply filters if self.filters: for f in self.filters: - chunk = await asyncio.to_thread(f.encode, chunk) + chunk = f.encode(chunk) # check object encoding if ensure_ndarray_like(chunk).dtype == object: raise RuntimeError("cannot write object array without object codec") # compress if self.compressor: - cdata = await asyncio.to_thread(self.compressor.encode, chunk) + cdata = self.compressor.encode(chunk) else: cdata = chunk cdata = ensure_bytes(cdata) return chunk_spec.prototype.buffer.from_bytes(cdata) + async def _decode_single( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return await asyncio.to_thread(self._decode_sync, chunk_bytes, chunk_spec) + + async def _encode_single( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return await asyncio.to_thread(self._encode_sync, chunk_array, chunk_spec) + def compute_encoded_size(self, _input_byte_length: int, _chunk_spec: ArraySpec) -> int: raise NotImplementedError diff --git a/src/zarr/codecs/blosc.py b/src/zarr/codecs/blosc.py index 62ceff7659..ee45632153 100644 --- a/src/zarr/codecs/blosc.py +++ b/src/zarr/codecs/blosc.py @@ -2,18 +2,19 @@ import asyncio from dataclasses import dataclass, field, replace -from enum import Enum from functools import cached_property -from typing import TYPE_CHECKING, Final, Literal, NotRequired, TypedDict +from typing import TYPE_CHECKING, ClassVar, Final, Literal, NotRequired, TypedDict import numcodecs from numcodecs.blosc import Blosc from packaging.version import Version from zarr.abc.codec import BytesBytesCodec +from zarr.codecs._deprecated_enum import _coerce_enum_input, _DeprecatedStrEnumMeta from zarr.core.buffer.cpu import as_numpy_array_wrapper -from zarr.core.common import JSON, NamedRequiredConfig, parse_enum, parse_named_configuration +from zarr.core.common import JSON, NamedRequiredConfig, parse_named_configuration from zarr.core.dtype.common import HasItemSize +from zarr.core.json_parse import parse_field if TYPE_CHECKING: from typing import Self @@ -21,19 +22,21 @@ from zarr.core.array_spec import ArraySpec from zarr.core.buffer import Buffer -Shuffle = Literal["noshuffle", "shuffle", "bitshuffle"] +BloscShuffleLiteral = Literal["noshuffle", "shuffle", "bitshuffle"] """The shuffle values permitted for the blosc codec""" -SHUFFLE: Final = ("noshuffle", "shuffle", "bitshuffle") +BLOSC_SHUFFLE: Final = ("noshuffle", "shuffle", "bitshuffle") -CName = Literal["lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd"] -"""The codec identifiers used in the blosc codec """ +BloscCnameLiteral = Literal["lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd"] +"""The codec identifiers used in the blosc codec""" + +BLOSC_CNAME: Final = ("lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd") class BloscConfigV2(TypedDict): """Configuration for the V2 Blosc codec""" - cname: CName + cname: BloscCnameLiteral clevel: int shuffle: int blocksize: int @@ -43,9 +46,9 @@ class BloscConfigV2(TypedDict): class BloscConfigV3(TypedDict): """Configuration for the V3 Blosc codec""" - cname: CName + cname: BloscCnameLiteral clevel: int - shuffle: Shuffle + shuffle: BloscShuffleLiteral blocksize: int typesize: int @@ -56,38 +59,45 @@ class BloscJSON_V3(NamedRequiredConfig[Literal["blosc"], BloscConfigV3]): """ -class BloscShuffle(Enum): +class BloscShuffle(metaclass=_DeprecatedStrEnumMeta): """ - Enum for shuffle filter used by blosc. + Deprecated. Pass a literal string (`"noshuffle"`, `"shuffle"`, or + `"bitshuffle"`) directly to `BloscCodec` instead. """ - noshuffle = "noshuffle" - shuffle = "shuffle" - bitshuffle = "bitshuffle" + _members: ClassVar[dict[str, str]] = { + "noshuffle": "noshuffle", + "shuffle": "shuffle", + "bitshuffle": "bitshuffle", + } - @classmethod - def from_int(cls, num: int) -> BloscShuffle: - blosc_shuffle_int_to_str = { + @staticmethod + def from_int(num: int) -> BloscShuffleLiteral: + mapping: dict[int, BloscShuffleLiteral] = { 0: "noshuffle", 1: "shuffle", 2: "bitshuffle", } - if num not in blosc_shuffle_int_to_str: + if num not in mapping: raise ValueError(f"Value must be between 0 and 2. Got {num}.") - return BloscShuffle[blosc_shuffle_int_to_str[num]] + return mapping[num] -class BloscCname(Enum): +class BloscCname(metaclass=_DeprecatedStrEnumMeta): """ - Enum for compression library used by blosc. + Deprecated. Pass a literal string (one of `"lz4"`, `"lz4hc"`, + `"blosclz"`, `"snappy"`, `"zlib"`, `"zstd"`) directly to + `BloscCodec` instead. """ - lz4 = "lz4" - lz4hc = "lz4hc" - blosclz = "blosclz" - zstd = "zstd" - snappy = "snappy" - zlib = "zlib" + _members: ClassVar[dict[str, str]] = { + "lz4": "lz4", + "lz4hc": "lz4hc", + "blosclz": "blosclz", + "snappy": "snappy", + "zstd": "zstd", + "zlib": "zlib", + } # See https://zarr.readthedocs.io/en/stable/user-guide/performance.html#configuring-blosc @@ -95,27 +105,36 @@ class BloscCname(Enum): def parse_typesize(data: JSON) -> int: - if isinstance(data, int): - if data > 0: - return data - else: - raise ValueError( - f"Value must be greater than 0. Got {data}, which is less or equal to 0." - ) - raise TypeError(f"Value must be an int. Got {type(data)} instead.") + parsed: int = parse_field(data, int, "typesize", error=TypeError) + if parsed > 0: + return parsed + else: + raise ValueError( + f"Value must be greater than 0. Got {parsed}, which is less or equal to 0." + ) # todo: real validation def parse_clevel(data: JSON) -> int: - if isinstance(data, int): - return data - raise TypeError(f"Value should be an int. Got {type(data)} instead.") + parsed: int = parse_field(data, int, "clevel", error=TypeError) + return parsed def parse_blocksize(data: JSON) -> int: - if isinstance(data, int): - return data - raise TypeError(f"Value should be an int. Got {type(data)} instead.") + parsed: int = parse_field(data, int, "blocksize", error=TypeError) + return parsed + + +def _parse_cname(data: object) -> BloscCnameLiteral: + if isinstance(data, str) and data in BLOSC_CNAME: + return data # type: ignore[return-value] + raise ValueError(f"cname must be one of {list(BLOSC_CNAME)!r}. Got {data!r}.") + + +def _parse_shuffle(data: object) -> BloscShuffleLiteral: + if isinstance(data, str) and data in BLOSC_SHUFFLE: + return data # type: ignore[return-value] + raise ValueError(f"shuffle must be one of {list(BLOSC_SHUFFLE)!r}. Got {data!r}.") @dataclass(frozen=True) @@ -133,12 +152,14 @@ class BloscCodec(BytesBytesCodec): Always False for Blosc codec, as compression produces variable-sized output. typesize : int The data type size in bytes used for shuffle filtering. - cname : BloscCname - The compression algorithm being used (lz4, lz4hc, blosclz, snappy, zlib, or zstd). + cname : BloscCnameLiteral + The compression algorithm being used; one of "lz4", "lz4hc", + "blosclz", "snappy", "zlib", or "zstd". clevel : int The compression level (0-9). - shuffle : BloscShuffle - The shuffle filter mode (noshuffle, shuffle, or bitshuffle). + shuffle : BloscShuffleLiteral + The shuffle filter mode; one of "noshuffle", "shuffle", or + "bitshuffle". blocksize : int The size of compressed blocks in bytes (0 for automatic). @@ -148,13 +169,16 @@ class BloscCodec(BytesBytesCodec): The data type size in bytes. This affects how the shuffle filter processes the data. If None, defaults to 1 and the attribute is marked as tunable. Default: 1. - cname : BloscCname or {'lz4', 'lz4hc', 'blosclz', 'snappy', 'zlib', 'zstd'}, optional - The compression algorithm to use. Default: 'zstd'. + cname : BloscCnameLiteral, optional + The compression algorithm to use; one of "lz4", "lz4hc", "blosclz", + "snappy", "zlib", or "zstd". Default is "zstd". Passing a `BloscCname` + enum is deprecated. clevel : int, optional The compression level, from 0 (no compression) to 9 (maximum compression). Higher values provide better compression at the cost of speed. Default: 5. - shuffle : BloscShuffle or {'noshuffle', 'shuffle', 'bitshuffle'}, optional - The shuffle filter to apply before compression: + shuffle : BloscShuffleLiteral or None, optional + The shuffle filter to apply before compression; one of "noshuffle", + "shuffle", or "bitshuffle": - 'noshuffle': No shuffling - 'shuffle': Byte shuffling (better for typesize > 1) @@ -183,18 +207,13 @@ class BloscCodec(BytesBytesCodec): >>> codec.typesize 1 >>> codec.shuffle - + 'bitshuffle' Create a codec with specific compression settings: >>> codec = BloscCodec(cname='zstd', clevel=9, shuffle='shuffle') >>> codec.cname - - - See Also - -------- - BloscShuffle : Enum for shuffle filter options - BloscCname : Enum for compression algorithm options + 'zstd' """ # This attribute tracks parameters were set to None at init time, and thus tunable @@ -202,38 +221,37 @@ class BloscCodec(BytesBytesCodec): is_fixed_size = False typesize: int - cname: BloscCname + cname: BloscCnameLiteral clevel: int - shuffle: BloscShuffle + shuffle: BloscShuffleLiteral blocksize: int def __init__( self, *, typesize: int | None = None, - cname: BloscCname | CName = BloscCname.zstd, + cname: BloscCname | BloscCnameLiteral = "zstd", clevel: int = 5, - shuffle: BloscShuffle | Shuffle | None = None, + shuffle: BloscShuffle | BloscShuffleLiteral | None = None, blocksize: int = 0, ) -> None: object.__setattr__(self, "_tunable_attrs", set()) - # If typesize was set to None, replace it with a valid typesize - # and flag the typesize attribute as safe to replace later if typesize is None: typesize = 1 self._tunable_attrs.update({"typesize"}) - # If shuffle was set to None, replace it with a valid shuffle - # and flag the shuffle attribute as safe to replace later if shuffle is None: - shuffle = BloscShuffle.bitshuffle + shuffle = "bitshuffle" self._tunable_attrs.update({"shuffle"}) + cname = _coerce_enum_input(cname, "cname", "BloscCodec") # type: ignore[assignment] + shuffle = _coerce_enum_input(shuffle, "shuffle", "BloscCodec") # type: ignore[assignment] + typesize_parsed = parse_typesize(typesize) - cname_parsed = parse_enum(cname, BloscCname) + cname_parsed = _parse_cname(cname) clevel_parsed = parse_clevel(clevel) - shuffle_parsed = parse_enum(shuffle, BloscShuffle) + shuffle_parsed = _parse_shuffle(shuffle) blocksize_parsed = parse_blocksize(blocksize) object.__setattr__(self, "typesize", typesize_parsed) @@ -252,9 +270,9 @@ def to_dict(self) -> dict[str, JSON]: "name": "blosc", "configuration": { "typesize": self.typesize, - "cname": self.cname.value, + "cname": self.cname, "clevel": self.clevel, - "shuffle": self.shuffle.value, + "shuffle": self.shuffle, "blocksize": self.blocksize, }, } @@ -276,20 +294,20 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: if "shuffle" in self._tunable_attrs: new_codec = replace( new_codec, - shuffle=(BloscShuffle.bitshuffle if item_size == 1 else BloscShuffle.shuffle), + shuffle=("bitshuffle" if item_size == 1 else "shuffle"), ) return new_codec @cached_property def _blosc_codec(self) -> Blosc: - map_shuffle_str_to_int = { - BloscShuffle.noshuffle: 0, - BloscShuffle.shuffle: 1, - BloscShuffle.bitshuffle: 2, + map_shuffle_str_to_int: dict[BloscShuffleLiteral, int] = { + "noshuffle": 0, + "shuffle": 1, + "bitshuffle": 2, } config_dict: BloscConfigV2 = { - "cname": self.cname.name, # type: ignore[typeddict-item] + "cname": self.cname, "clevel": self.clevel, "shuffle": map_shuffle_str_to_int[self.shuffle], "blocksize": self.blocksize, diff --git a/src/zarr/codecs/bytes.py b/src/zarr/codecs/bytes.py index 86bb354fb5..fae762fd08 100644 --- a/src/zarr/codecs/bytes.py +++ b/src/zarr/codecs/bytes.py @@ -1,14 +1,16 @@ from __future__ import annotations import sys +import warnings from dataclasses import dataclass, replace -from enum import Enum -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar, Final, Literal from zarr.abc.codec import ArrayBytesCodec +from zarr.codecs._deprecated_enum import _coerce_enum_input, _DeprecatedStrEnumMeta from zarr.core.buffer import Buffer, NDBuffer -from zarr.core.common import JSON, parse_enum, parse_named_configuration +from zarr.core.common import JSON, parse_named_configuration from zarr.core.dtype.common import HasEndianness +from zarr.core.dtype.npy.structured import Struct if TYPE_CHECKING: from typing import Self @@ -16,16 +18,25 @@ from zarr.core.array_spec import ArraySpec -class Endian(Enum): +EndianLiteral = Literal["little", "big"] +"""Byte order of multi-byte numeric data.""" + +ENDIAN: Final = ("little", "big") + + +class Endian(metaclass=_DeprecatedStrEnumMeta): """ - Enum for endian type used by bytes codec. + Deprecated. Pass a literal string (`"little"` or `"big"`) directly to + `BytesCodec` instead. """ - big = "big" - little = "little" + _members: ClassVar[dict[str, str]] = {"little": "little", "big": "big"} -default_system_endian = Endian(sys.byteorder) +def _parse_endian(data: object) -> EndianLiteral: + if isinstance(data, str) and data in ENDIAN: + return data # type: ignore[return-value] + raise ValueError(f"endian must be one of {list(ENDIAN)!r}. Got {data!r}.") @dataclass(frozen=True) @@ -34,10 +45,14 @@ class BytesCodec(ArrayBytesCodec): is_fixed_size = True - endian: Endian | None + endian: EndianLiteral | None - def __init__(self, *, endian: Endian | str | None = default_system_endian) -> None: - endian_parsed = None if endian is None else parse_enum(endian, Endian) + def __init__(self, *, endian: Endian | EndianLiteral | None = sys.byteorder) -> None: + if endian is None: + endian_parsed: EndianLiteral | None = None + else: + coerced = _coerce_enum_input(endian, "endian", "BytesCodec") + endian_parsed = _parse_endian(coerced) object.__setattr__(self, "endian", endian_parsed) @@ -47,16 +62,30 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: data, "bytes", require_configuration=False ) configuration_parsed = configuration_parsed or {} + configuration_parsed.setdefault("endian", None) return cls(**configuration_parsed) # type: ignore[arg-type] def to_dict(self) -> dict[str, JSON]: if self.endian is None: return {"name": "bytes"} else: - return {"name": "bytes", "configuration": {"endian": self.endian.value}} + return {"name": "bytes", "configuration": {"endian": self.endian}} def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: - if not isinstance(array_spec.dtype, HasEndianness): + if isinstance(array_spec.dtype, Struct): + if array_spec.dtype.has_multi_byte_fields(): + if self.endian is None: + warnings.warn( + "Missing 'endian' for structured dtype with multi-byte fields. " + "Assuming little-endian for legacy compatibility.", + UserWarning, + stacklevel=2, + ) + return replace(self, endian="little") + else: + if self.endian is not None: + return replace(self, endian=None) + elif not isinstance(array_spec.dtype, HasEndianness): if self.endian is not None: return replace(self, endian=None) elif self.endian is None: @@ -70,16 +99,29 @@ def _decode_sync( chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> NDBuffer: - # TODO: remove endianness enum in favor of literal union - endian_str = self.endian.value if self.endian is not None else None + endian_str = self.endian + dtype = chunk_spec.dtype.to_native_dtype() + # The byte order of the stored data is set by this codec's `endian` + # configuration; the byte order of the decoded array is set by the array's + # data type. The two are independent: the raw bytes are viewed with a dtype + # in the stored byte order, then converted to the declared dtype if needed. if isinstance(chunk_spec.dtype, HasEndianness): - dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] + view_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] + elif isinstance(chunk_spec.dtype, Struct) and endian_str is not None: + # Per the struct data type spec, all multi-byte fields are stored in the + # byte order configured on this codec. + view_dtype = dtype.newbyteorder(endian_str) else: - dtype = chunk_spec.dtype.to_native_dtype() + view_dtype = dtype as_array_like = chunk_bytes.as_array_like() chunk_array = chunk_spec.prototype.nd_buffer.from_ndarray_like( - as_array_like.view(dtype=dtype) # type: ignore[attr-defined] + as_array_like.view(dtype=view_dtype) # type: ignore[attr-defined] ) + if view_dtype != dtype: + # This byte-swapping conversion copies the chunk. The dtype inequality + # guard keeps the common case, where the stored and declared byte orders + # already match, on the zero-copy view path above. + chunk_array = chunk_array.astype(dtype) # ensure correct chunk shape if chunk_array.shape != chunk_spec.shape: @@ -101,15 +143,14 @@ def _encode_sync( chunk_spec: ArraySpec, ) -> Buffer | None: assert isinstance(chunk_array, NDBuffer) - if ( - chunk_array.dtype.itemsize > 1 - and self.endian is not None - and self.endian != chunk_array.byteorder - ): - # type-ignore is a numpy bug - # see https://github.com/numpy/numpy/issues/26473 - new_dtype = chunk_array.dtype.newbyteorder(self.endian.name) # type: ignore[arg-type] - chunk_array = chunk_array.astype(new_dtype) + if chunk_array.dtype.itemsize > 1 and self.endian is not None: + # Compare full dtypes rather than the top-level byteorder: numpy reports + # byteorder '|' for structured dtypes even when their fields are + # byte-order-sensitive, so newbyteorder is the only reliable way to + # detect (and normalize) a byte-order mismatch. + new_dtype = chunk_array.dtype.newbyteorder(self.endian) + if new_dtype != chunk_array.dtype: + chunk_array = chunk_array.astype(new_dtype) nd_array = chunk_array.as_ndarray_like() # Flatten the nd-array (only copy if needed) and reinterpret as bytes diff --git a/src/zarr/codecs/cast_value.py b/src/zarr/codecs/cast_value.py new file mode 100644 index 0000000000..b19a10c873 --- /dev/null +++ b/src/zarr/codecs/cast_value.py @@ -0,0 +1,435 @@ +"""Cast-value array-to-array codec. + +Value-converts array elements to a new data type during encoding, +and back to the original data type during decoding, with configurable +rounding, out-of-range handling, and explicit scalar mappings. + +Requires the optional ``cast-value-rs`` package for the actual casting +logic. Install it with: ``pip install 'cast-value-rs>=0.4.2'``. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, replace +from importlib.metadata import PackageNotFoundError, version +from typing import TYPE_CHECKING, Final, Literal, TypedDict, cast + +import numpy as np +from packaging.version import Version + +from zarr.abc.codec import ArrayArrayCodec +from zarr.core.common import JSON, parse_named_configuration +from zarr.core.dtype import get_data_type_from_json + +if TYPE_CHECKING: + from typing import NotRequired, Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.metadata.v3 import ChunkGridMetadata + + class ScalarMapJSON(TypedDict): + encode: NotRequired[list[tuple[object, object]]] + decode: NotRequired[list[tuple[object, object]]] + + +RoundingMode = Literal[ + "nearest-even", + "towards-zero", + "towards-positive", + "towards-negative", + "nearest-away", +] + +OutOfRangeMode = Literal["clamp", "wrap"] + + +class ScalarMap(TypedDict, total=False): + """ + The normalized, in-memory form of a scalar map. + """ + + encode: Mapping[str | float | int, str | float | int] + decode: Mapping[str | float | int, str | float | int] + + +# see https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/cast_value +CAST_VALUE_INT_DTYPES: Final[set[str]] = { + # signed + "int2", + "int4", + "int8", + "int16", + "int32", + "int64", + # unsigned + "uint2", + "uint4", + "uint8", + "uint16", + "uint32", + "uint64", +} +"""Integer dtype identifiers permitted as the source or target of `cast_value`. + +Membership in this set drives the `out_of_range="wrap"` rule, which the +spec restricts to integral targets that use two's-complement representation +for modular arithmetic. +""" + +CAST_VALUE_FLOAT_DTYPES: Final[set[str]] = { + "float4_e2m1fn", + "float6_e2m3fn", + "float6_e3m2fn", + "float8_e3m4", + "float8_e4m3", + "float8_e4m3b11fnuz", + "float8_e4m3fnuz", + "float8_e5m2", + "float8_e5m2fnuz", + "float8_e8m0fnu", + "bfloat16", + "float16", + "float32", + "float64", +} +"""Floating-point dtype identifiers permitted as the source or target of `cast_value`.""" + +PERMITTED_DATA_TYPE_NAMES: Final[set[str]] = CAST_VALUE_INT_DTYPES | CAST_VALUE_FLOAT_DTYPES +"""All dtype identifiers the `cast_value` codec is defined for.""" + + +def parse_scalar_map(obj: ScalarMapJSON | ScalarMap) -> ScalarMap: + """ + Parse a scalar map into its normalized dict-of-dicts form. + + Accepts either the JSON form (lists of tuples) or an already-normalized form + (dicts). For example, ``{"encode": [("NaN", 0)]}`` becomes + ``{"encode": {"NaN": 0}}``. + """ + result: ScalarMap = {} + for direction in ("encode", "decode"): + if direction in obj: + entries = obj[direction] + if entries is not None: + if isinstance(entries, Mapping): + result[direction] = entries + else: + result[direction] = dict(entries) # type: ignore[arg-type] + return result + + +# --------------------------------------------------------------------------- +# Backend: cast-value-rs +# --------------------------------------------------------------------------- + +# Versions below this silently transpose input arrays that are not row-major - +# the layout `transpose` hands to the next codec - writing corrupted data with +# no error. Keep in sync with the `cast-value-rs` extra in pyproject.toml. +CAST_VALUE_RS_MIN_VERSION: Final = "0.4.2" + +_INSTALL_HINT: Final = f"Install it with: pip install 'cast-value-rs>={CAST_VALUE_RS_MIN_VERSION}'" + + +def _check_backend_version() -> str | None: + """Return a message describing an unusable backend version, or `None` if it is usable.""" + try: + installed = version("cast-value-rs") + except PackageNotFoundError: + # Importable but without distribution metadata, e.g. a `maturin develop` + # build. There is no version to compare, so let it through. + return None + if Version(installed) < Version(CAST_VALUE_RS_MIN_VERSION): + return ( + f"The cast_value codec requires cast-value-rs >= {CAST_VALUE_RS_MIN_VERSION}, " + f"but version {installed} is installed. Earlier versions silently corrupt data " + f"when the input array is not row-major. {_INSTALL_HINT}" + ) + return None + + +# Set once at import; raised from `_do_cast`, so an unusable backend does not +# make `import zarr` fail for users who never touch this codec. +_BACKEND_ERROR: str | None +try: + from cast_value_rs import cast_array as cast_array_rs +except ModuleNotFoundError: + _BACKEND_ERROR = f"The cast_value codec requires the 'cast-value-rs' package. {_INSTALL_HINT}" +else: + _BACKEND_ERROR = _check_backend_version() + + +def _check_representable( + value: JSON, + zdtype: ZDType[TBaseDType, TBaseScalar], + label: str, +) -> None: + """Raise ``ValueError`` if *value* cannot be parsed by *zdtype*.""" + try: + zdtype.from_json_scalar(value, zarr_format=3) + except (TypeError, ValueError, OverflowError) as e: + raise ValueError( + f"{label} {value!r} is not representable in dtype {zdtype.to_native_dtype()}." + ) from e + + +# --------------------------------------------------------------------------- +# Codec +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class CastValue(ArrayArrayCodec): + """Cast-value array-to-array codec. + + Value-converts array elements to a new data type during encoding, + and back to the original data type during decoding. + + Requires the `cast-value-rs` package for the actual casting logic. + + Parameters + ---------- + data_type : str or ZDType + Target zarr v3 data type. Strings are looked up by spec name + (e.g. "uint8", "float32"); a `ZDType` instance is used as-is. + rounding : RoundingMode + How to round when exact representation is impossible. Default is + "nearest-even". + out_of_range : OutOfRangeMode or None + What to do when a value is outside the target's range. `None` means + error; "clamp" clips to range; "wrap" uses modular arithmetic + (only valid for integer types). Default is `None`. + scalar_map : ScalarMap, ScalarMapJSON, or None + Explicit mapping from input scalars to output scalars. Default is + `None`. + + Attributes + ---------- + dtype : ZDType + Resolved target data type (a `ZDType` instance, regardless of + whether the constructor received a string or a `ZDType`). + rounding : RoundingMode + The rounding mode, as supplied to the constructor. + out_of_range : OutOfRangeMode or None + The out-of-range behaviour, as supplied to the constructor. + scalar_map : ScalarMap or None + Parsed scalar map (always normalized to `ScalarMap` form). + + References + ---------- + + - The `cast_value` codec spec: https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/cast_value + """ + + is_fixed_size = True + + dtype: ZDType[TBaseDType, TBaseScalar] + rounding: RoundingMode + out_of_range: OutOfRangeMode | None + scalar_map: ScalarMap | None + + def __init__( + self, + *, + data_type: str | ZDType[TBaseDType, TBaseScalar], + rounding: RoundingMode = "nearest-even", + out_of_range: OutOfRangeMode | None = None, + scalar_map: ScalarMapJSON | ScalarMap | None = None, + ) -> None: + if isinstance(data_type, str): + zdtype = get_data_type_from_json(data_type, zarr_format=3) + else: + zdtype = data_type + if zdtype.to_json(zarr_format=3) not in PERMITTED_DATA_TYPE_NAMES: + raise ValueError( + f"Invalid target data type {data_type!r}. " + f"cast_value codec only supports integer and floating-point data types. " + f"Got {zdtype}." + ) + object.__setattr__(self, "dtype", zdtype) + object.__setattr__(self, "rounding", rounding) + object.__setattr__(self, "out_of_range", out_of_range) + if scalar_map is not None: + parsed = parse_scalar_map(scalar_map) + else: + parsed = None + object.__setattr__(self, "scalar_map", parsed) + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + _, configuration_parsed = parse_named_configuration( + data, "cast_value", require_configuration=True + ) + return cls(**configuration_parsed) # type: ignore[arg-type] + + def to_dict(self) -> dict[str, JSON]: + config: dict[str, JSON] = {"data_type": cast("JSON", self.dtype.to_json(zarr_format=3))} + if self.rounding != "nearest-even": + config["rounding"] = self.rounding + if self.out_of_range is not None: + config["out_of_range"] = self.out_of_range + if self.scalar_map is not None: + json_map: dict[str, list[tuple[object, object]]] = {} + for direction in ("encode", "decode"): + if direction in self.scalar_map: + json_map[direction] = [(k, v) for k, v in self.scalar_map[direction].items()] + config["scalar_map"] = cast("JSON", json_map) + return {"name": "cast_value", "configuration": config} + + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: + # `dtype` is the source (the array's dtype); `self.dtype` is the + # cast target. The spec requires both to be permitted, and rules + # like `out_of_range="wrap"` apply to the target. + source_name = dtype.to_json(zarr_format=3) + target_name = self.dtype.to_json(zarr_format=3) + for role, name in (("source", source_name), ("target", target_name)): + if name not in PERMITTED_DATA_TYPE_NAMES: + raise ValueError( + f"The cast_value codec only supports integer and floating-point data types. " + f"Got {role} dtype {name}." + ) + if self.out_of_range == "wrap" and target_name not in CAST_VALUE_INT_DTYPES: + raise ValueError( + f"out_of_range='wrap' is only valid for integer target types. " + f"Got target dtype {target_name}." + ) + + if self.scalar_map is not None: + self._validate_scalar_map(dtype, self.dtype) + + def _validate_scalar_map( + self, + source_zdtype: ZDType[TBaseDType, TBaseScalar], + target_zdtype: ZDType[TBaseDType, TBaseScalar], + ) -> None: + """Validate that scalar map entries are compatible with source/target dtypes.""" + assert self.scalar_map is not None + # For encode: keys are source values, values are target values. + # For decode: keys are target values, values are source values. + direction_dtypes: dict[ + str, tuple[ZDType[TBaseDType, TBaseScalar], ZDType[TBaseDType, TBaseScalar]] + ] = { + "encode": (source_zdtype, target_zdtype), + "decode": (target_zdtype, source_zdtype), + } + for direction, (key_zdtype, val_zdtype) in direction_dtypes.items(): + if direction not in self.scalar_map: + continue + sub_map = self.scalar_map[direction] # type: ignore[literal-required] + for k, v in sub_map.items(): + _check_representable(k, key_zdtype, f"scalar_map {direction} key") + _check_representable(v, val_zdtype, f"scalar_map {direction} value") + + def _do_cast( + self, + arr: np.ndarray, + *, + target_dtype: np.dtype, + scalar_map: Mapping[str | float | int, str | float | int] | None, + ) -> np.ndarray: + if _BACKEND_ERROR is not None: + raise ImportError(_BACKEND_ERROR) + scalar_map_entries: dict[float | int, float | int] | None = None + if scalar_map is not None: + src_dtype = arr.dtype + to_src = int if np.issubdtype(src_dtype, np.integer) else float + to_tgt = int if np.issubdtype(target_dtype, np.integer) else float + scalar_map_entries = {to_src(k): to_tgt(v) for k, v in scalar_map.items()} + return cast_array_rs( # type: ignore[no-any-return] + arr, + target_dtype=target_dtype, + rounding_mode=self.rounding, + out_of_range_mode=self.out_of_range, + scalar_map_entries=scalar_map_entries, + ) + + def _get_scalar_map( + self, direction: str + ) -> Mapping[str | float | int, str | float | int] | None: + """Extract the encode or decode mapping from scalar_map, or None.""" + if self.scalar_map is None: + return None + return self.scalar_map.get(direction) # type: ignore[return-value] + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + """ + Update the fill value of the output spec by applying casting procedure. + """ + target_zdtype = self.dtype + target_native = target_zdtype.to_native_dtype() + source_native = chunk_spec.dtype.to_native_dtype() + + fill = chunk_spec.fill_value + fill_arr = np.array([fill], dtype=source_native) + + new_fill_arr = self._do_cast( + fill_arr, target_dtype=target_native, scalar_map=self._get_scalar_map("encode") + ) + new_fill = target_native.type(new_fill_arr[0]) + + return replace(chunk_spec, dtype=target_zdtype, fill_value=new_fill) + + def _encode_sync( + self, + chunk_array: NDBuffer, + _chunk_spec: ArraySpec, + ) -> NDBuffer | None: + arr = chunk_array.as_ndarray_like() + target_native = self.dtype.to_native_dtype() + + result = self._do_cast( + np.asarray(arr), target_dtype=target_native, scalar_map=self._get_scalar_map("encode") + ) + return chunk_array.__class__.from_ndarray_like(result) + + async def _encode_single( + self, + chunk_data: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer | None: + return self._encode_sync(chunk_data, chunk_spec) + + def _decode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + arr = chunk_array.as_ndarray_like() + target_native = chunk_spec.dtype.to_native_dtype() + + result = self._do_cast( + np.asarray(arr), target_dtype=target_native, scalar_map=self._get_scalar_map("decode") + ) + return chunk_array.__class__.from_ndarray_like(result) + + async def _decode_single( + self, + chunk_data: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return self._decode_sync(chunk_data, chunk_spec) + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + dtype_name = chunk_spec.dtype.to_json(zarr_format=3) + if dtype_name not in PERMITTED_DATA_TYPE_NAMES: + raise ValueError( + "cast_value codec only supports fixed-size integer and floating-point data types. " + f"Got source dtype: {chunk_spec.dtype}." + ) + source_itemsize = chunk_spec.dtype.to_native_dtype().itemsize + target_itemsize = self.dtype.to_native_dtype().itemsize + if source_itemsize == 0 or target_itemsize == 0: + raise ValueError( + "cast_value codec requires fixed-size data types. " + f"Got source itemsize={source_itemsize}, target itemsize={target_itemsize}." + ) + num_elements = input_byte_length // source_itemsize + return num_elements * target_itemsize diff --git a/src/zarr/codecs/crc32c_.py b/src/zarr/codecs/crc32c_.py index ebe2ac8f7a..7d41e11637 100644 --- a/src/zarr/codecs/crc32c_.py +++ b/src/zarr/codecs/crc32c_.py @@ -1,11 +1,11 @@ from __future__ import annotations +from collections.abc import Buffer as ABCBuffer from dataclasses import dataclass from typing import TYPE_CHECKING, cast import google_crc32c import numpy as np -import typing_extensions from zarr.abc.codec import BytesBytesCodec from zarr.core.common import JSON, parse_named_configuration @@ -41,9 +41,7 @@ def _decode_sync( inner_bytes = data[:-4] # Need to do a manual cast until https://github.com/numpy/numpy/issues/26783 is resolved - computed_checksum = np.uint32( - google_crc32c.value(cast("typing_extensions.Buffer", inner_bytes)) - ).tobytes() + computed_checksum = np.uint32(google_crc32c.value(cast(ABCBuffer, inner_bytes))).tobytes() stored_checksum = bytes(crc32_bytes) if computed_checksum != stored_checksum: raise ValueError( @@ -65,9 +63,7 @@ def _encode_sync( ) -> Buffer | None: data = chunk_bytes.as_numpy_array() # Calculate the checksum and "cast" it to a numpy array - checksum = np.array( - [google_crc32c.value(cast("typing_extensions.Buffer", data))], dtype=np.uint32 - ) + checksum = np.array([google_crc32c.value(cast(ABCBuffer, data))], dtype=np.uint32) # Append the checksum (as bytes) to the data return chunk_spec.prototype.buffer.from_array_like(np.append(data, checksum.view("B"))) diff --git a/src/zarr/codecs/gzip.py b/src/zarr/codecs/gzip.py index b8591748f7..7d86a03ba8 100644 --- a/src/zarr/codecs/gzip.py +++ b/src/zarr/codecs/gzip.py @@ -10,6 +10,7 @@ from zarr.abc.codec import BytesBytesCodec from zarr.core.buffer.cpu import as_numpy_array_wrapper from zarr.core.common import JSON, parse_named_configuration +from zarr.core.json_parse import parse_field if TYPE_CHECKING: from typing import Self @@ -19,13 +20,12 @@ def parse_gzip_level(data: JSON) -> int: - if not isinstance(data, (int)): - raise TypeError(f"Expected int, got {type(data)}") - if data not in range(10): + parsed: int = parse_field(data, int, "level", error=TypeError) + if parsed not in range(10): raise ValueError( - f"Expected an integer from the inclusive range (0, 9). Got {data} instead." + f"Expected an integer from the inclusive range (0, 9). Got {parsed} instead." ) - return data + return parsed @dataclass(frozen=True) diff --git a/src/zarr/codecs/numcodecs/_codecs.py b/src/zarr/codecs/numcodecs/_codecs.py index 4a3d88a84f..f44c35964c 100644 --- a/src/zarr/codecs/numcodecs/_codecs.py +++ b/src/zarr/codecs/numcodecs/_codecs.py @@ -8,14 +8,16 @@ import zarr import zarr.codecs.numcodecs as numcodecs +store = zarr.storage.MemoryStore() array = zarr.create_array( - store="data_numcodecs.zarr", - shape=(1024, 1024), - chunks=(64, 64), - dtype="uint32", - filters=[numcodecs.Delta(dtype="uint32")], - compressors=[numcodecs.BZ2(level=5)], - overwrite=True) + store=store, + shape=(1024, 1024), + chunks=(64, 64), + dtype="uint32", + filters=[numcodecs.Delta(dtype="uint32")], + compressors=[numcodecs.BZ2(level=5)], + overwrite=True +) array[:] = np.arange(np.prod(array.shape), dtype=array.dtype).reshape(*array.shape) ``` @@ -32,7 +34,6 @@ from dataclasses import dataclass, replace from functools import cached_property from typing import TYPE_CHECKING, Any, Self -from warnings import warn import numpy as np @@ -41,13 +42,12 @@ from zarr.core.buffer.cpu import as_numpy_array_wrapper from zarr.core.common import JSON, parse_named_configuration, product from zarr.dtype import UInt8, ZDType, parse_dtype -from zarr.errors import ZarrUserWarning from zarr.registry import get_numcodec if TYPE_CHECKING: from zarr.abc.numcodec import Numcodec from zarr.core.array_spec import ArraySpec - from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer + from zarr.core.buffer import Buffer, NDBuffer CODEC_PREFIX = "numcodecs." @@ -102,12 +102,6 @@ def __init__(self, **codec_config: JSON) -> None: ) # pragma: no cover object.__setattr__(self, "codec_config", codec_config) - warn( - "Numcodecs codecs are not in the Zarr version 3 specification and " - "may not be supported by other zarr implementations.", - category=ZarrUserWarning, - stacklevel=2, - ) @cached_property def _codec(self) -> Numcodec: @@ -140,53 +134,67 @@ class _NumcodecsBytesBytesCodec(_NumcodecsCodec, BytesBytesCodec): def __init__(self, **codec_config: JSON) -> None: super().__init__(**codec_config) - async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: - return await asyncio.to_thread( - as_numpy_array_wrapper, - self._codec.decode, - chunk_data, - chunk_spec.prototype, - ) + def _decode_sync(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: + return as_numpy_array_wrapper(self._codec.decode, chunk_data, chunk_spec.prototype) - def _encode(self, chunk_data: Buffer, prototype: BufferPrototype) -> Buffer: + def _encode_sync(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: encoded = self._codec.encode(chunk_data.as_array_like()) if isinstance(encoded, np.ndarray): # Required for checksum codecs - return prototype.buffer.from_bytes(encoded.tobytes()) - return prototype.buffer.from_bytes(encoded) + return chunk_spec.prototype.buffer.from_bytes(encoded.tobytes()) + return chunk_spec.prototype.buffer.from_bytes(encoded) + + async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: + return await asyncio.to_thread(self._decode_sync, chunk_data, chunk_spec) async def _encode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: - return await asyncio.to_thread(self._encode, chunk_data, chunk_spec.prototype) + return await asyncio.to_thread(self._encode_sync, chunk_data, chunk_spec) class _NumcodecsArrayArrayCodec(_NumcodecsCodec, ArrayArrayCodec): def __init__(self, **codec_config: JSON) -> None: super().__init__(**codec_config) - async def _decode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + def _decode_sync(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: chunk_ndarray = chunk_data.as_ndarray_like() - out = await asyncio.to_thread(self._codec.decode, chunk_ndarray) + out = self._codec.decode(chunk_ndarray) return chunk_spec.prototype.nd_buffer.from_ndarray_like(out.reshape(chunk_spec.shape)) - async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: - chunk_ndarray = chunk_data.as_ndarray_like() - out = await asyncio.to_thread(self._codec.encode, chunk_ndarray) + def _encode_sync(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + # numcodecs codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) + chunk_ndarray = np.ascontiguousarray(chunk_data.as_ndarray_like()) + out = self._codec.encode(chunk_ndarray) return chunk_spec.prototype.nd_buffer.from_ndarray_like(out) + async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return await asyncio.to_thread(self._encode_sync, chunk_data, chunk_spec) + + async def _decode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return await asyncio.to_thread(self._decode_sync, chunk_data, chunk_spec) + class _NumcodecsArrayBytesCodec(_NumcodecsCodec, ArrayBytesCodec): def __init__(self, **codec_config: JSON) -> None: super().__init__(**codec_config) - async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + def _decode_sync(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> NDBuffer: chunk_bytes = chunk_data.to_bytes() - out = await asyncio.to_thread(self._codec.decode, chunk_bytes) + out = self._codec.decode(chunk_bytes) return chunk_spec.prototype.nd_buffer.from_ndarray_like(out.reshape(chunk_spec.shape)) - async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> Buffer: - chunk_ndarray = chunk_data.as_ndarray_like() - out = await asyncio.to_thread(self._codec.encode, chunk_ndarray) + def _encode_sync(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + # numcodecs codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) + chunk_ndarray = np.ascontiguousarray(chunk_data.as_ndarray_like()) + out = self._codec.encode(chunk_ndarray) return chunk_spec.prototype.buffer.from_bytes(out) + async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + return await asyncio.to_thread(self._encode_sync, chunk_data, chunk_spec) + + async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + return await asyncio.to_thread(self._decode_sync, chunk_data, chunk_spec) + # bytes-to-bytes codecs class Blosc(_NumcodecsBytesBytesCodec, codec_name="blosc"): diff --git a/src/zarr/codecs/scale_offset.py b/src/zarr/codecs/scale_offset.py new file mode 100644 index 0000000000..f2908da1b6 --- /dev/null +++ b/src/zarr/codecs/scale_offset.py @@ -0,0 +1,418 @@ +from __future__ import annotations + +from dataclasses import dataclass, replace +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt + +from zarr.abc.codec import ArrayArrayCodec +from zarr.core.common import JSON, parse_named_configuration + +if TYPE_CHECKING: + from typing import Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.metadata.v3 import ChunkGridMetadata + + +_WIDE_INT = np.dtype(np.int64) + + +def _encode_fits_natively(dtype: np.dtype[Any], offset: int, scale: int) -> bool: + """Static range proof: is ``(x - offset) * scale`` always in range for every ``x`` in dtype? + + Uses Python ints (unbounded) to avoid overflow in the proof itself. + """ + info = np.iinfo(dtype) + d_lo = int(info.min) - offset + d_hi = int(info.max) - offset + # Taking min/max of both products handles negative scale without a sign branch. + products = (d_lo * scale, d_hi * scale) + lo, hi = min(products), max(products) + return info.min <= lo and hi <= info.max + + +def _decode_fits_natively(dtype: np.dtype[Any], offset: int, scale: int) -> bool: + """Static range proof for decode: is ``x // scale + offset`` always in range?""" + info = np.iinfo(dtype) + # x // scale is bounded by the extremes of x / scale (integer division stays within that range) + if scale > 0: + q_lo, q_hi = int(info.min) // scale, int(info.max) // scale + else: + q_lo, q_hi = int(info.max) // scale, int(info.min) // scale + lo, hi = q_lo + offset, q_hi + offset + return info.min <= lo and hi <= info.max + + +def _check_int_range( + values: npt.NDArray[np.integer[Any]], target: np.dtype[np.integer[Any]] +) -> None: + """Raise if any value is outside the representable range of ``target``. + + Uses a single min/max pass instead of two ``np.any`` passes. + """ + info = np.iinfo(target) + lo, hi = values.min(), values.max() + if lo < info.min or hi > info.max: + raise ValueError( + f"scale_offset produced a value outside the range of dtype {target} " + f"[{info.min}, {info.max}]." + ) + + +def _check_exact_division( + arr: npt.NDArray[np.integer[Any]], scale: np.integer[Any], scale_repr: object +) -> None: + """Raise ValueError if ``arr`` has any element not exactly divisible by ``scale``.""" + if np.any(arr % scale): + raise ValueError( + f"scale_offset decode produced a non-zero remainder when dividing by " + f"scale={scale_repr!r}; result is not exactly representable in dtype {arr.dtype}." + ) + + +def _encode_int_native( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Compute ``(arr - offset) * scale`` directly in ``arr.dtype``. + + This is the fast path; it exists only as a separate function to make the contract with + ``_encode_fits_natively`` explicit: the caller must have already proved that no ``x`` in + ``arr.dtype``'s range can overflow, so we can skip widening and range-checking entirely. + Using it without that proof would silently wrap on overflow. + """ + return cast("npt.NDArray[np.integer[Any]]", (arr - offset) * scale) + + +def _encode_int_widened( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Overflow-checked integer encode for int8..int64 and uint8..uint32. + + Exists because numpy integer arithmetic silently wraps on overflow, which the spec + forbids. We widen to int64, perform the arithmetic there (int64 holds the product of any + two values from these dtypes), range-check against the target dtype, then cast back. + uint64 cannot use this path because its range exceeds int64 — see ``_encode_uint64``. + """ + wide_arr = arr.astype(_WIDE_INT, copy=False) + result = (wide_arr - _WIDE_INT.type(offset)) * _WIDE_INT.type(scale) + _check_int_range(result, arr.dtype) + return result.astype(arr.dtype, copy=False) + + +def _encode_float( + arr: npt.NDArray[np.floating[Any]], offset: np.floating[Any], scale: np.floating[Any] +) -> npt.NDArray[np.floating[Any]]: + """Encode float arrays in-dtype, guarding only against silent promotion. + + Float arithmetic doesn't need widening — float64 is already the widest supported dtype, + and ``inf``/``nan`` from overflow are representable IEEE 754 values, so no range check is + required by the spec. The one thing that can still go wrong is numpy promoting the + result to a wider float dtype (e.g. float32 * float64 scalar -> float64), which would + violate the spec's "arithmetic semantics of the input array's data type" clause. + """ + result = cast("npt.NDArray[np.floating[Any]]", (arr - offset) * scale) + if result.dtype != arr.dtype: + raise ValueError( + f"scale_offset changed dtype from {arr.dtype} to {result.dtype}. " + f"Arithmetic must preserve the data type." + ) + return result + + +def _check_py_int_range( + result: np.ndarray[tuple[Any, ...], np.dtype[Any]], + target: np.dtype[np.unsignedinteger[Any]], +) -> None: + """Range-check an ``object``-dtype ndarray holding Python ints against ``target``'s iinfo. + + Exists as a uint64-specific counterpart to ``_check_int_range``. That one compares numpy + integers against ``iinfo``; here the values are unbounded Python ints produced by + ``_encode_uint64`` / ``_decode_uint64``, so we rely on Python's arbitrary-precision + comparison to detect values outside the target dtype's range. + """ + info = np.iinfo(target) + # np.min/np.max on an object array returns a Python int (which compares correctly with iinfo). + # Works uniformly for 0-d arrays where .flat iteration is awkward. + lo = np.min(result) + hi = np.max(result) + if lo < int(info.min) or hi > int(info.max): + raise ValueError( + f"scale_offset produced a value outside the range of dtype {target} " + f"[{info.min}, {info.max}]." + ) + + +def _encode_uint64( + arr: npt.NDArray[np.unsignedinteger[Any]], offset: int, scale: int +) -> npt.NDArray[np.unsignedinteger[Any]]: + """Encode uint64 via Python-int arithmetic in an ``object``-dtype array. + + Exists because uint64's range [0, 2**64) exceeds int64, so the int64 widening used by + ``_encode_int_widened`` would itself overflow. Python ints are unbounded, so computing + via ``object`` dtype is correct by construction. The trade-off is speed: object-dtype + arithmetic is interpreted per element and is roughly 10x slower than ufunc paths. + """ + obj = arr.astype(object, copy=False) + # np.asarray restores ndarray-ness in the 0-d/scalar edge case. + result = np.asarray((obj - offset) * scale, dtype=object) + _check_py_int_range(result, arr.dtype) + return cast("npt.NDArray[np.unsignedinteger[Any]]", result.astype(arr.dtype, copy=False)) + + +def _decode_uint64( + arr: npt.NDArray[np.unsignedinteger[Any]], offset: int, scale: int +) -> npt.NDArray[np.unsignedinteger[Any]]: + """Decode uint64 via Python-int arithmetic. See ``_encode_uint64`` for why.""" + obj = arr.astype(object, copy=False) + result = np.asarray((obj // scale) + offset, dtype=object) + _check_py_int_range(result, arr.dtype) + return cast("npt.NDArray[np.unsignedinteger[Any]]", result.astype(arr.dtype, copy=False)) + + +def _decode_int_native( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Compute ``arr // scale + offset`` directly in ``arr.dtype``. + + Fast-path counterpart to ``_encode_int_native``; same contract. Caller must have proved + via ``_decode_fits_natively`` that the result can't overflow. Divisibility is checked + upstream in ``_decode`` before this is called, so ``//`` is exact here. + """ + return cast("npt.NDArray[np.integer[Any]]", (arr // scale) + offset) + + +def _decode_int_widened( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Overflow-checked integer decode for int8..int64 and uint8..uint32. + + Counterpart to ``_encode_int_widened``. Widens to int64 so the addition of ``offset`` + after division can't silently wrap, then range-checks against the target dtype. + """ + wide_arr = arr.astype(_WIDE_INT, copy=False) + result = (wide_arr // _WIDE_INT.type(scale)) + _WIDE_INT.type(offset) + _check_int_range(result, arr.dtype) + return result.astype(arr.dtype, copy=False) + + +def _decode_float( + arr: npt.NDArray[np.floating[Any]], offset: np.floating[Any], scale: np.floating[Any] +) -> npt.NDArray[np.floating[Any]]: + """Decode float arrays in-dtype, guarding only against silent promotion. + + Counterpart to ``_encode_float``; same reasoning. ``arr / scale`` is true division and + always well-defined for floats (including ``0/0 = nan`` and ``x/0 = ±inf``), so no range + or exactness check is needed. + """ + result = cast("npt.NDArray[np.floating[Any]]", (arr / scale) + offset) + if result.dtype != arr.dtype: + raise ValueError( + f"scale_offset changed dtype from {arr.dtype} to {result.dtype}. " + f"Arithmetic must preserve the data type." + ) + return result + + +def _encode( + arr: np.ndarray[tuple[Any, ...], np.dtype[Any]], + offset: np.generic, + scale: np.generic, +) -> np.ndarray[tuple[Any, ...], np.dtype[Any]]: + """Compute ``(arr - offset) * scale`` without silent overflow, returning ``arr.dtype``.""" + # uint64 is split out first because its full range (up to 2**64-1) doesn't fit in int64, + # so the widening strategy used for every other integer dtype would itself overflow. + if arr.dtype == np.uint64: + u_arr = cast("npt.NDArray[np.unsignedinteger[Any]]", arr) + return _encode_uint64(u_arr, int(offset), int(scale)) + if np.issubdtype(arr.dtype, np.integer): + i_arr = cast("npt.NDArray[np.integer[Any]]", arr) + i_offset = cast("np.integer[Any]", offset) + i_scale = cast("np.integer[Any]", scale) + # Fast path: if a static proof shows no ``x`` in the dtype's range can overflow, + # skip the int64 widening and run the arithmetic directly in the input dtype. + if _encode_fits_natively(arr.dtype, int(offset), int(scale)): + return _encode_int_native(i_arr, i_offset, i_scale) + return _encode_int_widened(i_arr, i_offset, i_scale) + # Float path: arithmetic stays in-dtype (no widening); only guard against numpy + # silently promoting a narrower float to a wider one via scalar type mismatch. + f_arr = cast("npt.NDArray[np.floating[Any]]", arr) + f_offset = cast("np.floating[Any]", offset) + f_scale = cast("np.floating[Any]", scale) + return _encode_float(f_arr, f_offset, f_scale) + + +def _decode( + arr: np.ndarray[tuple[Any, ...], np.dtype[Any]], + offset: np.generic, + scale: np.generic, + *, + scale_repr: object, +) -> np.ndarray[tuple[Any, ...], np.dtype[Any]]: + """Compute ``arr / scale + offset`` without silent overflow, returning ``arr.dtype``.""" + # uint64: same reasoning as _encode — its range exceeds int64, so the Python-int path is the + # only correct option. Exactness check runs first so non-divisible inputs fail before the + # slower object-dtype arithmetic. + if arr.dtype == np.uint64: + u_arr = cast("npt.NDArray[np.unsignedinteger[Any]]", arr) + _check_exact_division(u_arr, cast("np.integer[Any]", scale), scale_repr) + return _decode_uint64(u_arr, int(offset), int(scale)) + if np.issubdtype(arr.dtype, np.integer): + i_arr = cast("npt.NDArray[np.integer[Any]]", arr) + i_offset = cast("np.integer[Any]", offset) + i_scale = cast("np.integer[Any]", scale) + # The spec requires decode to use true division and error if the result isn't + # representable. For integers that means the remainder must be zero; if any element + # isn't exactly divisible we fail here rather than silently truncating via //. + _check_exact_division(i_arr, i_scale, scale_repr) + # Fast path mirrors _encode: static proof that ``x // scale + offset`` stays in dtype. + if _decode_fits_natively(arr.dtype, int(offset), int(scale)): + return _decode_int_native(i_arr, i_offset, i_scale) + return _decode_int_widened(i_arr, i_offset, i_scale) + # Float path: division is well-defined; only guard against dtype promotion. + f_arr = cast("npt.NDArray[np.floating[Any]]", arr) + f_offset = cast("np.floating[Any]", offset) + f_scale = cast("np.floating[Any]", scale) + return _decode_float(f_arr, f_offset, f_scale) + + +@dataclass(frozen=True) +class ScaleOffset(ArrayArrayCodec): + """Scale-offset array-to-array codec. + + Encodes values with `out = (in - offset) * scale` and decodes with + `out = (in / scale) + offset`, using the input array's data type semantics. + Intermediate or final values that are not representable in that dtype are reported + as errors (integer overflow, unsigned underflow, non-exact integer division). + + Parameters + ---------- + offset : int, float, or str + Value subtracted during encoding. Strings preserve the exact JSON + representation when round-tripping metadata. Default is 0. + scale : int, float, or str + Value multiplied during encoding (after offset subtraction). Strings + preserve the exact JSON representation when round-tripping metadata. + Default is 1. + + Attributes + ---------- + offset : int, float, or str + The offset value, as supplied to the constructor. + scale : int, float, or str + The scale value, as supplied to the constructor. + + References + ---------- + + - The `scale_offset` codec spec: https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/scale_offset + """ + + is_fixed_size = True + + offset: int | float | str + scale: int | float | str + + def __init__(self, *, offset: object = 0, scale: object = 1) -> None: + if not isinstance(offset, int | float | str): + raise TypeError(f"offset must be a number or string, got {type(offset).__name__}") + if not isinstance(scale, int | float | str): + raise TypeError(f"scale must be a number or string, got {type(scale).__name__}") + object.__setattr__(self, "offset", offset) + object.__setattr__(self, "scale", scale) + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + _, configuration_parsed = parse_named_configuration( + data, "scale_offset", require_configuration=False + ) + configuration_parsed = configuration_parsed or {} + return cls(**configuration_parsed) + + def to_dict(self) -> dict[str, JSON]: + if self.offset == 0 and self.scale == 1: + return {"name": "scale_offset"} + config: dict[str, JSON] = {} + if self.offset != 0: + config["offset"] = self.offset + if self.scale != 1: + config["scale"] = self.scale + return {"name": "scale_offset", "configuration": config} + + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: + native = dtype.to_native_dtype() + if not np.issubdtype(native, np.integer) and not np.issubdtype(native, np.floating): + raise ValueError( + f"scale_offset codec only supports integer and floating-point data types. " + f"Got {dtype}." + ) + parsed: dict[str, Any] = {} + for name, value in [("offset", self.offset), ("scale", self.scale)]: + try: + parsed[name] = dtype.from_json_scalar(value, zarr_format=3) + except (TypeError, ValueError, OverflowError) as e: + raise ValueError( + f"scale_offset {name} value {value!r} is not representable in dtype {native}." + ) from e + # ``scale`` may be given as a string, and no string is ever ``== 0``, so this has to + # compare the parsed scalar rather than the value as supplied. + if parsed["scale"] == 0: + raise ValueError("scale_offset scale must be non-zero.") + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + zdtype = chunk_spec.dtype + fill = np.asarray(zdtype.cast_scalar(chunk_spec.fill_value)) + offset = cast("np.generic", zdtype.from_json_scalar(self.offset, zarr_format=3)) + scale = cast("np.generic", zdtype.from_json_scalar(self.scale, zarr_format=3)) + new_fill = _encode(fill, offset, scale) + return replace(chunk_spec, fill_value=new_fill.reshape(()).item()) + + def _decode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + arr = cast("np.ndarray[tuple[Any, ...], np.dtype[Any]]", chunk_array.as_ndarray_like()) + zdtype = chunk_spec.dtype + offset = cast("np.generic", zdtype.from_json_scalar(self.offset, zarr_format=3)) + scale = cast("np.generic", zdtype.from_json_scalar(self.scale, zarr_format=3)) + result = _decode(arr, offset, scale, scale_repr=self.scale) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(result) + + async def _decode_single( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return self._decode_sync(chunk_array, chunk_spec) + + def _encode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer | None: + arr = cast("np.ndarray[tuple[Any, ...], np.dtype[Any]]", chunk_array.as_ndarray_like()) + zdtype = chunk_spec.dtype + offset = cast("np.generic", zdtype.from_json_scalar(self.offset, zarr_format=3)) + scale = cast("np.generic", zdtype.from_json_scalar(self.scale, zarr_format=3)) + result = _encode(arr, offset, scale) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(result) + + async def _encode_single( + self, + chunk_array: NDBuffer, + _chunk_spec: ArraySpec, + ) -> NDBuffer | None: + return self._encode_sync(chunk_array, _chunk_spec) + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index 85162c2f74..41780e45b4 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -1,11 +1,9 @@ from __future__ import annotations -from collections.abc import Iterable, Mapping, MutableMapping +from collections.abc import Iterable, Mapping, MutableMapping, Sequence from dataclasses import dataclass, replace -from enum import Enum from functools import lru_cache -from operator import itemgetter -from typing import TYPE_CHECKING, Any, NamedTuple, cast +from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, NamedTuple import numpy as np import numpy.typing as npt @@ -16,14 +14,18 @@ ArrayBytesCodecPartialEncodeMixin, Codec, CodecPipeline, + _codec_supports_sync, ) from zarr.abc.store import ( ByteGetter, ByteRequest, ByteSetter, RangeByteRequest, + Store, SuffixByteRequest, + _store_supports_sync_io, ) +from zarr.codecs._deprecated_enum import _coerce_enum_input, _DeprecatedStrEnumMeta from zarr.codecs.bytes import BytesCodec from zarr.codecs.crc32c_ import Crc32cCodec from zarr.core.array_spec import ArrayConfig, ArraySpec @@ -34,26 +36,43 @@ default_buffer_prototype, numpy_buffer_prototype, ) -from zarr.core.chunk_grids import ChunkGrid, RegularChunkGrid +from zarr.core.chunk_grids import ChunkGrid +from zarr.core.chunk_utils import ( + ChunkTransform, + decode_and_scatter_chunk, + encode_or_elide_chunk, + evolve_codecs, + merge_and_encode_chunk, +) from zarr.core.common import ( ShapeLike, - parse_enum, parse_named_configuration, parse_shapelike, product, ) +from zarr.core.config import config as zarr_config +from zarr.core.dtype.common import HasEndianness from zarr.core.dtype.npy.int import UInt64 +from zarr.core.dtype.npy.structured import Struct from zarr.core.indexing import ( BasicIndexer, + ChunkProjection, SelectorTuple, - _morton_order, - _morton_order_keys, - c_order_iter, + SliceDimIndexer, + _lexicographic_order, + colexicographic_order_coords, get_indexer, - morton_order_iter, + lexicographic_order_coords, + morton_order_coords, +) +from zarr.core.metadata.v3 import ( + ChunkGridMetadata, + RectilinearChunkGridMetadata, + RegularChunkGridMetadata, + parse_codecs, ) -from zarr.core.metadata.v3 import parse_codecs from zarr.registry import get_ndbuffer_class, get_pipeline_class +from zarr.storage._common import StorePath from zarr.storage._utils import _normalize_byte_range_index if TYPE_CHECKING: @@ -68,28 +87,79 @@ ShardMutableMapping = MutableMapping[tuple[int, ...], Buffer | None] -class ShardingCodecIndexLocation(Enum): +IndexLocation = Literal["start", "end"] +"""Position of the shard index within the encoded shard.""" + +INDEX_LOCATION: Final = ("start", "end") + + +class ShardingCodecIndexLocation(metaclass=_DeprecatedStrEnumMeta): """ - Enum for index location used by the sharding codec. + Deprecated. Pass a literal string (`"start"` or `"end"`) directly to + `ShardingCodec` instead. """ - start = "start" - end = "end" + _members: ClassVar[dict[str, str]] = {"start": "start", "end": "end"} + +SubchunkWriteOrder = Literal["morton", "unordered", "lexicographic", "colexicographic"] +SUBCHUNK_WRITE_ORDER: Final[tuple[str, str, str, str]] = ( + "morton", + "unordered", + "lexicographic", + "colexicographic", +) -def parse_index_location(data: object) -> ShardingCodecIndexLocation: - return parse_enum(data, ShardingCodecIndexLocation) + +def _is_identity_full_read(indexer: Any, shard_shape: tuple[int, ...]) -> bool: + """True when `indexer` selects every element of a `shard_shape` array in + natural order: one whole-dimension, step-1 `SliceDimIndexer` per dimension. + + Structural on purpose, not `isinstance(indexer, BasicIndexer)`: a full + `arr[:]` read reaches the shard as an `OrthogonalIndexer`, so a type gate + would silently disable the bulk fast path for the most common case. Any + gather (integer-array / boolean / coordinate selection), subset, strided, + or integer-scalar selection fails the per-dimension check — output shape + alone is not enough, because a reordering or duplicating selection can have + the same shape as the shard while requiring `chunk_selection` / + `out_selection` to be honored. + """ + dim_indexers = getattr(indexer, "dim_indexers", None) + if dim_indexers is None or len(dim_indexers) != len(shard_shape): + return False + return all( + isinstance(dim_indexer, SliceDimIndexer) + and dim_indexer.dim_len == dim_len + and dim_indexer.start == 0 + and dim_indexer.stop == dim_len + and dim_indexer.step == 1 + for dim_indexer, dim_len in zip(dim_indexers, shard_shape, strict=True) + ) + + +def _parse_index_location(data: object) -> IndexLocation: + if isinstance(data, str) and data in INDEX_LOCATION: + return data # type: ignore[return-value] + raise ValueError(f"index_location must be one of {list(INDEX_LOCATION)!r}. Got {data!r}.") @dataclass(frozen=True) class _ShardingByteGetter(ByteGetter): + """In-memory byte getter for one inner chunk of a shard. + + Implements `SyncByteGetter` (dict access needs no event loop), so the + synchronous codec pipeline takes its sync fast path on inner chunks + instead of scheduling one coroutine per chunk; the async `get` simply + delegates to `get_sync`. + """ + shard_dict: ShardMapping chunk_coords: tuple[int, ...] - async def get( - self, prototype: BufferPrototype, byte_range: ByteRequest | None = None + def get_sync( + self, prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None ) -> Buffer | None: - assert prototype == default_buffer_prototype(), ( + assert prototype is None or prototype == default_buffer_prototype(), ( f"prototype is not supported within shards currently. diff: {prototype} != {default_buffer_prototype()}" ) value = self.shard_dict.get(self.chunk_coords) @@ -100,36 +170,48 @@ async def get( start, stop = _normalize_byte_range_index(value, byte_range) return value[start:stop] + async def get( + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + return self.get_sync(prototype, byte_range) + @dataclass(frozen=True) class _ShardingByteSetter(_ShardingByteGetter, ByteSetter): + """In-memory byte setter for one inner chunk of a shard. + + Implements `SyncByteSetter`; the async methods delegate to the sync ones. + """ + shard_dict: ShardMutableMapping + def set_sync(self, value: Buffer) -> None: + self.shard_dict[self.chunk_coords] = value + + def delete_sync(self) -> None: + del self.shard_dict[self.chunk_coords] + async def set(self, value: Buffer, byte_range: ByteRequest | None = None) -> None: assert byte_range is None, "byte_range is not supported within shards" - self.shard_dict[self.chunk_coords] = value + self.set_sync(value) async def delete(self) -> None: - del self.shard_dict[self.chunk_coords] + self.delete_sync() async def set_if_not_exists(self, default: Buffer) -> None: self.shard_dict.setdefault(self.chunk_coords, default) class _ShardIndex(NamedTuple): + # the chunk grid shape of a single shard + chunks_per_shard: tuple[int, ...] # dtype uint64, shape (chunks_per_shard_0, chunks_per_shard_1, ..., 2) offsets_and_lengths: npt.NDArray[np.uint64] - @property - def chunks_per_shard(self) -> tuple[int, ...]: - result = tuple(self.offsets_and_lengths.shape[0:-1]) - # The cast is required until https://github.com/numpy/numpy/pull/27211 is merged - return cast("tuple[int, ...]", result) - def _localize_chunk(self, chunk_coords: tuple[int, ...]) -> tuple[int, ...]: return tuple( chunk_i % shard_i - for chunk_i, shard_i in zip(chunk_coords, self.offsets_and_lengths.shape, strict=False) + for chunk_i, shard_i in zip(chunk_coords, self.chunks_per_shard, strict=False) ) def is_all_empty(self) -> bool: @@ -138,6 +220,31 @@ def is_all_empty(self) -> bool: def get_full_chunk_map(self) -> npt.NDArray[np.bool_]: return np.not_equal(self.offsets_and_lengths[..., 0], MAX_UINT_64) + def is_dense(self, chunk_byte_length: int, *, data_section_start: int) -> bool: + """True when the chunk payloads exactly tile the shard's data section. + + Every chunk must be present with length `chunk_byte_length`, and the + sorted offsets must be exactly `data_section_start + i * chunk_byte_length` + for `i` in `0..n_chunks-1`: no gaps, no overlaps, and nothing outside the + data section (a corrupt index could otherwise point chunks into the + index region or out of the blob). Used to gate the vectorized + whole-shard decode: a dense fixed-size shard is a regular grid of + equal-length payloads, so it can be reshaped/scattered in bulk rather + than decoded chunk-by-chunk. + """ + offsets = self.offsets_and_lengths[..., 0].reshape(-1) + lengths = self.offsets_and_lengths[..., 1].reshape(-1) + # all present + if bool(np.any(offsets == MAX_UINT_64)): + return False + # all the same fixed length + if not bool(np.all(lengths == chunk_byte_length)): + return False + expected = np.uint64(data_section_start) + np.arange( + offsets.size, dtype=np.uint64 + ) * np.uint64(chunk_byte_length) + return bool(np.array_equal(np.sort(offsets), expected)) + def get_chunk_slice(self, chunk_coords: tuple[int, ...]) -> tuple[int, int] | None: localized_chunk = self._localize_chunk(chunk_coords) chunk_start, chunk_len = self.offsets_and_lengths[localized_chunk] @@ -165,15 +272,24 @@ def get_chunk_slices_vectorized( valid : ndarray of shape (n_chunks,) Boolean mask indicating which chunks are non-empty. """ - # Localize coordinates via modulo (vectorized) - shard_shape = np.array(self.offsets_and_lengths.shape[:-1], dtype=np.uint64) - localized = chunk_coords_array.astype(np.uint64) % shard_shape + # Handle 0-dimensional arrays (n_dims == 0): the shard holds a single + # chunk, so every coordinate maps to the same flat entry. + if chunk_coords_array.shape[1] == 0: + offsets_and_lengths = self.offsets_and_lengths.reshape(-1, 2) + offsets_and_lengths = np.broadcast_to( + offsets_and_lengths, (chunk_coords_array.shape[0], 2) + ) + else: + # Localize coordinates via modulo (vectorized) + shard_shape = np.array(self.chunks_per_shard, dtype=np.uint64) + localized = chunk_coords_array.astype(np.uint64) % shard_shape + + # Build index tuple for advanced indexing + index_tuple = tuple(localized[:, i] for i in range(localized.shape[1])) - # Build index tuple for advanced indexing - index_tuple = tuple(localized[:, i] for i in range(localized.shape[1])) + # Fetch all offsets and lengths at once + offsets_and_lengths = self.offsets_and_lengths[index_tuple] - # Fetch all offsets and lengths at once - offsets_and_lengths = self.offsets_and_lengths[index_tuple] starts = offsets_and_lengths[:, 0] lengths = offsets_and_lengths[:, 1] @@ -195,32 +311,11 @@ def set_chunk_slice(self, chunk_coords: tuple[int, ...], chunk_slice: slice | No chunk_slice.stop - chunk_slice.start, ) - def is_dense(self, chunk_byte_length: int) -> bool: - sorted_offsets_and_lengths = sorted( - [ - (offset, length) - for offset, length in self.offsets_and_lengths - if offset != MAX_UINT_64 - ], - key=itemgetter(0), - ) - - # Are all non-empty offsets unique? - if len( - {offset for offset, _ in sorted_offsets_and_lengths if offset != MAX_UINT_64} - ) != len(sorted_offsets_and_lengths): - return False - - return all( - offset % chunk_byte_length == 0 and length == chunk_byte_length - for offset, length in sorted_offsets_and_lengths - ) - @classmethod def create_empty(cls, chunks_per_shard: tuple[int, ...]) -> _ShardIndex: offsets_and_lengths = np.zeros(chunks_per_shard + (2,), dtype=" int: return int(self.index.offsets_and_lengths.size / 2) def __iter__(self) -> Iterator[tuple[int, ...]]: - return c_order_iter(self.index.offsets_and_lengths.shape[:-1]) + return iter(lexicographic_order_coords(self.index.chunks_per_shard)) - def to_dict_vectorized( - self, - chunk_coords_array: npt.NDArray[np.integer[Any]], - ) -> dict[tuple[int, ...], Buffer | None]: + def to_dict_vectorized(self) -> dict[tuple[int, ...], Buffer | None]: """Build a dict of chunk coordinates to buffers using vectorized lookup. - Parameters - ---------- - chunk_coords_array : ndarray of shape (n_chunks, n_dims) - Array of chunk coordinates for vectorized index lookup. + The full per-shard chunk coordinate grid (both the array used for the + vectorized index lookup and the plain tuples used as dict keys) is + cached on `chunks_per_shard`, so neither is rebuilt on every call. For a + shard with tens of thousands of chunks this avoids reconstructing that + many tuples on every partial write. Returns ------- dict mapping chunk coordinate tuples to Buffer or None """ + chunks_per_shard = self.index.chunks_per_shard + # The same chunk-grid coordinates are needed in two forms, and neither can + # stand in for the other: + # - `chunk_coords_array`: an (n_chunks, n_dims) numpy array, fed to the + # vectorized index lookup, which does modulo + advanced indexing on it. + # A list of tuples can't be used for that without first being arrayified. + # - `chunk_coords_keys`: the same coordinates as hashable Python tuples, + # used as the result dict's keys. numpy array rows are unhashable + # (mutable), so they can't key a dict. + # Both are cached per shape (see indexing.py), so neither is rebuilt here; + # row i of the array and key i refer to the same chunk. + chunk_coords_array = _lexicographic_order(chunks_per_shard) + chunk_coords_keys = lexicographic_order_coords(chunks_per_shard) starts, ends, valid = self.index.get_chunk_slices_vectorized(chunk_coords_array) - chunks_per_shard = tuple(self.index.offsets_and_lengths.shape[:-1]) - chunk_coords_keys = _morton_order_keys(chunks_per_shard) result: dict[tuple[int, ...], Buffer | None] = {} for i, coords in enumerate(chunk_coords_keys): @@ -299,12 +403,20 @@ def to_dict_vectorized( class ShardingCodec( ArrayBytesCodec, ArrayBytesCodecPartialDecodeMixin, ArrayBytesCodecPartialEncodeMixin ): - """Sharding codec""" + """Sharding codec. + + `subchunk_write_order` controls the physical order of subchunks within a shard. It is a + write-time setting only: it is not stored in array metadata, so reopening a sharded array + does not recover it (the setting reverts to the `morton` default per codec instance). + """ + + is_fixed_size = False chunk_shape: tuple[int, ...] codecs: tuple[Codec, ...] index_codecs: tuple[Codec, ...] - index_location: ShardingCodecIndexLocation = ShardingCodecIndexLocation.end + index_location: IndexLocation = "end" + subchunk_write_order: SubchunkWriteOrder = "morton" def __init__( self, @@ -312,42 +424,64 @@ def __init__( chunk_shape: ShapeLike, codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(),), index_codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(), Crc32cCodec()), - index_location: ShardingCodecIndexLocation | str = ShardingCodecIndexLocation.end, + index_location: ShardingCodecIndexLocation | IndexLocation = "end", + subchunk_write_order: SubchunkWriteOrder = "morton", ) -> None: chunk_shape_parsed = parse_shapelike(chunk_shape) codecs_parsed = parse_codecs(codecs) index_codecs_parsed = parse_codecs(index_codecs) - index_location_parsed = parse_index_location(index_location) + index_location_coerced = _coerce_enum_input( + index_location, "index_location", "ShardingCodec" + ) + index_location_parsed = _parse_index_location(index_location_coerced) + if subchunk_write_order not in SUBCHUNK_WRITE_ORDER: + raise ValueError( + f"Unrecognized subchunk write order: {subchunk_write_order}. Only {SUBCHUNK_WRITE_ORDER} are allowed." + ) object.__setattr__(self, "chunk_shape", chunk_shape_parsed) object.__setattr__(self, "codecs", codecs_parsed) object.__setattr__(self, "index_codecs", index_codecs_parsed) object.__setattr__(self, "index_location", index_location_parsed) + object.__setattr__(self, "subchunk_write_order", subchunk_write_order) # Use instance-local lru_cache to avoid memory leaks - - # numpy void scalars are not hashable, which means an array spec with a fill value that is - # a numpy void scalar will break the lru_cache. This is commented for now but should be - # fixed. See https://github.com/zarr-developers/zarr-python/issues/3054 - # object.__setattr__(self, "_get_chunk_spec", lru_cache()(self._get_chunk_spec)) + object.__setattr__(self, "_get_chunk_spec", lru_cache()(self._get_chunk_spec)) object.__setattr__(self, "_get_index_chunk_spec", lru_cache()(self._get_index_chunk_spec)) object.__setattr__(self, "_get_chunks_per_shard", lru_cache()(self._get_chunks_per_shard)) + object.__setattr__(self, "_shard_index_size", lru_cache()(self._shard_index_size)) + object.__setattr__( + self, "_get_inner_chunk_transform", lru_cache()(self._get_inner_chunk_transform) + ) + object.__setattr__( + self, "_get_index_chunk_transform", lru_cache()(self._get_index_chunk_transform) + ) # todo: typedict return type def __getstate__(self) -> dict[str, Any]: - return self.to_dict() + # `subchunk_write_order` is not part of codec metadata (`to_dict`), so carry it + # explicitly to survive a pickle round-trip (otherwise it reverts to `morton`). + return {"subchunk_write_order": self.subchunk_write_order, **self.to_dict()} def __setstate__(self, state: dict[str, Any]) -> None: config = state["configuration"] object.__setattr__(self, "chunk_shape", parse_shapelike(config["chunk_shape"])) object.__setattr__(self, "codecs", parse_codecs(config["codecs"])) object.__setattr__(self, "index_codecs", parse_codecs(config["index_codecs"])) - object.__setattr__(self, "index_location", parse_index_location(config["index_location"])) + object.__setattr__(self, "index_location", _parse_index_location(config["index_location"])) + object.__setattr__(self, "subchunk_write_order", state["subchunk_write_order"]) # Use instance-local lru_cache to avoid memory leaks - # object.__setattr__(self, "_get_chunk_spec", lru_cache()(self._get_chunk_spec)) + object.__setattr__(self, "_get_chunk_spec", lru_cache()(self._get_chunk_spec)) object.__setattr__(self, "_get_index_chunk_spec", lru_cache()(self._get_index_chunk_spec)) object.__setattr__(self, "_get_chunks_per_shard", lru_cache()(self._get_chunks_per_shard)) + object.__setattr__(self, "_shard_index_size", lru_cache()(self._shard_index_size)) + object.__setattr__( + self, "_get_inner_chunk_transform", lru_cache()(self._get_inner_chunk_transform) + ) + object.__setattr__( + self, "_get_index_chunk_transform", lru_cache()(self._get_index_chunk_transform) + ) @classmethod def from_dict(cls, data: dict[str, JSON]) -> Self: @@ -358,6 +492,41 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: def codec_pipeline(self) -> CodecPipeline: return get_pipeline_class().from_codecs(self.codecs) + def _get_inner_pipeline(self, shard_spec: ArraySpec) -> CodecPipeline: + """The nested pipeline for inner-chunk IO, evolved against the inner + chunk spec. + + Evolving matters for two reasons: it threads the spec through the inner + codec chain (spec-changing codecs see the spec they will actually + operate on), and — for a synchronous pipeline — it builds the sync + transform, so inner-chunk IO over the (sync-capable) sharding byte + getters takes the pipeline's sync fast path instead of scheduling one + coroutine per inner chunk. The bare `codec_pipeline` property returns an + unevolved pipeline, which a synchronous pipeline can only run through + its async fallback. + + Memoized per (pipeline class, batch size, shard_spec): evolving builds + a ChunkTransform, which is wasteful to redo on every shard operation. + The pipeline class and batch size participate in the key so the + `codec_pipeline.path` and `codec_pipeline.batch_size` configs are still + honored after the first use (`from_codecs` captures batch_size at + construction). A benign construction race between threads is possible + (last writer wins) — same as the other caches here. + """ + cache: dict[tuple[type[CodecPipeline], int, ArraySpec], CodecPipeline] | None = getattr( + self, "_inner_pipeline_cache", None + ) + if cache is None: + cache = {} + object.__setattr__(self, "_inner_pipeline_cache", cache) + key = (get_pipeline_class(), zarr_config.get("codec_pipeline.batch_size"), shard_spec) + pipeline = cache.get(key) + if pipeline is None: + chunk_spec = self._get_chunk_spec(shard_spec) + pipeline = self.codec_pipeline.evolve_from_array_spec(chunk_spec) + cache[key] = pipeline + return pipeline + def to_dict(self) -> dict[str, JSON]: return { "name": "sharding_indexed", @@ -365,13 +534,32 @@ def to_dict(self) -> dict[str, JSON]: "chunk_shape": self.chunk_shape, "codecs": tuple(s.to_dict() for s in self.codecs), "index_codecs": tuple(s.to_dict() for s in self.index_codecs), - "index_location": self.index_location.value, + "index_location": self.index_location, }, } def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: + """Thread the spec through the inner chain. + + Each codec is evolved against the spec produced by the previous one. + Evolving every codec against the same unthreaded spec is the bug shape that + strips `BytesCodec.endian` behind a dtype-changing codec — and this + method runs on the real array-creation path, baking the damaged chain + into the evolved instance before the transform builders ever run. + + Parameters + ---------- + array_spec + The base spec to be evolved as we thread it. + + Returns + ------- + This codec with the evolved code chain. + """ + from zarr.core.chunk_utils import evolve_codecs + shard_spec = self._get_chunk_spec(array_spec) - evolved_codecs = tuple(c.evolve_from_array_spec(array_spec=shard_spec) for c in self.codecs) + evolved_codecs = evolve_codecs(self.codecs, shard_spec) if evolved_codecs != self.codecs: return replace(self, codecs=evolved_codecs) return self @@ -381,26 +569,407 @@ def validate( *, shape: tuple[int, ...], dtype: ZDType[TBaseDType, TBaseScalar], - chunk_grid: ChunkGrid, + chunk_grid: ChunkGridMetadata, ) -> None: if len(self.chunk_shape) != len(shape): raise ValueError( "The shard's `chunk_shape` and array's `shape` need to have the same number of dimensions." ) - if not isinstance(chunk_grid, RegularChunkGrid): - raise TypeError("Sharding is only compatible with regular chunk grids.") - if not all( - s % c == 0 - for s, c in zip( - chunk_grid.chunk_shape, - self.chunk_shape, - strict=False, + if isinstance(chunk_grid, RegularChunkGridMetadata): + edges_per_dim: tuple[tuple[int, ...], ...] = tuple((s,) for s in chunk_grid.chunk_shape) + elif isinstance(chunk_grid, RectilinearChunkGridMetadata): + edges_per_dim = tuple( + (s,) if isinstance(s, int) else s for s in chunk_grid.chunk_shapes ) - ): - raise ValueError( - f"The array's `chunk_shape` (got {chunk_grid.chunk_shape}) " - f"needs to be divisible by the shard's inner `chunk_shape` (got {self.chunk_shape})." + else: + raise TypeError( + f"Sharding is only compatible with regular and rectilinear chunk grids, " + f"got {type(chunk_grid)}" + ) + for i, (edges, inner) in enumerate(zip(edges_per_dim, self.chunk_shape, strict=False)): + for edge in set(edges): + if edge % inner != 0: + raise ValueError( + f"Chunk edge length {edge} in dimension {i} is not " + f"divisible by the shard's inner chunk size {inner}." + ) + + def _get_inner_chunk_transform(self, shard_spec: ArraySpec) -> Any: + """The synchronous transform for the inner codec chain. + + Memoized by the instance-local `lru_cache` wrapping installed in + `__init__`/`__setstate__` (the single cache mechanism for these + builders — do not add another layer inside the body). + + Codecs are evolved with the spec THREADED forward (`evolve_codecs`): + each inner codec is evolved against the spec produced by the previous + one, not the original chunk spec. Evolving every codec against the same + unthreaded spec is the bug shape that stripped `BytesCodec.endian` at + the pipeline level (see `evolve_codecs`) — the inner chain must use the + same single source of truth. + """ + + chunk_spec = self._get_chunk_spec(shard_spec) + return ChunkTransform(codecs=evolve_codecs(self.codecs, chunk_spec)) + + def _get_index_chunk_transform(self, chunks_per_shard: tuple[int, ...]) -> Any: + """The synchronous transform for the index codec chain. + + Memoized via instance-local `lru_cache`. + """ + + index_spec = self._get_index_chunk_spec(chunks_per_shard) + return ChunkTransform(codecs=evolve_codecs(self.index_codecs, index_spec)) + + def _decode_shard_index_sync( + self, index_bytes: Buffer, chunks_per_shard: tuple[int, ...] + ) -> _ShardIndex: + """Decode shard index synchronously using ChunkTransform.""" + index_transform = self._get_index_chunk_transform(chunks_per_shard) + index_spec = self._get_index_chunk_spec(chunks_per_shard) + index_array = index_transform.decode_chunk(index_bytes, index_spec) + return _ShardIndex(chunks_per_shard, index_array.as_numpy_array()) + + def _encode_shard_index_sync(self, index: _ShardIndex) -> Buffer: + """Encode shard index synchronously using ChunkTransform.""" + index_transform = self._get_index_chunk_transform(index.chunks_per_shard) + index_spec = self._get_index_chunk_spec(index.chunks_per_shard) + index_nd = get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths) + result: Buffer | None = index_transform.encode_chunk(index_nd, index_spec) + assert result is not None + return result + + def _shard_reader_from_bytes_sync( + self, buf: Buffer, chunks_per_shard: tuple[int, ...] + ) -> _ShardReader: + """Sync version of _ShardReader.from_bytes.""" + shard_index_size = self._shard_index_size(chunks_per_shard) + if self.index_location == "start": + shard_index_bytes = buf[:shard_index_size] + else: + shard_index_bytes = buf[-shard_index_size:] + index = self._decode_shard_index_sync(shard_index_bytes, chunks_per_shard) + reader = _ShardReader() + reader.buf = buf + reader.index = index + return reader + + def _decode_sync( + self, + shard_bytes: Buffer, + shard_spec: ArraySpec, + ) -> NDBuffer: + """Decode a full shard synchronously. + + Sync counterpart to `_decode_single`. Same semantics (decode every + inner chunk and assemble the full shard array) but routes through + `ChunkTransform` instead of the async codec pipeline, so it can + run on the sync codec-pipeline fast path without an event loop. + + For a partial read where the caller only needs a slice of the shard, + use `_decode_partial_sync` instead — it fetches only the byte + ranges that overlap the selection. + + This method does not parallelize decompression, but should. + See TODO: make issue for handling subchunk parallelism + """ + shard_shape = shard_spec.shape + chunk_shape = self.chunk_shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = BasicIndexer( + tuple(slice(0, s) for s in shard_shape), + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), + ) + + out = chunk_spec.prototype.nd_buffer.empty( + shape=shard_shape, + dtype=shard_spec.dtype.to_native_dtype(), + order=shard_spec.order, + ) + + shard_dict = self._shard_reader_from_bytes_sync(shard_bytes, chunks_per_shard) + + if shard_dict.index.is_all_empty(): + out.fill(shard_spec.fill_value) + return out + + for chunk_coords, chunk_selection, out_selection, _ in indexer: + # the GetResult status is discarded: missing INNER chunks of a + # present shard always fill (read_missing_chunks is a store-key + # level promise, applied to top-level statuses at the array layer) + decode_and_scatter_chunk( + shard_dict.get(chunk_coords), + out, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + drop_axes=(), + decode=inner_transform.decode_chunk, + ) + + return out + + def _encode_sync( + self, + shard_array: NDBuffer, + shard_spec: ArraySpec, + ) -> Buffer | None: + """Encode a full shard synchronously. + + Sync counterpart to `_encode_single`. This is reached when a + `ShardingCodec` is an *inner* codec of another sharding codec (nested + sharding): the outer codec encodes each inner chunk through its + `ChunkTransform`, which calls this method on the inner `ShardingCodec`. + + Each inner chunk is encoded through the inner `ChunkTransform` and + collected into an intermediate `dict`. The dict's key order is + immaterial — the physical on-disk layout is decided downstream by the + `subchunk_write_order` loop in `_encode_shard_dict_sync` (this method + does NOT impose a layout). Empty inner chunks become `None` entries when + `write_empty_chunks` is False, signalling `_encode_shard_dict_sync` to + elide them from the data section and mark them empty in the shard index. + + Returns `None` if every inner chunk was elided (an all-empty shard) — + callers treat that as "delete the shard key". + + This method does not parallelize compression, but should. + See TODO: make issue for handling subchunk parallelism + + For a partial write that only touches some inner chunks, use + `_encode_partial_sync` instead. + """ + shard_shape = shard_spec.shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = BasicIndexer( + tuple(slice(0, s) for s in shard_shape), + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, self.chunk_shape), + ) + + # Key order here is immaterial; _encode_shard_dict_sync lays the present + # chunks out in subchunk_write_order. + shard_builder: dict[tuple[int, ...], Buffer | None] = dict.fromkeys( + lexicographic_order_coords(chunks_per_shard) + ) + + for chunk_coords, _chunk_selection, out_selection, _ in indexer: + # None = chunk normalized to missing (see encode_or_elide_chunk) + shard_builder[chunk_coords] = encode_or_elide_chunk( + shard_array[out_selection], chunk_spec, inner_transform.encode_chunk + ) + + return self._encode_shard_dict_sync( + shard_builder, + chunks_per_shard=chunks_per_shard, + buffer_prototype=default_buffer_prototype(), + ) + + def _encode_partial_sync( + self, + byte_setter: Any, + value: NDBuffer, + selection: SelectorTuple, + shard_spec: ArraySpec, + ) -> None: + """Sync equivalent of `_encode_partial_single`. + + Receives the source data for the written region (not a pre-merged + shard array) and the selection within the shard, matching the + calling convention of the async partial-encode path used by + `BatchedCodecPipeline`. + + This method does not parallelize compression, but should. + See TODO: make issue for handling subchunk parallelism + + Loads the existing shard, merges the written region into the affected + inner chunks, and rewrites the whole shard. + """ + shard_shape = shard_spec.shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = list( + get_indexer( + selection, + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, self.chunk_shape), + ) + ) + + is_complete = self._is_complete_shard_write(indexer, chunks_per_shard) + + is_scalar = len(value.shape) == 0 + + # Load existing inner-chunk bytes into a dict (same structure as + # the async path's shard_dict). + if is_complete: + shard_dict: dict[tuple[int, ...], Buffer | None] = dict.fromkeys( + lexicographic_order_coords(chunks_per_shard) + ) + else: + existing_bytes = byte_setter.get_sync(prototype=shard_spec.prototype) + if existing_bytes is not None: + shard_reader_fb = self._shard_reader_from_bytes_sync( + existing_bytes, chunks_per_shard + ) + # Build the dict with one vectorized index lookup over all chunks, + # matching the async _encode_partial_single path. A per-coordinate + # __getitem__ loop here is O(n_chunks) Python overhead that dominates + # partial writes into shards with many inner chunks. The coordinate + # array and keys are cached on the reader, so neither is rebuilt here. + shard_dict = shard_reader_fb.to_dict_vectorized() + else: + shard_dict = dict.fromkeys(lexicographic_order_coords(chunks_per_shard)) + + # Merge, encode, and store each affected inner chunk into shard_dict via + # the canonical merge_and_encode_chunk (None = normalized to missing). + # + # Scalar fast path: when the written value is a scalar broadcast, every + # *complete* inner chunk is byte-for-byte identical — same fill, same + # empty-check, same encoded bytes. Compute that outcome once and reuse it + # for all complete chunks instead of re-merging, re-checking, and + # re-encoding tens of thousands of identical chunks. Incomplete (edge) + # chunks still merge against their own existing data individually. + # `_sentinel` distinguishes "not computed yet" from a memoized `None` + # (an empty chunk). + _sentinel = object() + scalar_complete_result: Buffer | object | None = _sentinel + + for chunk_coords, chunk_sel, out_sel, is_complete_chunk in indexer: + if is_scalar and is_complete_chunk: + if scalar_complete_result is _sentinel: + scalar_complete_result = merge_and_encode_chunk( + None, + value, + chunk_spec=chunk_spec, + chunk_selection=chunk_sel, + out_selection=out_sel, + is_complete=is_complete_chunk, + drop_axes=(), + decode=inner_transform.decode_chunk, + encode=inner_transform.encode_chunk, + ) + shard_dict[chunk_coords] = scalar_complete_result # type: ignore[assignment] + continue + + # A complete chunk fully overwrites: skip decoding what it replaces. + existing_raw = None if is_complete_chunk else shard_dict.get(chunk_coords) + shard_dict[chunk_coords] = merge_and_encode_chunk( + existing_raw, + value, + chunk_spec=chunk_spec, + chunk_selection=chunk_sel, + out_selection=out_sel, + is_complete=is_complete_chunk, + drop_axes=(), + decode=inner_transform.decode_chunk, + encode=inner_transform.encode_chunk, + ) + + blob = self._encode_shard_dict_sync( + shard_dict, + chunks_per_shard=chunks_per_shard, + buffer_prototype=default_buffer_prototype(), + ) + if blob is None: + byte_setter.delete_sync() + else: + byte_setter.set_sync(blob) + + def _build_shard_layout( + self, + shard_dict: ShardMapping, + chunks_per_shard: tuple[int, ...], + ) -> tuple[_ShardIndex, list[Buffer]] | None: + """Lay out the present inner chunks of a shard. Pure compute, no IO. + + Packs the encoded inner chunks (in the codec's `subchunk_write_order`) + into a contiguous data section and builds a shard index pointing each + present chunk at its ABSOLUTE byte offset within the final blob: when + the index is stored at the start, offsets are pre-shifted by the index + size (known without encoding — the index codecs are fixed-size, which + every index read path already relies on), so the index can be encoded + exactly once by the caller. + + Returns `(index, data_buffers)`, or `None` for an all-empty shard (no + chunks present). Shared by the sync and async `_encode_shard_dict*` so + the layout/offset logic cannot drift between them. + """ + index = _ShardIndex.create_empty(chunks_per_shard) + buffers: list[Buffer] = [] + chunk_start = ( + self._shard_index_size(chunks_per_shard) if self.index_location == "start" else 0 + ) + + for chunk_coords in self._subchunk_order_iter(chunks_per_shard, self.subchunk_write_order): + value = shard_dict.get(chunk_coords) + if value is None or len(value) == 0: + continue + chunk_length = len(value) + buffers.append(value) + index.set_chunk_slice(chunk_coords, slice(chunk_start, chunk_start + chunk_length)) + chunk_start += chunk_length + + if len(buffers) == 0: + return None + return index, buffers + + def _assemble_shard( + self, + index_bytes: Buffer, + buffers: list[Buffer], + buffer_prototype: BufferPrototype, + *, + chunks_per_shard: tuple[int, ...], + ) -> Buffer: + """Concatenate the encoded index and data buffers into the shard blob. + + The layout from `_build_shard_layout` already assumes the index size, so + the encoded index length must match `_shard_index_size` exactly — guard + that assumption rather than silently corrupt offsets. The guard lives + here, once, for both the sync and async encode paths. + """ + if len(index_bytes) != self._shard_index_size(chunks_per_shard): + raise RuntimeError( + "encoded shard index size does not match _shard_index_size; " + "variable-size index codecs are not supported" ) + if self.index_location == "start": + buffers.insert(0, index_bytes) + else: + buffers.append(index_bytes) + template = buffer_prototype.buffer.create_zero_length() + return template.combine(buffers) + + def _encode_shard_dict_sync( + self, + shard_dict: ShardMapping, + chunks_per_shard: tuple[int, ...], + buffer_prototype: BufferPrototype, + ) -> Buffer | None: + """Sync version of _encode_shard_dict. + + Layout via the shared `_build_shard_layout` (offsets already absolute), + then a single index encode and concatenation. + + Returns `None` for an all-empty shard (no chunks present). + """ + layout = self._build_shard_layout(shard_dict, chunks_per_shard) + if layout is None: + return None + index, buffers = layout + index_bytes = self._encode_shard_index_sync(index) + return self._assemble_shard( + index_bytes, buffers, buffer_prototype, chunks_per_shard=chunks_per_shard + ) async def _decode_single( self, @@ -415,7 +984,7 @@ async def _decode_single( indexer = BasicIndexer( tuple(slice(0, s) for s in shard_shape), shape=shard_shape, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) # setup output array @@ -431,7 +1000,7 @@ async def _decode_single( return out # decoding chunks and writing them into the output buffer - await self.codec_pipeline.read( + await self._get_inner_pipeline(shard_spec).read( [ ( _ShardingByteGetter(shard_dict, chunk_coords), @@ -461,7 +1030,7 @@ async def _decode_partial_single( indexer = get_indexer( selection, shape=shard_shape, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) # setup output array @@ -475,7 +1044,7 @@ async def _decode_partial_single( all_chunk_coords = {chunk_coords for chunk_coords, *_ in indexed_chunks} # reading bytes of all requested chunks - shard_dict: ShardMapping = {} + shard_dict_maybe: ShardMapping | None if self._is_total_shard(all_chunk_coords, chunks_per_shard): # read entire shard shard_dict_maybe = await self._load_full_shard_maybe( @@ -483,27 +1052,23 @@ async def _decode_partial_single( prototype=chunk_spec.prototype, chunks_per_shard=chunks_per_shard, ) - if shard_dict_maybe is None: - return None - shard_dict = shard_dict_maybe else: # read some chunks within the shard - shard_index = await self._load_shard_index_maybe(byte_getter, chunks_per_shard) - if shard_index is None: - return None - shard_dict = {} - for chunk_coords in all_chunk_coords: - chunk_byte_slice = shard_index.get_chunk_slice(chunk_coords) - if chunk_byte_slice: - chunk_bytes = await byte_getter.get( - prototype=chunk_spec.prototype, - byte_range=RangeByteRequest(chunk_byte_slice[0], chunk_byte_slice[1]), - ) - if chunk_bytes: - shard_dict[chunk_coords] = chunk_bytes + shard_dict_maybe = await self._load_partial_shard_maybe( + byte_getter, + chunk_spec.prototype, + chunks_per_shard, + all_chunk_coords, + max_gap_bytes=shard_spec.config.sharding_coalesce_max_gap_bytes, + max_coalesced_bytes=shard_spec.config.sharding_coalesce_max_bytes, + ) + + if shard_dict_maybe is None: + return None + shard_dict = shard_dict_maybe # decoding chunks and writing them into the output buffer - await self.codec_pipeline.read( + await self._get_inner_pipeline(shard_spec).read( [ ( _ShardingByteGetter(shard_dict, chunk_coords), @@ -522,6 +1087,227 @@ async def _decode_partial_single( else: return out + def _subchunk_order_iter( + self, chunks_per_shard: tuple[int, ...], subchunk_write_order: SubchunkWriteOrder + ) -> Iterable[tuple[int, ...]]: + subchunk_iter: Iterable[tuple[int, ...]] + match subchunk_write_order: + case "morton": + subchunk_iter = morton_order_coords(chunks_per_shard) + case "lexicographic": + subchunk_iter = lexicographic_order_coords(chunks_per_shard) + case "colexicographic": + subchunk_iter = colexicographic_order_coords(chunks_per_shard) + case "unordered": + # "unordered" promises no particular layout; today it happens to be + # lexicographic, but callers must not rely on that. + subchunk_iter = np.ndindex(chunks_per_shard) + case _: + raise ValueError(f"Unrecognized subchunk write order: {subchunk_write_order!r}.") + return subchunk_iter + + def _decode_full_shard_bulk_if_uncompressed( + self, + shard_bytes: Buffer, + shard_spec: ArraySpec, + indexer: Any, + ) -> NDBuffer | None: + """Vectorized whole-shard decode for dense, fixed-size, uncompressed shards. + + Returns the assembled shard array, or None if the fast path does not + apply (so the caller falls back to the per-chunk loop). Conditions: + - inner codec chain is fixed-size (no compression / variable-length); + - the inner codec chain is exactly a single BytesCodec — decode is a + dtype/endian view with no reordering. A trailing crc32c is NOT accepted + (the bulk path can't verify per-chunk checksums, so crc shards keep the + per-chunk path's corruption detection); + - the data type is not structured (the byte-order handling below has no + `Struct` branch); + - `indexer` is an identity full-shard read (`_is_identity_full_read`); + - the stored index is dense (every chunk present, equal fixed length, + exactly tiling the data section) so the data section is a regular + grid of chunk payloads. + + Chunk positions are read from the stored index, so this is correct for + any `subchunk_write_order` (morton / lexicographic / colexicographic / + unordered). The on-disk byte order is taken from the BytesCodec's + `endian`, so big- and little-endian shards both decode correctly. + """ + # --- gate on a trivial, fixed-size inner codec chain --- + if not self._inner_codecs_fixed_size: + return None + # The inner chain must be exactly a single BytesCodec (a dtype/endian + # view, no reordering). A trailing Crc32cCodec is excluded on purpose: + # the bulk path would have to strip-and-discard the per-chunk checksum + # bytes, silently dropping the corruption detection the per-chunk path + # enforces (Crc32cCodec._decode_sync raises on mismatch). crc-protected + # shards therefore fall through to the per-chunk path. + if len(self.codecs) != 1 or not isinstance(self.codecs[0], BytesCodec): + return None + ab_codec = self.codecs[0] + + # The byte-order handling below lacks the structured-dtype branch of + # `BytesCodec._decode_sync` (which applies `newbyteorder` to multi-byte + # struct fields), so structured dtypes must take the per-chunk path. + if isinstance(shard_spec.dtype, Struct): + return None + + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + n_chunks = product(chunks_per_shard) + if n_chunks == 0: + return None + + # Only valid for an identity full-shard read, where each chunk lands at + # its natural grid position. The per-dimension check is load-bearing: + # a gather selection (an `OrthogonalIndexer` with an integer-array or + # boolean dimension, from `arr[perm, :]` / `arr.oindex[...]`, or a + # `CoordinateIndexer` from vindex) can have an output `.shape` equal to + # the shard shape while reordering or duplicating points — serving it + # from the bulk path would return the shard in natural order, silently + # dropping the reordering. Anything that is not a full-slice-per- + # dimension read falls through to the per-chunk path so + # chunk_selection / out_selection are honored. + if not _is_identity_full_read(indexer, shard_spec.shape): + return None + chunk_byte_length = self._inner_chunk_byte_length(chunk_spec) + + shard_index_size = self._shard_index_size(chunks_per_shard) + if len(shard_bytes) != n_chunks * chunk_byte_length + shard_index_size: + return None # not a dense fixed-size shard + + # --- decode the index; require dense layout --- + if self.index_location == "start": + index_bytes = shard_bytes[:shard_index_size] + else: + index_bytes = shard_bytes[-shard_index_size:] + index = self._decode_shard_index_sync(index_bytes, chunks_per_shard) + data_section_start = shard_index_size if self.index_location == "start" else 0 + if not index.is_dense(chunk_byte_length, data_section_start=data_section_start): + return None + + # --- bulk reconstruct --- + # The index gives each chunk's absolute byte offset within the blob; with + # a dense, crc-free, fixed-size layout the payload length is exactly the + # encoded item-bytes of one chunk. + native_dtype = shard_spec.dtype.to_native_dtype() + raw = shard_bytes.as_numpy_array().view(np.uint8) + payload = chunk_byte_length + cs = self.chunk_shape + + # On-disk byte order is carried by the BytesCodec's `endian`, NOT by the + # data type (zarr v3). Build the read-view dtype from the codec's endian + # exactly as BytesCodec._decode_sync does, so a big-endian shard read on a + # little-endian host (or vice versa) is interpreted correctly. Assigning + # into the native-dtype `out` then performs any needed byteswap. `endian` + # is now a plain Literal['little', 'big'] | None string (no longer an enum). + endian_str = ab_codec.endian + if isinstance(chunk_spec.dtype, HasEndianness): + stored_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] + else: + stored_dtype = chunk_spec.dtype.to_native_dtype() + + offsets = index.offsets_and_lengths[..., 0].reshape(-1) # localized coords, C-order + coords_c = list(np.ndindex(chunks_per_shard)) + out = shard_spec.prototype.nd_buffer.empty( + shape=indexer.shape, dtype=native_dtype, order=shard_spec.order + ) + for flat, coord in enumerate(coords_c): + start = int(offsets[flat]) + chunk = raw[start : start + payload].view(stored_dtype).reshape(cs) + sel = tuple(slice(c * s, c * s + s) for c, s in zip(coord, cs, strict=True)) + out[sel] = chunk + return out + + def _decode_partial_sync( + self, + byte_getter: Any, + selection: SelectorTuple, + shard_spec: ArraySpec, + ) -> NDBuffer | None: + """Sync equivalent of `_decode_partial_single`. + + Reads only the inner-chunk byte ranges that overlap `selection` + (plus the shard index) and decodes them through the inner codec + chain. The store must support `get_sync` with byte ranges. + + This method does not parallelize decompression, but should. + See TODO: make issue for handling subchunk parallelism + + Two sub-paths: + - If `selection` covers the entire shard, just fetch the whole + blob — that's strictly cheaper than two round trips (index, then + data) plus the per-chunk overhead of partial fetches. + - Otherwise fetch the index alone, look up only the byte slices of + the inner chunks the selection touches, fetch those, and decode. + """ + shard_shape = shard_spec.shape + chunk_shape = self.chunk_shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = get_indexer( + selection, + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), + ) + + out = shard_spec.prototype.nd_buffer.empty( + shape=indexer.shape, + dtype=shard_spec.dtype.to_native_dtype(), + order=shard_spec.order, + ) + + indexed_chunks = list(indexer) + all_chunk_coords = {chunk_coords for chunk_coords, *_ in indexed_chunks} + + # Read just the inner chunks we need. + if self._is_total_shard(all_chunk_coords, chunks_per_shard): + shard_bytes = byte_getter.get_sync(prototype=chunk_spec.prototype) + if shard_bytes is None: + return None + bulk = self._decode_full_shard_bulk_if_uncompressed(shard_bytes, shard_spec, indexer) + if bulk is not None: + # The bulk path only fires for an identity full-shard read + # (`_is_identity_full_read`), so the result is already + # shard-shaped and in natural order — no reshape needed. + return bulk + shard_reader = self._shard_reader_from_bytes_sync(shard_bytes, chunks_per_shard) + shard_dict: ShardMapping = shard_reader + else: + # Partial read: fetch only the touched inner chunks, coalescing + # adjacent byte ranges (mirrors the async _load_partial_shard_maybe + # / #3004). Returns None if the shard is absent. + partial = self._load_partial_shard_maybe_sync( + byte_getter, + chunk_spec.prototype, + chunks_per_shard, + all_chunk_coords, + max_gap_bytes=shard_spec.config.sharding_coalesce_max_gap_bytes, + max_coalesced_bytes=shard_spec.config.sharding_coalesce_max_bytes, + ) + if partial is None: + return None + shard_dict = partial + + # Decode each needed inner chunk and scatter into out (statuses + # discarded: missing inner chunks fill, see _decode_sync). + for chunk_coords, chunk_selection, out_selection, _ in indexed_chunks: + decode_and_scatter_chunk( + shard_dict.get(chunk_coords), + out, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + drop_axes=(), + decode=inner_transform.decode_chunk, + ) + + if hasattr(indexer, "sel_shape"): + return out.reshape(indexer.sel_shape) + return out + async def _encode_single( self, shard_array: NDBuffer, @@ -536,13 +1322,12 @@ async def _encode_single( BasicIndexer( tuple(slice(0, s) for s in shard_shape), shape=shard_shape, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) ) + shard_builder = dict.fromkeys(lexicographic_order_coords(chunks_per_shard)) - shard_builder = dict.fromkeys(morton_order_iter(chunks_per_shard)) - - await self.codec_pipeline.write( + await self._get_inner_pipeline(shard_spec).write( [ ( _ShardingByteSetter(shard_builder, chunk_coords), @@ -574,22 +1359,29 @@ async def _encode_partial_single( chunks_per_shard = self._get_chunks_per_shard(shard_spec) chunk_spec = self._get_chunk_spec(shard_spec) - shard_reader = await self._load_full_shard_maybe( - byte_getter=byte_setter, - prototype=chunk_spec.prototype, - chunks_per_shard=chunks_per_shard, - ) - shard_reader = shard_reader or _ShardReader.create_empty(chunks_per_shard) - # Use vectorized lookup for better performance - shard_dict = shard_reader.to_dict_vectorized(np.asarray(_morton_order(chunks_per_shard))) - indexer = list( get_indexer( - selection, shape=shard_shape, chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape) + selection, + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) ) - await self.codec_pipeline.write( + if self._is_complete_shard_write(indexer, chunks_per_shard): + shard_dict = dict.fromkeys(lexicographic_order_coords(chunks_per_shard)) + else: + shard_reader = await self._load_full_shard_maybe( + byte_getter=byte_setter, + prototype=chunk_spec.prototype, + chunks_per_shard=chunks_per_shard, + ) + shard_reader = shard_reader or _ShardReader.create_empty(chunks_per_shard) + # Use vectorized lookup for better performance. The lexicographic + # coordinate array and keys are cached, so neither is rebuilt on + # every write. + shard_dict = shard_reader.to_dict_vectorized() + + await self._get_inner_pipeline(shard_spec).write( [ ( _ShardingByteSetter(shard_dict, chunk_coords), @@ -619,65 +1411,90 @@ async def _encode_shard_dict( chunks_per_shard: tuple[int, ...], buffer_prototype: BufferPrototype, ) -> Buffer | None: - index = _ShardIndex.create_empty(chunks_per_shard) - - buffers = [] - - template = buffer_prototype.buffer.create_zero_length() - chunk_start = 0 - for chunk_coords in morton_order_iter(chunks_per_shard): - value = map.get(chunk_coords) - if value is None: - continue - - if len(value) == 0: - continue - - chunk_length = len(value) - buffers.append(value) - index.set_chunk_slice(chunk_coords, slice(chunk_start, chunk_start + chunk_length)) - chunk_start += chunk_length - - if len(buffers) == 0: + """Layout via the shared `_build_shard_layout` (offsets already + absolute), then a single index encode and concatenation. Async twin of + `_encode_shard_dict_sync`.""" + layout = self._build_shard_layout(map, chunks_per_shard) + if layout is None: return None - + index, buffers = layout index_bytes = await self._encode_shard_index(index) - if self.index_location == ShardingCodecIndexLocation.start: - empty_chunks_mask = index.offsets_and_lengths[..., 0] == MAX_UINT_64 - index.offsets_and_lengths[~empty_chunks_mask, 0] += len(index_bytes) - index_bytes = await self._encode_shard_index( - index - ) # encode again with corrected offsets - buffers.insert(0, index_bytes) - else: - buffers.append(index_bytes) - - return template.combine(buffers) + return self._assemble_shard( + index_bytes, buffers, buffer_prototype, chunks_per_shard=chunks_per_shard + ) def _is_total_shard( self, all_chunk_coords: set[tuple[int, ...]], chunks_per_shard: tuple[int, ...] ) -> bool: - return len(all_chunk_coords) == product(chunks_per_shard) and all( - chunk_coords in all_chunk_coords for chunk_coords in c_order_iter(chunks_per_shard) + # `all_chunk_coords` comes from an indexer over this shard's chunk grid, so + # it is always a subset of that grid (`validate` requires the shard shape to + # be divisible by the inner chunk shape, so the indexer cannot produce an + # out-of-grid coordinate). A subset whose size equals the grid's is the + # whole grid, so the count check alone proves totality — no need to build + # and membership-test the full coordinate set on this hot path. + return len(all_chunk_coords) == product(chunks_per_shard) + + def _is_complete_shard_write( + self, + indexed_chunks: Sequence[ChunkProjection], + chunks_per_shard: tuple[int, ...], + ) -> bool: + all_chunk_coords = {chunk_coords for chunk_coords, *_ in indexed_chunks} + return self._is_total_shard(all_chunk_coords, chunks_per_shard) and all( + is_complete_chunk for *_, is_complete_chunk in indexed_chunks ) + @property + def _sync_capable(self) -> bool: + """Dynamic opt-out consulted by `_codec_supports_sync` / `ChunkTransform`. + + This codec structurally satisfies `SupportsSyncCodec`, but every sync + method (`_decode_sync`, `_encode_sync`, `_decode_partial_sync`, + `_encode_partial_sync`) delegates to the inner and index codec chains + through `ChunkTransform`, so it can only run synchronously when every + codec in BOTH chains is itself sync-capable. Reporting False here makes + `ChunkTransform` construction raise, which in turn makes + `FusedCodecPipeline.evolve_from_array_spec` set `sync_transform=None` — + the whole pipeline then declines the sync fast path and routes through + the async paths (partial shard decode / async fallback write), exactly + as it does for an async-only TOP-level codec or a non-sync store. + """ + return self._inner_codecs_sync_capable() and self._index_codecs_sync_capable() + + def _inner_codecs_sync_capable(self) -> bool: + # _codec_supports_sync (not bare isinstance) so a nested sharding codec + # with an async-only inner chain propagates its opt-out outward. + return all(_codec_supports_sync(c) for c in self.codecs) + + def _index_codecs_sync_capable(self) -> bool: + return all(_codec_supports_sync(c) for c in self.index_codecs) + async def _decode_shard_index( self, index_bytes: Buffer, chunks_per_shard: tuple[int, ...] ) -> _ShardIndex: + # Pure compute (the bytes are already in hand): delegate to the sync + # implementation instead of spinning up a pipeline + per-call + # AsyncChunkTransform for a tiny fixed-size decode. The default + # (bytes + crc32c) index chain is sync-capable; an async-only + # third-party index codec falls back to the full async pipeline, which + # the synchronous read paths cannot use but this async path still can. + if self._index_codecs_sync_capable(): + return self._decode_shard_index_sync(index_bytes, chunks_per_shard) index_array = next( iter( await get_pipeline_class() .from_codecs(self.index_codecs) - .decode( - [(index_bytes, self._get_index_chunk_spec(chunks_per_shard))], - ) + .decode([(index_bytes, self._get_index_chunk_spec(chunks_per_shard))]) ) ) - # This cannot be None because we have the bytes already - index_array = cast(NDBuffer, index_array) - return _ShardIndex(index_array.as_numpy_array()) + assert index_array is not None # the bytes are already in hand + return _ShardIndex(chunks_per_shard, index_array.as_numpy_array()) async def _encode_shard_index(self, index: _ShardIndex) -> Buffer: + # Pure compute: delegate to the sync implementation, with the same + # async-pipeline fallback as _decode_shard_index. + if self._index_codecs_sync_capable(): + return self._encode_shard_index_sync(index) index_bytes = next( iter( await get_pipeline_class() @@ -688,12 +1505,11 @@ async def _encode_shard_index(self, index: _ShardIndex) -> Buffer: get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths), self._get_index_chunk_spec(index.chunks_per_shard), ) - ], + ] ) ) ) assert index_bytes is not None - assert isinstance(index_bytes, Buffer) return index_bytes def _shard_index_size(self, chunks_per_shard: tuple[int, ...]) -> int: @@ -735,30 +1551,48 @@ def _get_chunks_per_shard(self, shard_spec: ArraySpec) -> tuple[int, ...]: ) ) + def _shard_index_byte_range( + self, chunks_per_shard: tuple[int, ...] + ) -> RangeByteRequest | SuffixByteRequest: + """Byte range of the shard index within the shard blob. + + Single source of truth for the index-location arithmetic, shared by the + sync and async index loaders so they cannot drift. + """ + shard_index_size = self._shard_index_size(chunks_per_shard) + if self.index_location == "start": + return RangeByteRequest(0, shard_index_size) + return SuffixByteRequest(shard_index_size) + + @staticmethod + def _pair_chunks_with_byte_ranges( + shard_index: _ShardIndex, all_chunk_coords: set[tuple[int, ...]] + ) -> list[tuple[tuple[int, ...], RangeByteRequest]]: + """Pair each requested chunk coord with its byte range in the shard. + + Coords whose chunk is absent from the index are omitted. Shared by the + sync and async partial-shard loaders. + """ + chunk_coord_byte_ranges: list[tuple[tuple[int, ...], RangeByteRequest]] = [] + for chunk_coord in all_chunk_coords: + chunk_byte_slice = shard_index.get_chunk_slice(chunk_coord) + if chunk_byte_slice is not None: + chunk_coord_byte_ranges.append( + (chunk_coord, RangeByteRequest(chunk_byte_slice[0], chunk_byte_slice[1])) + ) + return chunk_coord_byte_ranges + async def _load_shard_index_maybe( self, byte_getter: ByteGetter, chunks_per_shard: tuple[int, ...] ) -> _ShardIndex | None: - shard_index_size = self._shard_index_size(chunks_per_shard) - if self.index_location == ShardingCodecIndexLocation.start: - index_bytes = await byte_getter.get( - prototype=numpy_buffer_prototype(), - byte_range=RangeByteRequest(0, shard_index_size), - ) - else: - index_bytes = await byte_getter.get( - prototype=numpy_buffer_prototype(), byte_range=SuffixByteRequest(shard_index_size) - ) + index_bytes = await byte_getter.get( + prototype=numpy_buffer_prototype(), + byte_range=self._shard_index_byte_range(chunks_per_shard), + ) if index_bytes is not None: return await self._decode_shard_index(index_bytes, chunks_per_shard) return None - async def _load_shard_index( - self, byte_getter: ByteGetter, chunks_per_shard: tuple[int, ...] - ) -> _ShardIndex: - return ( - await self._load_shard_index_maybe(byte_getter, chunks_per_shard) - ) or _ShardIndex.create_empty(chunks_per_shard) - async def _load_full_shard_maybe( self, byte_getter: ByteGetter, prototype: BufferPrototype, chunks_per_shard: tuple[int, ...] ) -> _ShardReader | None: @@ -770,6 +1604,153 @@ async def _load_full_shard_maybe( else None ) + @property + def _inner_codecs_fixed_size(self) -> bool: + """True when all inner codecs produce fixed-size output (no compression).""" + return all(c.is_fixed_size for c in self.codecs) + + def _inner_chunk_byte_length(self, chunk_spec: ArraySpec) -> int: + """Encoded byte length of a single inner chunk. Only valid when _inner_codecs_fixed_size.""" + raw_byte_length = 1 + for s in self.chunk_shape: + raw_byte_length *= s + raw_byte_length *= chunk_spec.dtype.item_size # type: ignore[attr-defined] + return int(self.codec_pipeline.compute_encoded_size(raw_byte_length, chunk_spec)) + + async def _load_partial_shard_maybe( + self, + byte_getter: ByteGetter, + prototype: BufferPrototype, + chunks_per_shard: tuple[int, ...], + all_chunk_coords: set[tuple[int, ...]], + max_gap_bytes: int, + max_coalesced_bytes: int, + ) -> ShardMapping | None: + """ + Read chunks from `byte_getter` for the case where the read is less than a full shard. + Returns a mapping of chunk coordinates to bytes or None. + + `max_gap_bytes` and `max_coalesced_bytes` are forwarded to + `Store.get_ranges` to control byte-range coalescing across the requested + chunks. + """ + shard_index = await self._load_shard_index_maybe(byte_getter, chunks_per_shard) + if shard_index is None: + return None + + chunk_coord_byte_ranges = self._pair_chunks_with_byte_ranges(shard_index, all_chunk_coords) + + if not chunk_coord_byte_ranges: + return {} + + shard_dict: ShardMutableMapping = {} + if isinstance(byte_getter, StorePath): + # External store: use Store.get_ranges for coalescing + concurrency. + byte_ranges = [byte_range for _, byte_range in chunk_coord_byte_ranges] + try: + async for group in byte_getter.store.get_ranges( + byte_getter.path, + byte_ranges, + prototype=prototype, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + for idx, buf in group: + if buf is not None: + chunk_coord, _ = chunk_coord_byte_ranges[idx] + shard_dict[chunk_coord] = buf + except BaseExceptionGroup as eg: + # `Store.get_ranges` raises FileNotFoundError (wrapped in a + # BaseExceptionGroup) if any underlying fetch indicates the key is + # absent. The shard index loaded above, so this typically means a + # race where the shard was deleted mid-read; treat it as "shard + # gone" to match the index-missing branch (return None). Anything + # else in the group (e.g. IO errors) is re-raised. + _, rest = eg.split(FileNotFoundError) + if rest is not None: + raise rest from None + return None + else: + # Any other ByteGetter. In practice only `_ShardingByteGetter` for + # nested sharding, which slices an in-memory buffer (no I/O to coalesce). + for chunk_coord, byte_range in chunk_coord_byte_ranges: + buf = await byte_getter.get(prototype, byte_range) + if buf is not None: + shard_dict[chunk_coord] = buf + + return shard_dict + + def _load_shard_index_maybe_sync( + self, byte_getter: Any, chunks_per_shard: tuple[int, ...] + ) -> _ShardIndex | None: + """Sync counterpart of `_load_shard_index_maybe`.""" + index_bytes = byte_getter.get_sync( + prototype=numpy_buffer_prototype(), + byte_range=self._shard_index_byte_range(chunks_per_shard), + ) + if index_bytes is not None: + return self._decode_shard_index_sync(index_bytes, chunks_per_shard) + return None + + def _load_partial_shard_maybe_sync( + self, + byte_getter: Any, + prototype: BufferPrototype, + chunks_per_shard: tuple[int, ...], + all_chunk_coords: set[tuple[int, ...]], + *, + max_gap_bytes: int, + max_coalesced_bytes: int, + ) -> ShardMapping | None: + """Sync counterpart of `_load_partial_shard_maybe` (the #3004 read path). + + Reads the shard index, then fetches only the touched inner chunks via the + store's coalescing `get_ranges_sync` (merging adjacent ranges into fewer + reads), matching the async path's IO shape without an event loop. + `max_gap_bytes` and `max_coalesced_bytes` control the coalescing, forwarded + from the array's `sharding_coalesce_*` config exactly as the async path. + """ + shard_index = self._load_shard_index_maybe_sync(byte_getter, chunks_per_shard) + if shard_index is None: + return None + + chunk_coord_byte_ranges = self._pair_chunks_with_byte_ranges(shard_index, all_chunk_coords) + + if not chunk_coord_byte_ranges: + return {} + + shard_dict: ShardMutableMapping = {} + store = byte_getter.store if hasattr(byte_getter, "store") else None + if isinstance(store, Store) and _store_supports_sync_io(store): + # External store: coalesce via get_ranges_sync (mirrors get_ranges). + byte_ranges = [byte_range for _, byte_range in chunk_coord_byte_ranges] + try: + for idx, buf in store.get_ranges_sync( + byte_getter.path, + byte_ranges, + prototype=prototype, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + if buf is not None: + chunk_coord, _ = chunk_coord_byte_ranges[idx] + shard_dict[chunk_coord] = buf + except BaseExceptionGroup as eg: + # Mirror the async path: a FileNotFoundError means the shard was + # deleted mid-read -> treat as "gone" (None). Re-raise anything else. + _, rest = eg.split(FileNotFoundError) + if rest is not None: + raise rest from None + return None + else: + # Nested sharding: an in-memory _ShardingByteGetter, no IO to coalesce. + for chunk_coord, byte_range in chunk_coord_byte_ranges: + buf = byte_getter.get_sync(prototype=prototype, byte_range=byte_range) + if buf is not None: + shard_dict[chunk_coord] = buf + + return shard_dict + def compute_encoded_size(self, input_byte_length: int, shard_spec: ArraySpec) -> int: chunks_per_shard = self._get_chunks_per_shard(shard_spec) return input_byte_length + self._shard_index_size(chunks_per_shard) diff --git a/src/zarr/codecs/transpose.py b/src/zarr/codecs/transpose.py index 609448a59c..5756fba2b4 100644 --- a/src/zarr/codecs/transpose.py +++ b/src/zarr/codecs/transpose.py @@ -14,8 +14,8 @@ from typing import Self from zarr.core.buffer import NDBuffer - from zarr.core.chunk_grids import ChunkGrid from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.metadata.v3 import ChunkGridMetadata def parse_transpose_order(data: JSON | Iterable[int]) -> tuple[int, ...]: @@ -51,7 +51,7 @@ def validate( self, shape: tuple[int, ...], dtype: ZDType[TBaseDType, TBaseScalar], - chunk_grid: ChunkGrid, + chunk_grid: ChunkGridMetadata, ) -> None: if len(self.order) != len(shape): raise ValueError( diff --git a/src/zarr/codecs/vlen_utf8.py b/src/zarr/codecs/vlen_utf8.py index a10cb7c335..078e6032fc 100644 --- a/src/zarr/codecs/vlen_utf8.py +++ b/src/zarr/codecs/vlen_utf8.py @@ -67,8 +67,10 @@ def _encode_sync( chunk_spec: ArraySpec, ) -> Buffer | None: assert isinstance(chunk_array, NDBuffer) + # numcodecs vlen codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) return chunk_spec.prototype.buffer.from_bytes( - _vlen_utf8_codec.encode(chunk_array.as_numpy_array()) + _vlen_utf8_codec.encode(np.ascontiguousarray(chunk_array.as_numpy_array())) ) async def _encode_single( @@ -125,8 +127,10 @@ def _encode_sync( chunk_spec: ArraySpec, ) -> Buffer | None: assert isinstance(chunk_array, NDBuffer) + # numcodecs vlen codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) return chunk_spec.prototype.buffer.from_bytes( - _vlen_bytes_codec.encode(chunk_array.as_numpy_array()) + _vlen_bytes_codec.encode(np.ascontiguousarray(chunk_array.as_numpy_array())) ) async def _encode_single( diff --git a/src/zarr/codecs/zstd.py b/src/zarr/codecs/zstd.py index f93c25a3c7..6d9f8910a7 100644 --- a/src/zarr/codecs/zstd.py +++ b/src/zarr/codecs/zstd.py @@ -12,6 +12,7 @@ from zarr.abc.codec import BytesBytesCodec from zarr.core.buffer.cpu import as_numpy_array_wrapper from zarr.core.common import JSON, parse_named_configuration +from zarr.core.json_parse import parse_field if TYPE_CHECKING: from typing import Self @@ -21,17 +22,15 @@ def parse_zstd_level(data: JSON) -> int: - if isinstance(data, int): - if data >= 23: - raise ValueError(f"Value must be less than or equal to 22. Got {data} instead.") - return data - raise TypeError(f"Got value with type {type(data)}, but expected an int.") + parsed: int = parse_field(data, int, "level", error=TypeError) + if parsed >= 23: + raise ValueError(f"Value must be less than or equal to 22. Got {parsed} instead.") + return parsed def parse_checksum(data: JSON) -> bool: - if isinstance(data, bool): - return data - raise TypeError(f"Expected bool. Got {type(data)}.") + parsed: bool = parse_field(data, bool, "checksum", error=TypeError) + return parsed @dataclass(frozen=True) diff --git a/src/zarr/convenience.py b/src/zarr/convenience.py deleted file mode 100644 index 391ffc5186..0000000000 --- a/src/zarr/convenience.py +++ /dev/null @@ -1,44 +0,0 @@ -""" -Convenience helpers. - -!!! warning "Deprecated" - This sub-module is deprecated. All functions here are defined in the top level zarr namespace instead. -""" - -import warnings - -from zarr.api.synchronous import ( - consolidate_metadata, - copy, - copy_all, - copy_store, - load, - open, - open_consolidated, - save, - save_array, - save_group, - tree, -) -from zarr.errors import ZarrDeprecationWarning - -__all__ = [ - "consolidate_metadata", - "copy", - "copy_all", - "copy_store", - "load", - "open", - "open_consolidated", - "save", - "save_array", - "save_group", - "tree", -] - -warnings.warn( - "zarr.convenience is deprecated. " - "Import these functions from the top level zarr. namespace instead.", - ZarrDeprecationWarning, - stacklevel=2, -) diff --git a/src/zarr/core/_coalesce.py b/src/zarr/core/_coalesce.py new file mode 100644 index 0000000000..bfee9b4052 --- /dev/null +++ b/src/zarr/core/_coalesce.py @@ -0,0 +1,222 @@ +# src/zarr/core/_coalesce.py +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING, NamedTuple + +from zarr.abc.store import RangeByteRequest + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator, Awaitable, Callable, Sequence + + from zarr.abc.store import ByteRequest + from zarr.core.buffer import Buffer + + +class _WorkerCtx(NamedTuple): + """Shared state passed to the per-task worker coroutines. + + Bundling these lets the workers declare their dependencies as one + parameter instead of capturing them implicitly via closure. + """ + + fetch: Callable[[ByteRequest | None], Awaitable[Buffer | None]] + semaphore: asyncio.Semaphore + + +async def _fetch_single( + ctx: _WorkerCtx, idx: int, req: ByteRequest | None +) -> Sequence[tuple[int, Buffer | None]]: + """Fetch one byte range. Raises FileNotFoundError if the key is absent.""" + async with ctx.semaphore: + buf = await ctx.fetch(req) + if buf is None: + raise FileNotFoundError + return ((idx, buf),) + + +async def _fetch_group( + ctx: _WorkerCtx, members: list[tuple[int, RangeByteRequest]] +) -> Sequence[tuple[int, Buffer | None]]: + """Fetch one merged byte range and slice it back into per-input buffers. + + `members` must already be sorted by `start`; callers in this module + build it from the sorted mergeable list. Raises `FileNotFoundError` + if the key is absent. + """ + if len(members) == 1: + solo_idx, solo_req = members[0] + return await _fetch_single(ctx, solo_idx, solo_req) + + start = members[0][1].start + end = max(r.end for _, r in members) + async with ctx.semaphore: + big = await ctx.fetch(RangeByteRequest(start, end)) + if big is None: + raise FileNotFoundError + sliced = [(idx, big[r.start - start : r.end - start]) for idx, r in members] + return tuple(sliced) + + +def coalesce_ranges( + byte_ranges: Sequence[ByteRequest | None], + *, + max_gap_bytes: int, + max_coalesced_bytes: int, +) -> tuple[ + list[list[tuple[int, RangeByteRequest]]], + list[tuple[int, ByteRequest | None]], +]: + """Plan a set of byte-range fetches: which inputs merge, which stand alone. + + Pure (no I/O). The result is the I/O plan a caller would execute: each + group corresponds to one fetch of a coalesced byte range, and each + uncoalescable item corresponds to one fetch of the original request. + + All tuning knobs are required keyword arguments. `Store.get_ranges` is + the public entry point and owns the canonical default values; this + function takes them explicitly to avoid duplicating policy. + + Parameters + ---------- + byte_ranges + Input ranges. `None` means "the whole value". + max_gap_bytes + Two `RangeByteRequest`s separated by at most this many bytes may be + merged into one fetch. + max_coalesced_bytes + Upper bound on the size of a single merged fetch. + + Returns + ------- + groups + List of merged groups. Each group is a list of + `(input_index, RangeByteRequest)` pairs sorted by `start`. A + single-element group represents a `RangeByteRequest` that did not + merge with any neighbor. + uncoalescable + List of `(input_index, request)` pairs for inputs that are not + `RangeByteRequest` (`OffsetByteRequest`, `SuffixByteRequest`, + `None`). Indices are preserved from the input order. + + Notes + ----- + Only `RangeByteRequest` inputs participate in coalescing. Two ranges + merge when both: their gap (next `start` minus current group's running + `end`) is `<= max_gap_bytes`, and the resulting merged span is + `<= max_coalesced_bytes`. + """ + indexed = list(enumerate(byte_ranges)) + mergeable = [(i, r) for i, r in indexed if isinstance(r, RangeByteRequest)] + uncoalescable: list[tuple[int, ByteRequest | None]] = [ + (i, r) for i, r in indexed if not isinstance(r, RangeByteRequest) + ] + + # Sort mergeables by start offset, then merge. Track running start/end of the + # current group so each merge step is O(1) instead of O(group size). + mergeable.sort(key=lambda pair: pair[1].start) + groups: list[list[tuple[int, RangeByteRequest]]] = [] + group_start = 0 + group_end = 0 + for pair in mergeable: + _i, r = pair + if groups and r.start - group_end <= max_gap_bytes: + prospective_end = max(group_end, r.end) + if prospective_end - group_start <= max_coalesced_bytes: + groups[-1].append(pair) + group_end = prospective_end + continue + groups.append([pair]) + group_start = r.start + group_end = r.end + + return groups, uncoalescable + + +async def coalesced_get( + fetch: Callable[[ByteRequest | None], Awaitable[Buffer | None]], + byte_ranges: Sequence[ByteRequest | None], + *, + max_concurrency: int, + max_gap_bytes: int, + max_coalesced_bytes: int, +) -> AsyncGenerator[Sequence[tuple[int, Buffer | None]]]: + """Read many byte ranges through `fetch` with coalescing and concurrency. + + Nearby ranges are merged into a single underlying I/O, and merged fetches + are run concurrently. Each yield corresponds to exactly one underlying I/O + operation: a sequence of `(input_index, result)` tuples for all input + ranges served by that I/O. Tuples within a yielded sequence are ordered by + start offset. Yields across groups are in completion order, not input + order. + + All tuning knobs are required keyword arguments. `Store.get_ranges` is + the public entry point and owns the canonical default values; this + function takes them explicitly to avoid duplicating policy. + + Parameters + ---------- + fetch + Callable that reads one byte range and returns a `Buffer` (or `None` + if the underlying key does not exist). Typically constructed via + `functools.partial(store.get, key, prototype)`. + byte_ranges + Input ranges. `None` means "the whole value". + max_concurrency + Maximum number of merged fetches in flight at once. + max_gap_bytes + Forwarded to `coalesce_ranges`. + max_coalesced_bytes + Forwarded to `coalesce_ranges`. + + Yields + ------ + Sequence[tuple[int, Buffer | None]] + Per-I/O batch of `(input_index, result)` tuples. + + Notes + ----- + - Only `RangeByteRequest` inputs are coalesced. `OffsetByteRequest`, + `SuffixByteRequest`, and `None` are each treated as uncoalescable + (one fetch, one single-tuple yield per input). + - Failures from underlying fetches surface as a `BaseExceptionGroup` + (PEP 654). Inner exceptions include `FileNotFoundError` if a fetch + returns `None`, plus any exception `fetch` raises. Pending fetches are + cancelled as soon as one task fails, so the group typically contains a + single non-`CancelledError` exception even under high concurrency. + - Groups completed before the failure remain observable on the yields + preceding the raise. + - `GeneratorExit` raised by `aclose()` is filtered out so the iterator + closes cleanly; callers don't see a group containing only it. + """ + if not byte_ranges: + return + + groups, singles = coalesce_ranges( + byte_ranges, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ) + + ctx = _WorkerCtx(fetch=fetch, semaphore=asyncio.Semaphore(max_concurrency)) + + # Launch all work as tasks. The semaphore bounds actual I/O concurrency. + # TaskGroup wraps task exceptions in BaseExceptionGroup; we propagate the + # group unchanged as part of the public contract (callers handle batch + # failures via `except*` / PEP 654). GeneratorExit (raised when the + # consumer calls aclose()) is filtered out so close completes cleanly. + try: + async with asyncio.TaskGroup() as tg: + tasks = [ + *(tg.create_task(_fetch_group(ctx, group)) for group in groups), + *(tg.create_task(_fetch_single(ctx, i, single)) for i, single in singles), + ] + + for fut in asyncio.as_completed(tasks): + yield await fut + except BaseExceptionGroup as eg: + # Strip GeneratorExits (consumer aclose()) and propagate whatever remains. + _, other_errors = eg.split(GeneratorExit) + + if other_errors is not None: + raise other_errors from None diff --git a/src/zarr/core/_info.py b/src/zarr/core/_info.py index fef424346a..1503f05b26 100644 --- a/src/zarr/core/_info.py +++ b/src/zarr/core/_info.py @@ -117,7 +117,7 @@ def __repr__(self) -> str: if self._chunk_shape is None: # for non-regular chunk grids - kwargs["chunk_shape"] = "" + kwargs["_chunk_shape"] = "" template += "\nFilters : {_filters}" diff --git a/src/zarr/core/_json.py b/src/zarr/core/_json.py new file mode 100644 index 0000000000..efe8152a4f --- /dev/null +++ b/src/zarr/core/_json.py @@ -0,0 +1,133 @@ +"""Helpers for moving JSON documents in and out of zarr stores. + +These are free functions, deliberately not methods on the ``Store`` ABC: +reading and writing JSON is a composition of the store's ``get``/``set`` +primitives with a buffer/JSON conversion, not part of the store contract. +Keeping them as functions means stores cannot (and need not) override them, +and the ``Store`` definition stays free of any dependency on the buffer +prototype. + +These functions are pure: the JSON encoding parameters (``indent``, +``allow_nan``) are explicit arguments rather than read from the global config. +Callers that want zarr's configured indentation pass +``indent=config.get("json_indent")``. + +Two layers: + +- ``buffer_to_json`` / ``json_to_buffer`` convert between a ``Buffer`` and a + parsed JSON value. The buffer prototype lives here, at buffer construction, + where it is meaningful. +- ``get_json`` / ``set_json`` compose those with ``Store.get`` / ``Store.set``. + ``get_json`` returns ``None`` for a missing key (the contract most callers + want); callers that require presence check for ``None`` themselves. +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, cast + +from zarr.core.buffer import default_buffer_prototype + +if TYPE_CHECKING: + from zarr.abc.store import ByteRequest, Store + from zarr.core.buffer import Buffer, BufferPrototype + from zarr.core.common import JSON + + +def buffer_to_json(buffer: Buffer) -> JSON: + """Parse the contents of a `Buffer` as a JSON value.""" + # json.loads is typed as returning Any; the result is by definition JSON. + return cast("JSON", json.loads(buffer.to_bytes())) + + +def buffer_to_json_object(buffer: Buffer) -> dict[str, JSON]: + """Parse the contents of a `Buffer` as a JSON object (a `dict`). + + Every metadata document zarr reads is a JSON object, so this narrows the + `JSON` union to `dict[str, JSON]` once, here, instead of at each call site. + + Parameters + ---------- + buffer + The buffer whose contents are parsed as a JSON object. + + Raises + ------ + TypeError + If the parsed value is not a JSON object. + """ + obj = buffer_to_json(buffer) + if not isinstance(obj, dict): + raise TypeError(f"Expected a JSON object, got {type(obj).__name__}.") + return obj + + +def json_to_buffer( + obj: JSON, + *, + prototype: BufferPrototype | None = None, + indent: int | None = None, + allow_nan: bool = True, +) -> Buffer: + """Serialize a JSON value into a `Buffer`. + + Parameters + ---------- + obj + The JSON-serializable value to encode. + prototype + The buffer prototype to construct the result with. Defaults to + `default_buffer_prototype()`. + indent + Indentation passed to `json.dumps`. `None` (the default) writes + without newline indentation, using json's default separators. + Callers that want zarr's configured indentation pass + `indent=config.get("json_indent")`. + allow_nan + Whether to permit `NaN`/`Infinity` in the output, passed to + `json.dumps`. + """ + if prototype is None: + prototype = default_buffer_prototype() + return prototype.buffer.from_bytes(json.dumps(obj, indent=indent, allow_nan=allow_nan).encode()) + + +async def get_json(store: Store, key: str, *, byte_range: ByteRequest | None = None) -> JSON | None: + """Read and parse the JSON document at `key`, or `None` if it is absent. + + Parameters + ---------- + store + The store to read from. + key + The key identifying the JSON document. + byte_range + If given, read only this portion of the value. Note that a partial + read of a JSON document may not be valid JSON. + + Returns + ------- + JSON or None + The parsed JSON value, or `None` if `key` does not exist. + """ + buffer = await store.get(key, default_buffer_prototype(), byte_range) + return None if buffer is None else buffer_to_json(buffer) + + +async def set_json( + store: Store, + key: str, + obj: JSON, + *, + prototype: BufferPrototype | None = None, + indent: int | None = None, + allow_nan: bool = True, +) -> None: + """Serialize `obj` as JSON and write it to `key` in `store`. + + `indent` and `allow_nan` are forwarded to `json_to_buffer`. + """ + await store.set( + key, json_to_buffer(obj, prototype=prototype, indent=indent, allow_nan=allow_nan) + ) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 486216fa32..9cb66f339e 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -1,18 +1,16 @@ from __future__ import annotations -import json +import math import warnings from asyncio import gather -from collections.abc import Iterable, Mapping +from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace from itertools import starmap from logging import getLogger from typing import ( TYPE_CHECKING, Any, - Generic, Literal, - TypeAlias, TypedDict, cast, overload, @@ -20,7 +18,7 @@ from warnings import warn import numpy as np -from typing_extensions import deprecated +from typing_extensions import Sentinel, deprecated import zarr from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec @@ -30,7 +28,8 @@ from zarr.codecs.vlen_utf8 import VLenBytesCodec, VLenUTF8Codec from zarr.codecs.zstd import ZstdCodec from zarr.core._info import ArrayInfo -from zarr.core.array_spec import ArrayConfig, ArrayConfigLike, parse_array_config +from zarr.core._json import buffer_to_json_object +from zarr.core.array_spec import ArrayConfig, ArrayConfigLike, ArraySpec, parse_array_config from zarr.core.attributes import Attributes from zarr.core.buffer import ( BufferPrototype, @@ -40,7 +39,15 @@ default_buffer_prototype, ) from zarr.core.buffer.cpu import buffer_prototype as cpu_buffer_prototype -from zarr.core.chunk_grids import RegularChunkGrid, _auto_partition, normalize_chunks +from zarr.core.chunk_grids import ( + SHARDED_INNER_CHUNK_MAX_BYTES, + ChunkGrid, + _is_rectilinear_chunks, + as_regular_shape, + guess_chunks, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) from zarr.core.chunk_key_encodings import ( ChunkKeyEncoding, ChunkKeyEncodingLike, @@ -53,7 +60,8 @@ ZARR_JSON, ZARRAY_JSON, ZATTRS_JSON, - DimensionNames, + ChunksLike, + DimensionNamesLike, MemoryOrder, ShapeLike, ZarrFormat, @@ -66,6 +74,7 @@ ) from zarr.core.config import config as zarr_config from zarr.core.dtype import ( + Structured, VariableLengthBytes, VariableLengthUTF8, ZDType, @@ -107,7 +116,6 @@ ArrayV2Metadata, ArrayV2MetadataDict, ArrayV3Metadata, - T_ArrayMetadata, ) from zarr.core.metadata.io import save_metadata from zarr.core.metadata.v2 import ( @@ -116,10 +124,15 @@ parse_compressor, parse_filters, ) -from zarr.core.metadata.v3 import parse_node_type_array +from zarr.core.metadata.v3 import ( + ChunkGridMetadata, + create_chunk_grid_metadata, + parse_node_type_array, +) from zarr.core.sync import sync from zarr.errors import ( ArrayNotFoundError, + ChunkNotFoundError, MetadataValidationError, ZarrDeprecationWarning, ZarrUserWarning, @@ -134,23 +147,22 @@ from zarr.storage._utils import _relativize_path if TYPE_CHECKING: - from collections.abc import Iterator, Sequence + from collections.abc import Iterator from typing import Self import numpy.typing as npt from zarr.abc.codec import CodecPipeline from zarr.abc.store import Store - from zarr.codecs.sharding import ShardingCodecIndexLocation + from zarr.codecs.sharding import IndexLocation from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar from zarr.storage import StoreLike from zarr.types import AnyArray, AnyAsyncArray, ArrayV2, ArrayV3, AsyncArrayV2, AsyncArrayV3 -# Array and AsyncArray are defined in the base ``zarr`` namespace +# Array and AsyncArray are defined in the base `zarr` namespace __all__ = [ "DEFAULT_FILL_VALUE", - "DefaultFillValue", "create_codec_pipeline", "parse_array_metadata", ] @@ -158,22 +170,31 @@ logger = getLogger(__name__) -class DefaultFillValue: - """ - Sentinel class to indicate that the default fill value should be used. - - This class exists because conventional values used to convey "defaultness" like ``None`` or - ``"auto"` are ambiguous when specifying the fill value parameter of a Zarr array. - The value ``None`` is ambiguous because it is a valid fill value for Zarr V2 - (resulting in ``"fill_value": null`` in array metadata). - A string like ``"auto"`` is ambiguous because such a string is a valid fill value for an array - with a string data type. - An instance of this class lies outside the space of valid fill values, which means it can - umambiguously express that the default fill value should be used. - """ +DEFAULT_FILL_VALUE = Sentinel("DEFAULT_FILL_VALUE") +""" +Sentinel indicating that the default fill value should be used. +This sentinel exists because conventional values used to convey "defaultness" like `None` or +`"auto"` are ambiguous when specifying the fill value parameter of a Zarr array. +The value `None` is ambiguous because it is a valid fill value for Zarr V2 +(resulting in `"fill_value": null` in array metadata). +A string like `"auto"` is ambiguous because such a string is a valid fill value for an array +with a string data type. +This sentinel lies outside the space of valid fill values, which means it can +unambiguously express that the default fill value should be used. +""" -DEFAULT_FILL_VALUE = DefaultFillValue() + +def _chunk_sizes_from_shape( + array_shape: tuple[int, ...], chunk_shape: tuple[int, ...] +) -> tuple[tuple[int, ...], ...]: + """Compute dask-style chunk sizes from an array shape and uniform chunk shape.""" + result: list[tuple[int, ...]] = [] + for s, c in zip(array_shape, chunk_shape, strict=True): + nchunks = ceildiv(s, c) + sizes = tuple(min(c, s - i * c) for i in range(nchunks)) + result.append(sizes) + return tuple(result) def parse_array_metadata(data: Any) -> ArrayMetadata: @@ -207,10 +228,41 @@ def create_codec_pipeline(metadata: ArrayMetadata, *, store: Store | None = None pass if isinstance(metadata, ArrayV3Metadata): - return get_pipeline_class().from_codecs(metadata.codecs) + # The pipeline built here is a throwaway: `evolve_from_array_spec` below + # reconstructs codecs against the evolved spec. `from_codecs` is the + # chain's first construction, so its advisory warnings (e.g. sharding's + # "disables partial reads" warning) fire here; `evolve_from_array_spec` + # re-splits the same already-warned-about chain via + # `codecs_from_list_unchecked`, so it does not re-emit them. + pipeline = get_pipeline_class().from_codecs(metadata.codecs) + from zarr.core.metadata.v3 import RegularChunkGridMetadata + + # Use the regular chunk shape if available, otherwise use a + # placeholder. The ChunkTransform is shape-agnostic — the actual + # chunk shape is passed per-call at decode/encode time. + if isinstance(metadata.chunk_grid, RegularChunkGridMetadata): + chunk_shape = metadata.chunk_grid.chunk_shape + else: + chunk_shape = (1,) * len(metadata.shape) + chunk_spec = ArraySpec( + shape=chunk_shape, + dtype=metadata.data_type, + fill_value=metadata.fill_value, + config=ArrayConfig.from_dict({}), + prototype=default_buffer_prototype(), + ) + return pipeline.evolve_from_array_spec(chunk_spec) elif isinstance(metadata, ArrayV2Metadata): v2_codec = V2Codec(filters=metadata.filters, compressor=metadata.compressor) - return get_pipeline_class().from_codecs([v2_codec]) + pipeline = get_pipeline_class().from_codecs([v2_codec]) + chunk_spec = ArraySpec( + shape=metadata.chunks, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=ArrayConfig.from_dict({"order": metadata.order}), + prototype=default_buffer_prototype(), + ) + return pipeline.evolve_from_array_spec(chunk_spec) raise TypeError # pragma: no cover @@ -265,21 +317,37 @@ async def get_array_metadata( if zarr_format == 2: # V2 arrays are comprised of a .zarray and .zattrs objects assert zarray_bytes is not None - metadata_dict = json.loads(zarray_bytes.to_bytes()) - zattrs_dict = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {} + metadata_dict = buffer_to_json_object(zarray_bytes) + zattrs_dict = buffer_to_json_object(zattrs_bytes) if zattrs_bytes is not None else {} metadata_dict["attributes"] = zattrs_dict else: # V3 arrays are comprised of a zarr.json object assert zarr_json_bytes is not None - metadata_dict = json.loads(zarr_json_bytes.to_bytes()) + metadata_dict = buffer_to_json_object(zarr_json_bytes) parse_node_type_array(metadata_dict.get("node_type")) return metadata_dict +async def _prepare_overwrite( + store_path: StorePath, *, zarr_format: ZarrFormat, overwrite: bool +) -> None: + """ + Prepare a store path for writing a new node. + + If `overwrite` is true and the store supports deletes, any existing node at + `store_path` is deleted. Otherwise, the absence of an existing node is enforced + (raising if one is present). + """ + if overwrite and store_path.store.supports_deletes: + await store_path.delete_dir() + else: + await ensure_no_existing_node(store_path, zarr_format=zarr_format) + + @dataclass(frozen=True) -class AsyncArray(Generic[T_ArrayMetadata]): +class AsyncArray[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: """ An asynchronous array class representing a chunked array stored in a Zarr store. @@ -307,6 +375,7 @@ class AsyncArray(Generic[T_ArrayMetadata]): metadata: T_ArrayMetadata store_path: StorePath codec_pipeline: CodecPipeline = field(init=False) + _chunk_grid: ChunkGrid = field(init=False) config: ArrayConfig @overload @@ -337,279 +406,13 @@ def __init__( object.__setattr__(self, "metadata", metadata_parsed) object.__setattr__(self, "store_path", store_path) object.__setattr__(self, "config", config_parsed) + object.__setattr__(self, "_chunk_grid", ChunkGrid.from_metadata(metadata_parsed)) object.__setattr__( self, "codec_pipeline", create_codec_pipeline(metadata=metadata_parsed, store=store_path.store), ) - # this overload defines the function signature when zarr_format is 2 - @overload - @classmethod - async def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: ShapeLike, - dtype: ZDTypeLike, - zarr_format: Literal[2], - fill_value: Any | None = DEFAULT_FILL_VALUE, - attributes: dict[str, JSON] | None = None, - chunks: ShapeLike | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: MemoryOrder | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: CompressorLikev2 | Literal["auto"] = "auto", - # runtime - overwrite: bool = False, - data: npt.ArrayLike | None = None, - config: ArrayConfigLike | None = None, - ) -> AsyncArrayV2: ... - - # this overload defines the function signature when zarr_format is 3 - @overload - @classmethod - async def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: ShapeLike, - dtype: ZDTypeLike, - zarr_format: Literal[3], - fill_value: Any | None = DEFAULT_FILL_VALUE, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ShapeLike | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, - # runtime - overwrite: bool = False, - data: npt.ArrayLike | None = None, - config: ArrayConfigLike | None = None, - ) -> AsyncArrayV3: ... - - @overload - @classmethod - async def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: ShapeLike, - dtype: ZDTypeLike, - zarr_format: Literal[3] = 3, - fill_value: Any | None = DEFAULT_FILL_VALUE, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ShapeLike | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, - # runtime - overwrite: bool = False, - data: npt.ArrayLike | None = None, - config: ArrayConfigLike | None = None, - ) -> AsyncArrayV3: ... - - @overload - @classmethod - async def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: ShapeLike, - dtype: ZDTypeLike, - zarr_format: ZarrFormat, - fill_value: Any | None = DEFAULT_FILL_VALUE, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ShapeLike | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, - # v2 only - chunks: ShapeLike | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: MemoryOrder | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: CompressorLike = "auto", - # runtime - overwrite: bool = False, - data: npt.ArrayLike | None = None, - config: ArrayConfigLike | None = None, - ) -> AnyAsyncArray: ... - - @classmethod - @deprecated("Use zarr.api.asynchronous.create_array instead.", category=ZarrDeprecationWarning) - async def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: ShapeLike, - dtype: ZDTypeLike, - zarr_format: ZarrFormat = 3, - fill_value: Any | None = DEFAULT_FILL_VALUE, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ShapeLike | None = None, - chunk_key_encoding: ( - ChunkKeyEncodingLike - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, - # v2 only - chunks: ShapeLike | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: MemoryOrder | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: CompressorLike = "auto", - # runtime - overwrite: bool = False, - data: npt.ArrayLike | None = None, - config: ArrayConfigLike | None = None, - ) -> AnyAsyncArray: - """Method to create a new asynchronous array instance. - - !!! warning "Deprecated" - `AsyncArray.create()` is deprecated since v3.0.0 and will be removed in a future release. - Use [`zarr.api.asynchronous.create_array`][] instead. - - Parameters - ---------- - store : StoreLike - The store where the array will be created. See the - [storage documentation in the user guide][user-guide-store-like] - for a description of all valid StoreLike values. - shape : ShapeLike - The shape of the array. - dtype : ZDTypeLike - The data type of the array. - zarr_format : ZarrFormat, optional - The Zarr format version (default is 3). - fill_value : Any, optional - The fill value of the array (default is None). - attributes : dict[str, JSON], optional - The attributes of the array (default is None). - chunk_shape : tuple[int, ...], optional - The shape of the array's chunks - Zarr format 3 only. Zarr format 2 arrays should use `chunks` instead. - If not specified, default are guessed based on the shape and dtype. - chunk_key_encoding : ChunkKeyEncodingLike, optional - A specification of how the chunk keys are represented in storage. - Zarr format 3 only. Zarr format 2 arrays should use `dimension_separator` instead. - Default is ``("default", "/")``. - codecs : Sequence of Codecs or dicts, optional - An iterable of Codec or dict serializations of Codecs. The elements of - this collection specify the transformation from array values to stored bytes. - Zarr format 3 only. Zarr format 2 arrays should use ``filters`` and ``compressor`` instead. - - If no codecs are provided, default codecs will be used: - dimension_names : Iterable[str | None], optional - The names of the dimensions (default is None). - Zarr format 3 only. Zarr format 2 arrays should not use this parameter. - chunks : ShapeLike, optional - The shape of the array's chunks. - Zarr format 2 only. Zarr format 3 arrays should use ``chunk_shape`` instead. - If not specified, default are guessed based on the shape and dtype. - dimension_separator : Literal[".", "/"], optional - The dimension separator (default is "."). - Zarr format 2 only. Zarr format 3 arrays should use ``chunk_key_encoding`` instead. - order : Literal["C", "F"], optional - The memory of the array (default is "C"). - If ``zarr_format`` is 2, this parameter sets the memory order of the array. - If ``zarr_format`` is 3, then this parameter is deprecated, because memory order - is a runtime parameter for Zarr 3 arrays. The recommended way to specify the memory - order for Zarr 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. - filters : Iterable[Codec] | Literal["auto"], optional - Iterable of filters to apply to each chunk of the array, in order, before serializing that - chunk to bytes. - - For Zarr format 3, a "filter" is a codec that takes an array and returns an array, - and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a - dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. - - For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. - - The default value of ``"auto"`` instructs Zarr to use a default used based on the data - type of the array and the Zarr format specified. For all data types in Zarr V3, and most - data types in Zarr V2, the default filters are empty. The only cases where default filters - are not empty is when the Zarr format is 2, and the data type is a variable-length data type like - [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, - the default filters contains a single element which is a codec specific to that particular data type. - - To create an array with no filters, provide an empty iterable or the value ``None``. - compressor : dict[str, JSON], optional - The compressor used to compress the data (default is None). - Zarr format 2 only. Zarr format 3 arrays should use ``codecs`` instead. - - If no ``compressor`` is provided, a default compressor will be used: - - - For numeric arrays, the default is ``ZstdCodec``. - - For Unicode strings, the default is ``VLenUTF8Codec``. - - For bytes or objects, the default is ``VLenBytesCodec``. - - These defaults can be changed by modifying the value of ``array.v2_default_compressor`` in [`zarr.config`][zarr.config]. - overwrite : bool, optional - Whether to raise an error if the store already exists (default is False). - data : npt.ArrayLike, optional - The data to be inserted into the array (default is None). - config : ArrayConfigLike, optional - Runtime configuration for the array. - - Returns - ------- - AsyncArray - The created asynchronous array instance. - """ - return await cls._create( - store, - # v2 and v3 - shape=shape, - dtype=dtype, - zarr_format=zarr_format, - fill_value=fill_value, - attributes=attributes, - # v3 only - chunk_shape=chunk_shape, - chunk_key_encoding=chunk_key_encoding, - codecs=codecs, - dimension_names=dimension_names, - # v2 only - chunks=chunks, - dimension_separator=dimension_separator, - order=order, - filters=filters, - compressor=compressor, - # runtime - overwrite=overwrite, - data=data, - config=config, - ) - @classmethod async def _create( cls, @@ -630,7 +433,7 @@ async def _create( | None ) = None, codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, # v2 only chunks: ShapeLike | None = None, dimension_separator: Literal[".", "/"] | None = None, @@ -653,13 +456,10 @@ async def _create( if chunks is not None and chunk_shape is not None: raise ValueError("Only one of chunk_shape or chunks can be provided.") - item_size = 1 - if isinstance(dtype_parsed, HasItemSize): - item_size = dtype_parsed.item_size - if chunks: - _chunks = normalize_chunks(chunks, shape, item_size) - else: - _chunks = normalize_chunks(chunk_shape, shape, item_size) + + # Unify the v2 (chunks) and v3 (chunk_shape) parameter names + _raw_chunks = chunks if chunks is not None else chunk_shape + config_parsed = parse_array_config(config) result: AnyAsyncArray @@ -680,11 +480,18 @@ async def _create( if order is not None: _warn_order_kwarg() + item_size = 1 + if isinstance(dtype_parsed, HasItemSize): + item_size = dtype_parsed.item_size + if _raw_chunks is None: + outer_chunks = guess_chunks(shape, item_size) + else: + outer_chunks = normalize_chunks_nd(_raw_chunks, shape) + chunk_grid = create_chunk_grid_metadata(outer_chunks) result = await cls._create_v3( store_path, shape=shape, dtype=dtype_parsed, - chunk_shape=_chunks, fill_value=fill_value, chunk_key_encoding=chunk_key_encoding, codecs=codecs, @@ -692,6 +499,7 @@ async def _create( attributes=attributes, overwrite=overwrite, config=config_parsed, + chunk_grid=chunk_grid, ) elif zarr_format == 2: if codecs is not None: @@ -704,6 +512,18 @@ async def _create( ) if dimension_names is not None: raise ValueError("dimension_names cannot be used for arrays with zarr_format 2.") + if _is_rectilinear_chunks(_raw_chunks): + raise ValueError("Zarr format 2 does not support rectilinear chunk grids.") + + item_size = 1 + if isinstance(dtype_parsed, HasItemSize): + item_size = dtype_parsed.item_size + _raw = chunks or chunk_shape + if _raw is None: + outer_chunks = guess_chunks(shape, item_size) + else: + outer_chunks = normalize_chunks_nd(_raw, shape) + _chunks = as_regular_shape(outer_chunks) if order is None: order_parsed = config_parsed.order @@ -738,22 +558,21 @@ async def _create( def _create_metadata_v3( shape: ShapeLike, dtype: ZDType[TBaseDType, TBaseScalar], - chunk_shape: tuple[int, ...], + chunk_grid: ChunkGridMetadata, fill_value: Any | None = DEFAULT_FILL_VALUE, chunk_key_encoding: ChunkKeyEncodingLike | None = None, codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, attributes: dict[str, JSON] | None = None, ) -> ArrayV3Metadata: - """ - Create an instance of ArrayV3Metadata. - """ + """Create an instance of ArrayV3Metadata.""" filters: tuple[ArrayArrayCodec, ...] compressors: tuple[BytesBytesCodec, ...] shape = parse_shapelike(shape) if codecs is None: - filters = default_filters_v3(dtype) + # no data types have default filters + filters = () serializer = default_serializer_v3(dtype) compressors = default_compressors_v3(dtype) @@ -767,18 +586,17 @@ def _create_metadata_v3( else: chunk_key_encoding_parsed = chunk_key_encoding - if isinstance(fill_value, DefaultFillValue) or fill_value is None: - # Use dtype's default scalar for DefaultFillValue sentinel - # For v3, None is converted to DefaultFillValue behavior + if fill_value is DEFAULT_FILL_VALUE or fill_value is None: + # Use dtype's default scalar for the DEFAULT_FILL_VALUE sentinel + # For v3, None is converted to DEFAULT_FILL_VALUE behavior fill_value_parsed = dtype.default_scalar() else: fill_value_parsed = fill_value - chunk_grid_parsed = RegularChunkGrid(chunk_shape=chunk_shape) return ArrayV3Metadata( shape=shape, data_type=dtype, - chunk_grid=chunk_grid_parsed, + chunk_grid=chunk_grid, chunk_key_encoding=chunk_key_encoding_parsed, fill_value=fill_value_parsed, codecs=codecs_parsed, # type: ignore[arg-type] @@ -793,7 +611,7 @@ async def _create_v3( *, shape: ShapeLike, dtype: ZDType[TBaseDType, TBaseScalar], - chunk_shape: tuple[int, ...], + chunk_grid: ChunkGridMetadata, config: ArrayConfig, fill_value: Any | None = DEFAULT_FILL_VALUE, chunk_key_encoding: ( @@ -803,17 +621,11 @@ async def _create_v3( | None ) = None, codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, attributes: dict[str, JSON] | None = None, overwrite: bool = False, ) -> AsyncArrayV3: - if overwrite: - if store_path.store.supports_deletes: - await store_path.delete_dir() - else: - await ensure_no_existing_node(store_path, zarr_format=3) - else: - await ensure_no_existing_node(store_path, zarr_format=3) + await _prepare_overwrite(store_path, zarr_format=3, overwrite=overwrite) if isinstance(chunk_key_encoding, tuple): chunk_key_encoding = ( @@ -825,7 +637,7 @@ async def _create_v3( metadata = cls._create_metadata_v3( shape=shape, dtype=dtype, - chunk_shape=chunk_shape, + chunk_grid=chunk_grid, fill_value=fill_value, chunk_key_encoding=chunk_key_encoding, codecs=codecs, @@ -852,8 +664,8 @@ def _create_metadata_v2( if dimension_separator is None: dimension_separator = "." - # Handle DefaultFillValue sentinel - if isinstance(fill_value, DefaultFillValue): + # Handle the DEFAULT_FILL_VALUE sentinel + if fill_value is DEFAULT_FILL_VALUE: fill_value_parsed: Any = dtype.default_scalar() else: # For v2, preserve None as-is (backward compatibility) @@ -888,13 +700,7 @@ async def _create_v2( attributes: dict[str, JSON] | None = None, overwrite: bool = False, ) -> AsyncArrayV2: - if overwrite: - if store_path.store.supports_deletes: - await store_path.delete_dir() - else: - await ensure_no_existing_node(store_path, zarr_format=2) - else: - await ensure_no_existing_node(store_path, zarr_format=2) + await _prepare_overwrite(store_path, zarr_format=2, overwrite=overwrite) compressor_parsed: CompressorLikev2 if compressor == "auto": @@ -1044,23 +850,81 @@ def chunks(self) -> tuple[int, ...]: """Returns the chunk shape of the Array. If sharding is used the inner chunk shape is returned. - Only defined for arrays using using `RegularChunkGrid`. - If array doesn't use `RegularChunkGrid`, `NotImplementedError` is raised. + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. Returns ------- tuple[int, ...]: The chunk shape of the Array. """ + # TODO: move sharding awareness out of metadata return self.metadata.chunks + @property + def read_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of chunks used for reading, clipped to the array extent. + + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + When sharding is used, returns the inner chunk sizes. + Otherwise, returns the outer chunk sizes (same as `write_chunk_sizes`). + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.read_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + + from zarr.codecs.sharding import ShardingCodec + + codecs: tuple[Codec, ...] = getattr(self.metadata, "codecs", ()) + if len(codecs) == 1 and isinstance(codecs[0], ShardingCodec): + inner_chunk_shape = codecs[0].chunk_shape + return _chunk_sizes_from_shape(self.shape, inner_chunk_shape) + return self._chunk_grid.chunk_sizes + + @property + def write_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of storage chunks, clipped to the array extent. + + Always returns the outer chunk sizes, regardless of sharding. + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> import zarr.storage + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.write_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + + return self._chunk_grid.chunk_sizes + @property def shards(self) -> tuple[int, ...] | None: """Returns the shard shape of the Array. Returns None if sharding is not used. - Only defined for arrays using using `RegularChunkGrid`. - If array doesn't use `RegularChunkGrid`, `NotImplementedError` is raised. + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. Returns ------- @@ -1078,7 +942,7 @@ def size(self) -> int: int Total number of elements in the array """ - return np.prod(self.metadata.shape).item() + return math.prod(self.metadata.shape) @property def filters(self) -> tuple[Numcodec, ...] | tuple[ArrayArrayCodec, ...]: @@ -1142,10 +1006,9 @@ def _zdtype(self) -> ZDType[TBaseDType, TBaseScalar]: """ The zarr-specific representation of the array data type """ - if self.metadata.zarr_format == 2: - return self.metadata.dtype - else: - return self.metadata.data_type + # `dtype` returns the zarr dtype object for both v2 and v3 metadata + # (on v3 it is an alias for `data_type`). + return self.metadata.dtype @property def dtype(self) -> TBaseDType: @@ -1258,7 +1121,16 @@ def _chunk_grid_shape(self) -> tuple[int, ...]: tuple[int, ...] The number of chunks along each dimension. """ - return tuple(starmap(ceildiv, zip(self.shape, self.chunks, strict=True))) + # TODO: refactor — extract a sharding_codec property on ArrayV3Metadata + # to replace the repeated `len == 1 and isinstance` pattern. + from zarr.codecs.sharding import ShardingCodec + + codecs: tuple[Codec, ...] = getattr(self.metadata, "codecs", ()) + if len(codecs) == 1 and isinstance(codecs[0], ShardingCodec): + # When sharding, count inner chunks across the whole array + chunk_shape = codecs[0].chunk_shape + return tuple(starmap(ceildiv, zip(self.shape, chunk_shape, strict=True))) + return self._chunk_grid.grid_shape @property def _shard_grid_shape(self) -> tuple[int, ...]: @@ -1502,7 +1374,7 @@ def _iter_shard_keys( ------ key: str The storage key of each shard in the selection or in case of no shard - present of each chunk although the latter case as technically incorrect. + present of each chunk although the latter case is technically incorrect. """ # Iterate over the coordinates of chunks in chunk grid space. return _iter_shard_keys( @@ -1567,7 +1439,7 @@ def nbytes(self) -> int: ----- This value is calculated by multiplying the number of elements in the array and the size of each element, the latter of which is determined by the dtype of the array. - For this reason, ``nbytes`` will likely be inaccurate for arrays with variable-length + For this reason, `nbytes` will likely be inaccurate for arrays with variable-length dtypes. It is not possible to determine the size of an array with variable-length elements from the shape and dtype alone. """ @@ -1586,6 +1458,7 @@ async def _get_selection( self.metadata, self.codec_pipeline, self.config, + self._chunk_grid, indexer, prototype=prototype, out=out, @@ -1615,31 +1488,31 @@ async def getitem( Examples -------- - ```python - import asyncio - import zarr.api.asynchronous - - async def example(): - store = zarr.storage.MemoryStore() - async_arr = await zarr.api.asynchronous.create_array( - store=store, - shape=(100,100), - chunks=(10,10), - dtype='i4', - fill_value=0) - result = await async_arr.getitem((0,1)) - print(result) - #> 0 - return result - - value = asyncio.run(example()) - ``` + >>> async def example(): + ... import zarr.api.asynchronous + ... import zarr.storage + ... + ... async_arr = await zarr.api.asynchronous.create_array( + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="i4", + ... fill_value=0, + ... ) + ... + ... return await async_arr.getitem((0, 1)) + + >>> import asyncio + >>> asyncio.run(example()) + np.int32(0) """ + return await _getitem( self.store_path, self.metadata, self.codec_pipeline, self.config, + self._chunk_grid, selection, prototype=prototype, ) @@ -1652,12 +1525,16 @@ async def get_orthogonal_selection( fields: Fields | None = None, prototype: BufferPrototype | None = None, ) -> NDArrayLikeOrScalar: - return await _get_orthogonal_selection( + if prototype is None: + prototype = default_buffer_prototype() + indexer = OrthogonalIndexer(selection, self.metadata.shape, self._chunk_grid) + return await _get_selection( self.store_path, self.metadata, self.codec_pipeline, self.config, - selection, + self._chunk_grid, + indexer=indexer, out=out, fields=fields, prototype=prototype, @@ -1671,12 +1548,16 @@ async def get_mask_selection( fields: Fields | None = None, prototype: BufferPrototype | None = None, ) -> NDArrayLikeOrScalar: - return await _get_mask_selection( + if prototype is None: + prototype = default_buffer_prototype() + indexer = MaskIndexer(mask, self.metadata.shape, self._chunk_grid) + return await _get_selection( self.store_path, self.metadata, self.codec_pipeline, self.config, - mask, + self._chunk_grid, + indexer=indexer, out=out, fields=fields, prototype=prototype, @@ -1690,16 +1571,24 @@ async def get_coordinate_selection( fields: Fields | None = None, prototype: BufferPrototype | None = None, ) -> NDArrayLikeOrScalar: - return await _get_coordinate_selection( + if prototype is None: + prototype = default_buffer_prototype() + indexer = CoordinateIndexer(selection, self.metadata.shape, self._chunk_grid) + out_array = await _get_selection( self.store_path, self.metadata, self.codec_pipeline, self.config, - selection, + self._chunk_grid, + indexer=indexer, out=out, fields=fields, prototype=prototype, ) + if hasattr(out_array, "shape"): + # restore shape + out_array = cast("NDArrayLikeOrScalar", np.array(out_array).reshape(indexer.sel_shape)) + return out_array async def _save_metadata(self, metadata: ArrayMetadata, ensure_parents: bool = False) -> None: """ @@ -1720,6 +1609,7 @@ async def _set_selection( self.metadata, self.codec_pipeline, self.config, + self._chunk_grid, indexer, value, prototype=prototype, @@ -1770,6 +1660,7 @@ async def setitem( self.metadata, self.codec_pipeline, self.config, + self._chunk_grid, selection, value, prototype=prototype, @@ -1886,20 +1777,25 @@ def info(self) -> Any: Examples -------- - - >>> arr = await zarr.api.asynchronous.create( - ... path="array", shape=(3, 4, 5), chunks=(2, 2, 2)) + >>> import asyncio + >>> arr = asyncio.run( + ... zarr.api.asynchronous.create( + ... path="array", shape=(3, 4, 5), chunks=(2, 2, 2) + ... ) ... ) >>> arr.info Type : Array Zarr format : 3 - Data type : DataType.float64 + Data type : Float64(endianness='little') + Fill value : 0.0 Shape : (3, 4, 5) Chunk shape : (2, 2, 2) Order : C Read-only : False Store type : MemoryStore - Codecs : [{'endian': }] + Filters : () + Serializer : BytesCodec(endian='little') + Compressors : (ZstdCodec(level=0, checksum=False),) No. bytes : 480 """ return self._info() @@ -1926,6 +1822,7 @@ async def info_complete(self) -> Any: def _info( self, count_chunks_initialized: int | None = None, count_bytes_stored: int | None = None ) -> Any: + chunk_shape = self.chunks if self._chunk_grid.is_regular else None return ArrayInfo( _zarr_format=self.metadata.zarr_format, _data_type=self._zdtype, @@ -1933,7 +1830,7 @@ def _info( _shape=self.shape, _order=self.order, _shard_shape=self.shards, - _chunk_shape=self.chunks, + _chunk_shape=chunk_shape, _read_only=self.read_only, _compressors=self.compressors, _filters=self.filters, @@ -1947,7 +1844,7 @@ def _info( # TODO: Array can be a frozen data class again once property setters (e.g. shape) are removed @dataclass(frozen=False) -class Array(Generic[T_ArrayMetadata]): +class Array[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: """ A Zarr array. """ @@ -1977,150 +1874,10 @@ def config(self) -> ArrayConfig: """ return self.async_array.config - @classmethod - @deprecated("Use zarr.create_array instead.", category=ZarrDeprecationWarning) - def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: tuple[int, ...], - dtype: ZDTypeLike, - zarr_format: ZarrFormat = 3, - fill_value: Any | None = DEFAULT_FILL_VALUE, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: tuple[int, ...] | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, - # v2 only - chunks: tuple[int, ...] | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: MemoryOrder | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: CompressorLike = "auto", - # runtime - overwrite: bool = False, - config: ArrayConfigLike | None = None, - ) -> AnyArray: - """Creates a new Array instance from an initialized store. - - !!! warning "Deprecated" - `Array.create()` is deprecated since v3.0.0 and will be removed in a future release. - Use [`zarr.create_array`][] instead. - - Parameters - ---------- - store : StoreLike - The array store that has already been initialized. See the - [storage documentation in the user guide][user-guide-store-like] - for a description of all valid StoreLike values. - shape : tuple[int, ...] - The shape of the array. - dtype : ZDTypeLike - The data type of the array. - chunk_shape : tuple[int, ...], optional - The shape of the Array's chunks. - Zarr format 3 only. Zarr format 2 arrays should use `chunks` instead. - If not specified, default are guessed based on the shape and dtype. - chunk_key_encoding : ChunkKeyEncodingLike, optional - A specification of how the chunk keys are represented in storage. - Zarr format 3 only. Zarr format 2 arrays should use `dimension_separator` instead. - Default is ``("default", "/")``. - codecs : Sequence of Codecs or dicts, optional - An iterable of Codec or dict serializations of Codecs. The elements of - this collection specify the transformation from array values to stored bytes. - Zarr format 3 only. Zarr format 2 arrays should use ``filters`` and ``compressor`` instead. - - If no codecs are provided, default codecs will be used: - - - For numeric arrays, the default is ``BytesCodec`` and ``ZstdCodec``. - - For Unicode strings, the default is ``VLenUTF8Codec`` and ``ZstdCodec``. - - For bytes or objects, the default is ``VLenBytesCodec`` and ``ZstdCodec``. - dimension_names : Iterable[str | None], optional - The names of the dimensions (default is None). - Zarr format 3 only. Zarr format 2 arrays should not use this parameter. - chunks : tuple[int, ...], optional - The shape of the array's chunks. - Zarr format 2 only. Zarr format 3 arrays should use ``chunk_shape`` instead. - If not specified, default are guessed based on the shape and dtype. - dimension_separator : Literal[".", "/"], optional - The dimension separator (default is "."). - Zarr format 2 only. Zarr format 3 arrays should use ``chunk_key_encoding`` instead. - order : Literal["C", "F"], optional - The memory of the array (default is "C"). - If ``zarr_format`` is 2, this parameter sets the memory order of the array. - If ``zarr_format`` is 3, then this parameter is deprecated, because memory order - is a runtime parameter for Zarr 3 arrays. The recommended way to specify the memory - order for Zarr 3 arrays is via the ``config`` parameter, e.g. ``{'order': 'C'}``. - - filters : Iterable[Codec] | Literal["auto"], optional - Iterable of filters to apply to each chunk of the array, in order, before serializing that - chunk to bytes. - - For Zarr format 3, a "filter" is a codec that takes an array and returns an array, - and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a - dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. - - For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. - - The default value of ``"auto"`` instructs Zarr to use a default used based on the data - type of the array and the Zarr format specified. For all data types in Zarr V3, and most - data types in Zarr V2, the default filters are empty. The only cases where default filters - are not empty is when the Zarr format is 2, and the data type is a variable-length data type like - [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, - the default filters contains a single element which is a codec specific to that particular data type. - - To create an array with no filters, provide an empty iterable or the value ``None``. - compressor : dict[str, JSON], optional - Primary compressor to compress chunk data. - Zarr format 2 only. Zarr format 3 arrays should use ``codecs`` instead. - - If no ``compressor`` is provided, a default compressor will be used: - - - For numeric arrays, the default is ``ZstdCodec``. - - For Unicode strings, the default is ``VLenUTF8Codec``. - - For bytes or objects, the default is ``VLenBytesCodec``. - - These defaults can be changed by modifying the value of ``array.v2_default_compressor`` in [`zarr.config`][zarr.config]. - overwrite : bool, optional - Whether to raise an error if the store already exists (default is False). - - Returns - ------- - Array - Array created from the store. - """ - return cls._create( - store, - # v2 and v3 - shape=shape, - dtype=dtype, - zarr_format=zarr_format, - attributes=attributes, - fill_value=fill_value, - # v3 only - chunk_shape=chunk_shape, - chunk_key_encoding=chunk_key_encoding, - codecs=codecs, - dimension_names=dimension_names, - # v2 only - chunks=chunks, - dimension_separator=dimension_separator, - order=order, - filters=filters, - compressor=compressor, - # runtime - overwrite=overwrite, - config=config, - ) + @property + def _chunk_grid(self) -> ChunkGrid: + """The chunk grid for this array, bound to the array's shape.""" + return self.async_array._chunk_grid @classmethod def _create( @@ -2142,7 +1899,7 @@ def _create( | None ) = None, codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, # v2 only chunks: tuple[int, ...] | None = None, dimension_separator: Literal[".", "/"] | None = None, @@ -2268,8 +2025,8 @@ def chunks(self) -> tuple[int, ...]: """Returns a tuple of integers describing the length of each dimension of a chunk of the array. If sharding is used the inner chunk shape is returned. - Only defined for arrays using using `RegularChunkGrid`. - If array doesn't use `RegularChunkGrid`, `NotImplementedError` is raised. + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. Returns ------- @@ -2278,13 +2035,63 @@ def chunks(self) -> tuple[int, ...]: """ return self.async_array.chunks + @property + def read_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of chunks used for reading, clipped to the array extent. + + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + When sharding is used, returns the inner chunk sizes. + Otherwise, returns the outer chunk sizes (same as `write_chunk_sizes`). + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> import zarr + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.read_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + return self.async_array.read_chunk_sizes + + @property + def write_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of storage chunks, clipped to the array extent. + + Always returns the outer chunk sizes, regardless of sharding. + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> import zarr + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.write_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + return self.async_array.write_chunk_sizes + @property def shards(self) -> tuple[int, ...] | None: """Returns a tuple of integers describing the length of each dimension of a shard of the array. Returns None if sharding is not used. - Only defined for arrays using using `RegularChunkGrid`. - If array doesn't use `RegularChunkGrid`, `NotImplementedError` is raised. + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. Returns ------- @@ -2374,7 +2181,7 @@ def filters(self) -> tuple[Numcodec, ...] | tuple[ArrayArrayCodec, ...]: return self.async_array.filters @property - def serializer(self) -> None | ArrayBytesCodec: + def serializer(self) -> ArrayBytesCodec | None: """ Array-to-bytes codec to use for serializing the chunks into bytes. """ @@ -2407,7 +2214,7 @@ def cdata_shape(self) -> tuple[int, ...]: When sharding is used, this counts inner chunks (not shards) per dimension. """ - return self.async_array._chunk_grid_shape + return self._chunk_grid_shape @property def _chunk_grid_shape(self) -> tuple[int, ...]: @@ -2479,7 +2286,7 @@ def nbytes(self) -> int: ----- This value is calculated by multiplying the number of elements in the array and the size of each element, the latter of which is determined by the dtype of the array. - For this reason, ``nbytes`` will likely be inaccurate for arrays with variable-length + For this reason, `nbytes` will likely be inaccurate for arrays with variable-length dtypes. It is not possible to determine the size of an array with variable-length elements from the shape and dtype alone. """ @@ -2493,7 +2300,7 @@ def nchunks_initialized(self) -> int: This value is calculated as the product of the number of initialized shards and the number of chunks per shard. For arrays that do not use sharding, the number of chunks per shard is effectively 1, and in that case the number of chunks initialized is the same as the number of stored objects associated with an - array. For a direct count of the number of initialized stored objects, see ``nshards_initialized``. + array. For a direct count of the number of initialized stored objects, see `nshards_initialized`. Returns ------- @@ -2502,7 +2309,7 @@ def nchunks_initialized(self) -> int: Examples -------- - >>> arr = zarr.create_array(store={}, shape=(10,), chunks=(1,), shards=(2,)) + >>> arr = zarr.create_array(store={}, dtype="i1", shape=(10,), chunks=(1,), shards=(2,)) >>> arr.nchunks_initialized 0 >>> arr[:5] = 1 @@ -2524,11 +2331,11 @@ def _nshards_initialized(self) -> int: Examples -------- - >>> arr = await zarr.create(shape=(10,), chunks=(2,)) + >>> arr = zarr.create(shape=(10,), chunks=(2,)) >>> arr._nshards_initialized 0 >>> arr[:5] = 1 - >>> arr._nshard_initialized + >>> arr._nshards_initialized 3 """ return sync(self.async_array._nshards_initialized()) @@ -2673,7 +2480,7 @@ def __array__( raise ValueError(msg) arr = self[...] - arr_np: NDArrayLike = np.array(arr, dtype=dtype) + arr_np = np.array(arr, dtype=dtype) if dtype is not None: arr_np = arr_np.astype(dtype) @@ -2696,66 +2503,66 @@ def __getitem__(self, selection: Selection) -> NDArrayLikeOrScalar: Examples -------- - Setup a 1-dimensional array:: + Setup a 1-dimensional array: >>> import zarr >>> import numpy as np >>> data = np.arange(100, dtype="uint16") >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=(10,), - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=(10,), + ... dtype=data.dtype, + ... ) >>> z[:] = data - Retrieve a single item:: + Retrieve a single item: >>> z[5] - 5 + array(5, dtype=uint16) - Retrieve a region via slicing:: + Retrieve a region via slicing: >>> z[:5] - array([0, 1, 2, 3, 4]) + array([0, 1, 2, 3, 4], dtype=uint16) >>> z[-5:] - array([95, 96, 97, 98, 99]) + array([95, 96, 97, 98, 99], dtype=uint16) >>> z[5:10] - array([5, 6, 7, 8, 9]) + array([5, 6, 7, 8, 9], dtype=uint16) >>> z[5:10:2] - array([5, 7, 9]) + array([5, 7, 9], dtype=uint16) >>> z[::2] - array([ 0, 2, 4, ..., 94, 96, 98]) + array([ 0, 2, 4, ..., 94, 96, 98], dtype=uint16) - Load the entire array into memory:: + Load the entire array into memory: >>> z[...] - array([ 0, 1, 2, ..., 97, 98, 99]) + array([ 0, 1, 2, ..., 97, 98, 99], dtype=uint16) - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> data = np.arange(100, dtype="uint16").reshape(10, 10) >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=(10, 10), - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=(10, 10), + ... dtype=data.dtype, + ... ) >>> z[:] = data - Retrieve an item:: + Retrieve an item: >>> z[2, 2] - 22 + array(22, dtype=uint16) - Retrieve a region via slicing:: + Retrieve a region via slicing: >>> z[1:3, 1:3] array([[11, 12], - [21, 22]]) + [21, 22]], dtype=uint16) >>> z[1:3, :] array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) + [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]], dtype=uint16) >>> z[:, 1:3] array([[ 1, 2], [11, 12], @@ -2766,19 +2573,19 @@ def __getitem__(self, selection: Selection) -> NDArrayLikeOrScalar: [61, 62], [71, 72], [81, 82], - [91, 92]]) + [91, 92]], dtype=uint16) >>> z[0:5:2, 0:5:2] array([[ 0, 2, 4], [20, 22, 24], - [40, 42, 44]]) + [40, 42, 44]], dtype=uint16) >>> z[::2, ::2] array([[ 0, 2, 4, 6, 8], [20, 22, 24, 26, 28], [40, 42, 44, 46, 48], [60, 62, 64, 66, 68], - [80, 82, 84, 86, 88]]) + [80, 82, 84, 86, 88]], dtype=uint16) - Load the entire array into memory:: + Load the entire array into memory: >>> z[...] array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], @@ -2790,7 +2597,7 @@ def __getitem__(self, selection: Selection) -> NDArrayLikeOrScalar: [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74, 75, 76, 77, 78, 79], [80, 81, 82, 83, 84, 85, 86, 87, 88, 89], - [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]) + [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]], dtype=uint16) Notes ----- @@ -2823,8 +2630,8 @@ def __getitem__(self, selection: Selection) -> NDArrayLikeOrScalar: [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], [get_block_selection][zarr.Array.get_block_selection], [set_block_selection][zarr.Array.set_block_selection], [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], [blocks][zarr.Array.blocks], [__setitem__][zarr.Array.__setitem__] - """ + fields, pure_selection = pop_fields(selection) if is_pure_fancy_indexing(pure_selection, self.ndim): return self.vindex[cast("CoordinateSelection | MaskSelection", selection)] @@ -2846,43 +2653,43 @@ def __setitem__(self, selection: Selection, value: npt.ArrayLike) -> None: Examples -------- - Setup a 1-dimensional array:: + Setup a 1-dimensional array: >>> import zarr >>> z = zarr.zeros( - >>> shape=(100,), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5,), - >>> dtype="i4", - >>> ) + ... shape=(100,), + ... store={}, + ... chunk_shape=(5,), + ... dtype="i4", + ... ) - Set all array elements to the same scalar value:: + Set all array elements to the same scalar value: >>> z[...] = 42 >>> z[...] - array([42, 42, 42, ..., 42, 42, 42]) + array([42, 42, 42, ..., 42, 42, 42], dtype=int32) - Set a portion of the array:: + Set a portion of the array: >>> z[:10] = np.arange(10) >>> z[-10:] = np.arange(10)[::-1] >>> z[...] - array([ 0, 1, 2, ..., 2, 1, 0]) + array([ 0, 1, 2, ..., 2, 1, 0], dtype=int32) - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) - Set all array elements to the same scalar value:: + Set all array elements to the same scalar value: >>> z[...] = 42 - Set a portion of the array:: + Set a portion of the array: >>> z[0, :] = np.arange(z.shape[1]) >>> z[:, 0] = np.arange(z.shape[0]) @@ -2891,7 +2698,7 @@ def __setitem__(self, selection: Selection, value: npt.ArrayLike) -> None: [ 1, 42, 42, 42, 42], [ 2, 42, 42, 42, 42], [ 3, 42, 42, 42, 42], - [ 4, 42, 42, 42, 42]]) + [ 4, 42, 42, 42, 42]], dtype=int32) Notes ----- @@ -2932,6 +2739,12 @@ def __setitem__(self, selection: Selection, value: npt.ArrayLike) -> None: [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__] """ + # Converting a zarr Array to numpy here avoids a SyncError that occurs when + # value.__getitem__ is called inside the async codec pipeline (which already + # runs within a running event loop). np.asarray triggers Array.__array__, + # which reads the data synchronously before we enter the async context. + if isinstance(value, Array): + value = np.asarray(value) fields, pure_selection = pop_fields(selection) if is_pure_fancy_indexing(pure_selection, self.ndim): self.vindex[cast("CoordinateSelection | MaskSelection", selection)] = value @@ -2952,8 +2765,8 @@ def get_basic_selection( Parameters ---------- - selection : tuple - A tuple specifying the requested item or region for each dimension of the + selection : BasicSelection + A selection specifying the requested item or region for each dimension of the array. May be any combination of int and/or slice or ellipsis for multidimensional arrays. out : NDBuffer, optional If given, load the selected data directly into this buffer. @@ -2970,67 +2783,67 @@ def get_basic_selection( Examples -------- - Setup a 1-dimensional array:: + Setup a 1-dimensional array: >>> import zarr >>> import numpy as np >>> data = np.arange(100, dtype="uint16") >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=(3,), - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=(3,), + ... dtype=data.dtype, + ... ) >>> z[:] = data - Retrieve a single item:: + Retrieve a single item: >>> z.get_basic_selection(5) - 5 + np.uint16(5) - Retrieve a region via slicing:: + Retrieve a region via slicing: >>> z.get_basic_selection(slice(5)) - array([0, 1, 2, 3, 4]) + array([0, 1, 2, 3, 4], dtype=uint16) >>> z.get_basic_selection(slice(-5, None)) - array([95, 96, 97, 98, 99]) + array([95, 96, 97, 98, 99], dtype=uint16) >>> z.get_basic_selection(slice(5, 10)) - array([5, 6, 7, 8, 9]) + array([5, 6, 7, 8, 9], dtype=uint16) >>> z.get_basic_selection(slice(5, 10, 2)) - array([5, 7, 9]) + array([5, 7, 9], dtype=uint16) >>> z.get_basic_selection(slice(None, None, 2)) - array([ 0, 2, 4, ..., 94, 96, 98]) + array([ 0, 2, 4, ..., 94, 96, 98], dtype=uint16) - Setup a 3-dimensional array:: + Setup a 3-dimensional array: >>> data = np.arange(1000).reshape(10, 10, 10) >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=(5, 5, 5), - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=(5, 5, 5), + ... dtype=data.dtype, + ... ) >>> z[:] = data - Retrieve an item:: + Retrieve an item: >>> z.get_basic_selection((1, 2, 3)) - 123 + np.int64(123) - Retrieve a region via slicing and Ellipsis:: + Retrieve a region via slicing and Ellipsis: >>> z.get_basic_selection((slice(1, 3), slice(1, 3), 0)) array([[110, 120], [210, 220]]) - >>> z.get_basic_selection(0, (slice(1, 3), slice(None))) + >>> z.get_basic_selection((0, slice(1, 3), slice(None))) array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) - >>> z.get_basic_selection((..., 5)) - array([[ 2 12 22 32 42 52 62 72 82 92] - [102 112 122 132 142 152 162 172 182 192] + >>> z.get_basic_selection((..., 2)) + array([[ 2, 12, 22, 32, 42, 52, 62, 72, 82, 92], + [102, 112, 122, 132, 142, 152, 162, 172, 182, 192], ... - [802 812 822 832 842 852 862 872 882 892] - [902 912 922 932 942 952 962 972 982 992]] + [802, 812, 822, 832, 842, 852, 862, 872, 882, 892], + [902, 912, 922, 932, 942, 952, 962, 972, 982, 992]]) Notes ----- @@ -3064,7 +2877,7 @@ def get_basic_selection( prototype = default_buffer_prototype() return sync( self.async_array._get_selection( - BasicIndexer(selection, self.shape, self.metadata.chunk_grid), + BasicIndexer(selection, self.shape, self._chunk_grid), out=out, fields=fields, prototype=prototype, @@ -3097,43 +2910,43 @@ def set_basic_selection( Examples -------- - Setup a 1-dimensional array:: + Setup a 1-dimensional array: >>> import zarr >>> z = zarr.zeros( - >>> shape=(100,), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(100,), - >>> dtype="i4", - >>> ) + ... shape=(100,), + ... store={}, + ... chunk_shape=(100,), + ... dtype="i4", + ... ) - Set all array elements to the same scalar value:: + Set all array elements to the same scalar value: >>> z.set_basic_selection(..., 42) >>> z[...] - array([42, 42, 42, ..., 42, 42, 42]) + array([42, 42, 42, ..., 42, 42, 42], dtype=int32) - Set a portion of the array:: + Set a portion of the array: >>> z.set_basic_selection(slice(10), np.arange(10)) >>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1]) >>> z[...] - array([ 0, 1, 2, ..., 2, 1, 0]) + array([ 0, 1, 2, ..., 2, 1, 0], dtype=int32) - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) - Set all array elements to the same scalar value:: + Set all array elements to the same scalar value: >>> z.set_basic_selection(..., 42) - Set a portion of the array:: + Set a portion of the array: >>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1])) >>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0])) @@ -3142,7 +2955,7 @@ def set_basic_selection( [ 1, 42, 42, 42, 42], [ 2, 42, 42, 42, 42], [ 3, 42, 42, 42, 42], - [ 4, 42, 42, 42, 42]]) + [ 4, 42, 42, 42, 42]], dtype=int32) Notes ----- @@ -3171,7 +2984,7 @@ def set_basic_selection( """ if prototype is None: prototype = default_buffer_prototype() - indexer = BasicIndexer(selection, self.shape, self.metadata.chunk_grid) + indexer = BasicIndexer(selection, self.shape, self._chunk_grid) sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) def get_orthogonal_selection( @@ -3208,21 +3021,21 @@ def get_orthogonal_selection( Examples -------- - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> import zarr >>> import numpy as np >>> data = np.arange(100).reshape(10, 10) >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=data.shape, - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=data.shape, + ... dtype=data.dtype, + ... ) >>> z[:] = data Retrieve rows and columns via any combination of int, slice, integer array and/or - Boolean array:: + Boolean array: >>> z.get_orthogonal_selection(([1, 4], slice(None))) array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], @@ -3249,7 +3062,7 @@ def get_orthogonal_selection( [41, 44]]) For convenience, the orthogonal selection functionality is also available via the - `oindex` property, e.g.:: + `oindex` property, e.g.: >>> z.oindex[[1, 4], :] array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], @@ -3299,7 +3112,7 @@ def get_orthogonal_selection( """ if prototype is None: prototype = default_buffer_prototype() - indexer = OrthogonalIndexer(selection, self.shape, self.metadata.chunk_grid) + indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) return sync( self.async_array._get_selection( indexer=indexer, out=out, fields=fields, prototype=prototype @@ -3332,18 +3145,18 @@ def set_orthogonal_selection( Examples -------- - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> import zarr >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) - Set data for a selection of rows:: + Set data for a selection of rows: >>> z.set_orthogonal_selection(([1, 4], slice(None)), 1) >>> z[...] @@ -3351,9 +3164,9 @@ def set_orthogonal_selection( [1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], - [1, 1, 1, 1, 1]]) + [1, 1, 1, 1, 1]], dtype=int32) - Set data for a selection of columns:: + Set data for a selection of columns: >>> z.set_orthogonal_selection((slice(None), [1, 4]), 2) >>> z[...] @@ -3361,9 +3174,9 @@ def set_orthogonal_selection( [1, 2, 1, 1, 2], [0, 2, 0, 0, 2], [0, 2, 0, 0, 2], - [1, 2, 1, 1, 2]]) + [1, 2, 1, 1, 2]], dtype=int32) - Set data for a selection of rows and columns:: + Set data for a selection of rows and columns: >>> z.set_orthogonal_selection(([1, 4], [1, 4]), 3) >>> z[...] @@ -3371,9 +3184,9 @@ def set_orthogonal_selection( [1, 3, 1, 1, 3], [0, 2, 0, 0, 2], [0, 2, 0, 0, 2], - [1, 3, 1, 1, 3]]) + [1, 3, 1, 1, 3]], dtype=int32) - Set data from a 2D array:: + Set data from a 2D array: >>> values = np.arange(10).reshape(2, 5) >>> z.set_orthogonal_selection(([0, 3], ...), values) @@ -3382,10 +3195,9 @@ def set_orthogonal_selection( [1, 3, 1, 1, 3], [0, 2, 0, 0, 2], [5, 6, 7, 8, 9], - [1, 3, 1, 1, 3]]) + [1, 3, 1, 1, 3]], dtype=int32) - For convenience, this functionality is also available via the `oindex` property. - E.g.:: + For convenience, this functionality is also available via the `oindex` property: >>> z.oindex[[1, 4], [1, 4]] = 4 >>> z[...] @@ -3393,7 +3205,7 @@ def set_orthogonal_selection( [1, 4, 1, 1, 4], [0, 2, 0, 0, 2], [5, 6, 7, 8, 9], - [1, 4, 1, 1, 4]]) + [1, 4, 1, 1, 4]], dtype=int32) Notes ----- @@ -3418,7 +3230,7 @@ def set_orthogonal_selection( """ if prototype is None: prototype = default_buffer_prototype() - indexer = OrthogonalIndexer(selection, self.shape, self.metadata.chunk_grid) + indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) return sync( self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype) ) @@ -3455,20 +3267,20 @@ def get_mask_selection( Examples -------- - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> import zarr >>> import numpy as np >>> data = np.arange(100).reshape(10, 10) >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=data.shape, - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=data.shape, + ... dtype=data.dtype, + ... ) >>> z[:] = data - Retrieve items by specifying a mask:: + Retrieve items by specifying a mask: >>> sel = np.zeros_like(z, dtype=bool) >>> sel[1, 1] = True @@ -3477,7 +3289,7 @@ def get_mask_selection( array([11, 44]) For convenience, the mask selection functionality is also available via the - `vindex` property, e.g.:: + `vindex` property: >>> z.vindex[sel] array([11, 44]) @@ -3506,7 +3318,7 @@ def get_mask_selection( if prototype is None: prototype = default_buffer_prototype() - indexer = MaskIndexer(mask, self.shape, self.metadata.chunk_grid) + indexer = MaskIndexer(mask, self.shape, self._chunk_grid) return sync( self.async_array._get_selection( indexer=indexer, out=out, fields=fields, prototype=prototype @@ -3538,17 +3350,17 @@ def set_mask_selection( Examples -------- - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> import zarr >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) - Set data for a selection of items:: + Set data for a selection of items: >>> sel = np.zeros_like(z, dtype=bool) >>> sel[1, 1] = True @@ -3559,10 +3371,9 @@ def set_mask_selection( [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], - [0, 0, 0, 0, 1]]) + [0, 0, 0, 0, 1]], dtype=int32) - For convenience, this functionality is also available via the `vindex` property. - E.g.:: + For convenience, this functionality is also available via the `vindex` property: >>> z.vindex[sel] = 2 >>> z[...] @@ -3570,7 +3381,7 @@ def set_mask_selection( [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], - [0, 0, 0, 0, 2]]) + [0, 0, 0, 0, 2]], dtype=int32) Notes ----- @@ -3596,7 +3407,7 @@ def set_mask_selection( """ if prototype is None: prototype = default_buffer_prototype() - indexer = MaskIndexer(mask, self.shape, self.metadata.chunk_grid) + indexer = MaskIndexer(mask, self.shape, self._chunk_grid) sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) def get_coordinate_selection( @@ -3629,29 +3440,29 @@ def get_coordinate_selection( Examples -------- - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> import zarr >>> import numpy as np >>> data = np.arange(0, 100, dtype="uint16").reshape((10, 10)) >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=(3, 3), - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=(3, 3), + ... dtype=data.dtype, + ... ) >>> z[:] = data - Retrieve items by specifying their coordinates:: + Retrieve items by specifying their coordinates: >>> z.get_coordinate_selection(([1, 4], [1, 4])) - array([11, 44]) + array([11, 44], dtype=uint16) For convenience, the coordinate selection functionality is also available via the - `vindex` property, e.g.:: + `vindex` property: >>> z.vindex[[1, 4], [1, 4]] - array([11, 44]) + array([11, 44], dtype=uint16) Notes ----- @@ -3684,7 +3495,7 @@ def get_coordinate_selection( """ if prototype is None: prototype = default_buffer_prototype() - indexer = CoordinateIndexer(selection, self.shape, self.metadata.chunk_grid) + indexer = CoordinateIndexer(selection, self.shape, self._chunk_grid) out_array = sync( self.async_array._get_selection( indexer=indexer, out=out, fields=fields, prototype=prototype @@ -3719,17 +3530,17 @@ def set_coordinate_selection( Examples -------- - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> import zarr >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) - Set data for a selection of items:: + Set data for a selection of items: >>> z.set_coordinate_selection(([1, 4], [1, 4]), 1) >>> z[...] @@ -3737,10 +3548,9 @@ def set_coordinate_selection( [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], - [0, 0, 0, 0, 1]]) + [0, 0, 0, 0, 1]], dtype=int32) - For convenience, this functionality is also available via the `vindex` property. - E.g.:: + For convenience, this functionality is also available via the `vindex` property: >>> z.vindex[[1, 4], [1, 4]] = 2 >>> z[...] @@ -3748,7 +3558,7 @@ def set_coordinate_selection( [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], - [0, 0, 0, 0, 2]]) + [0, 0, 0, 0, 2]], dtype=int32) Notes ----- @@ -3777,7 +3587,7 @@ def set_coordinate_selection( if prototype is None: prototype = default_buffer_prototype() # setup indexer - indexer = CoordinateIndexer(selection, self.shape, self.metadata.chunk_grid) + indexer = CoordinateIndexer(selection, self.shape, self._chunk_grid) # handle value - need ndarray-like flatten value if not is_scalar(value, self.dtype): @@ -3831,40 +3641,40 @@ def get_block_selection( Examples -------- - Setup a 2-dimensional array:: + Setup a 2-dimensional array: >>> import zarr >>> import numpy as np >>> data = np.arange(0, 100, dtype="uint16").reshape((10, 10)) >>> z = zarr.create_array( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunks=(3, 3), - >>> dtype=data.dtype, - >>> ) + ... {}, + ... shape=data.shape, + ... chunks=(3, 3), + ... dtype=data.dtype, + ... ) >>> z[:] = data - Retrieve items by specifying their block coordinates:: + Retrieve items by specifying their block coordinates: >>> z.get_block_selection((1, slice(None))) array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) + [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]], dtype=uint16) - Which is equivalent to:: + Which is equivalent to: >>> z[3:6, :] array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) + [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]], dtype=uint16) For convenience, the block selection functionality is also available via the - `blocks` property, e.g.:: + `blocks` property: >>> z.blocks[1] array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) + [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]], dtype=uint16) Notes ----- @@ -3874,13 +3684,12 @@ def get_block_selection( Slices are supported. However, only with a step size of one. - Block index arrays may be multidimensional to index multidimensional arrays. - For example:: + Block index arrays may be multidimensional to index multidimensional arrays: >>> z.blocks[0, 1:3] array([[ 3, 4, 5, 6, 7, 8], [13, 14, 15, 16, 17, 18], - [23, 24, 25, 26, 27, 28]]) + [23, 24, 25, 26, 27, 28]], dtype=uint16) Related ------- @@ -3899,7 +3708,7 @@ def get_block_selection( """ if prototype is None: prototype = default_buffer_prototype() - indexer = BlockIndexer(selection, self.shape, self.metadata.chunk_grid) + indexer = BlockIndexer(selection, self.shape, self._chunk_grid) return sync( self.async_array._get_selection( indexer=indexer, out=out, fields=fields, prototype=prototype @@ -3932,17 +3741,17 @@ def set_block_selection( Examples -------- - Set up a 2-dimensional array:: + Set up a 2-dimensional array: >>> import zarr >>> z = zarr.zeros( - >>> shape=(6, 6), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(2, 2), - >>> dtype="i4", - >>> ) + ... shape=(6, 6), + ... store={}, + ... chunk_shape=(2, 2), + ... dtype="i4", + ... ) - Set data for a selection of items:: + Set data for a selection of items: >>> z.set_block_selection((1, 0), 1) >>> z[...] @@ -3951,10 +3760,9 @@ def set_block_selection( [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0]]) + [0, 0, 0, 0, 0, 0]], dtype=int32) - For convenience, this functionality is also available via the `blocks` property. - E.g.:: + For convenience, this functionality is also available via the `blocks` property: >>> z.blocks[2, 1] = 4 >>> z[...] @@ -3963,7 +3771,7 @@ def set_block_selection( [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 4, 4, 0, 0], - [0, 0, 4, 4, 0, 0]]) + [0, 0, 4, 4, 0, 0]], dtype=int32) >>> z.blocks[:, 2] = 7 >>> z[...] @@ -3972,7 +3780,7 @@ def set_block_selection( [1, 1, 0, 0, 7, 7], [1, 1, 0, 0, 7, 7], [0, 0, 4, 4, 7, 7], - [0, 0, 4, 4, 7, 7]]) + [0, 0, 4, 4, 7, 7]], dtype=int32) Notes ----- @@ -4000,7 +3808,7 @@ def set_block_selection( """ if prototype is None: prototype = default_buffer_prototype() - indexer = BlockIndexer(selection, self.shape, self.metadata.chunk_grid) + indexer = BlockIndexer(selection, self.shape, self._chunk_grid) sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) @property @@ -4090,7 +3898,7 @@ def append(self, data: npt.ArrayLike, axis: int = 0) -> tuple[int, ...]: -------- >>> import numpy as np >>> import zarr - >>> a = np.arange(10000000, dtype='i4').reshape(10000, 1000) + >>> a = np.arange(10000000, dtype="i4").reshape(10000, 1000) >>> z = zarr.array(a, chunks=(1000, 100)) >>> z.shape (10000, 1000) @@ -4154,13 +3962,16 @@ def info(self) -> Any: >>> arr.info Type : Array Zarr format : 3 - Data type : DataType.float32 + Data type : Float32(endianness='little') + Fill value : 0.0 Shape : (10,) Chunk shape : (2,) Order : C Read-only : False Store type : MemoryStore - Codecs : [BytesCodec(endian=)] + Filters : () + Serializer : BytesCodec(endian='little') + Compressors : (ZstdCodec(level=0, checksum=False),) No. bytes : 40 """ return self.async_array.info @@ -4169,7 +3980,7 @@ def info_complete(self) -> Any: """ Returns all the information about an array, including information from the Store. - In addition to the statically known information like ``name`` and ``zarr_format``, + In addition to the statically known information like `name` and `zarr_format`, this includes additional information like the size of the array in bytes and the number of chunks written. @@ -4213,14 +4024,18 @@ async def _shards_initialized( x async for x in array.store_path.store.list_prefix(prefix=array.store_path.path) ] store_contents_relative = [ - _relativize_path(path=key, prefix=array.store_path.path) for key in store_contents + _relativize_path(path=key, prefix=array.store_path.path) + for key in store_contents + # obstore can include a directory marker whose key matches the listed prefix; + # it is not an initialized shard and must be excluded before relativizing. + if array.store_path.path == "" or key != array.store_path.path ] return tuple( chunk_key for chunk_key in array._iter_shard_keys() if chunk_key in store_contents_relative ) -FiltersLike: TypeAlias = ( +type FiltersLike = ( Iterable[dict[str, JSON] | ArrayArrayCodec | Numcodec] | ArrayArrayCodec | Iterable[Numcodec] @@ -4229,9 +4044,9 @@ async def _shards_initialized( | None ) # Union of acceptable types for users to pass in for both v2 and v3 compressors -CompressorLike: TypeAlias = dict[str, JSON] | BytesBytesCodec | Numcodec | Literal["auto"] | None +type CompressorLike = dict[str, JSON] | BytesBytesCodec | Numcodec | Literal["auto"] | None -CompressorsLike: TypeAlias = ( +type CompressorsLike = ( Iterable[dict[str, JSON] | BytesBytesCodec | Numcodec] | Mapping[str, JSON] | BytesBytesCodec @@ -4239,15 +4054,15 @@ async def _shards_initialized( | Literal["auto"] | None ) -SerializerLike: TypeAlias = dict[str, JSON] | ArrayBytesCodec | Literal["auto"] +type SerializerLike = dict[str, JSON] | ArrayBytesCodec | Literal["auto"] class ShardsConfigParam(TypedDict): shape: tuple[int, ...] - index_location: ShardingCodecIndexLocation | None + index_location: IndexLocation | None -ShardsLike: TypeAlias = tuple[int, ...] | ShardsConfigParam | Literal["auto"] +type ShardsLike = tuple[int, ...] | Sequence[Sequence[int]] | ShardsConfigParam | Literal["auto"] async def from_array( @@ -4256,8 +4071,8 @@ async def from_array( data: AnyArray | npt.ArrayLike, write_data: bool = True, name: str | None = None, - chunks: Literal["auto", "keep"] | tuple[int, ...] = "keep", - shards: ShardsLike | None | Literal["keep"] = "keep", + chunks: ChunksLike | Literal["auto", "keep"] = "keep", + shards: ShardsLike | Literal["keep"] | None = "keep", filters: FiltersLike | Literal["keep"] = "keep", compressors: CompressorsLike | Literal["keep"] = "keep", serializer: SerializerLike | Literal["keep"] = "keep", @@ -4266,7 +4081,7 @@ async def from_array( zarr_format: ZarrFormat | None = None, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, overwrite: bool = False, config: ArrayConfigLike | None = None, @@ -4283,18 +4098,22 @@ async def from_array( The array to copy. write_data : bool, default True Whether to copy the data from the input array to the new array. - If ``write_data`` is ``False``, the new array will be created with the same metadata as the + If `write_data` is `False`, the new array will be created with the same metadata as the input array, but without any data. name : str or None, optional - The name of the array within the store. If ``name`` is ``None``, the array will be located + The name of the array within the store. If `name` is `None`, the array will be located at the root of the store. - chunks : tuple[int, ...] or "auto" or "keep", optional + chunks : tuple[int, ...] or Sequence[Sequence[int]] or "auto" or "keep", optional Chunk shape of the array. Following values are supported: - "auto": Automatically determine the chunk shape based on the array's shape and dtype. - - "keep": Retain the chunk shape of the data array if it is a zarr Array. - - tuple[int, ...]: A tuple of integers representing the chunk shape. + - "keep": Retain the chunk grid of the data array if it is a zarr Array. + - tuple[int, ...]: A tuple of integers representing the chunk shape (regular grid). + - Sequence[Sequence[int]]: Per-dimension chunk edge lists (rectilinear grid). + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. If not specified, defaults to "keep" if data is a zarr Array, otherwise "auto". shards : tuple[int, ...], optional @@ -4316,24 +4135,24 @@ async def from_array( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"keep"`` instructs Zarr to infer ``filters`` from ``data``. - If that inference is not possible, Zarr will fall back to the behavior specified by ``"auto"``, + The default value of `"keep"` instructs Zarr to infer `filters` from `data`. + If that inference is not possible, Zarr will fall back to the behavior specified by `"auto"`, which is to choose default filters based on the data type of the array and the Zarr format specified. - For all data types in Zarr V3, and most data types in Zarr V2, the default filters are the empty tuple ``()``. + For all data types in Zarr V3, and most data types in Zarr V2, the default filters are the empty tuple `()`. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters is a tuple with a single element which is a codec specific to that particular data type. - To create an array with no filters, provide an empty iterable or the value ``None``. + To create an array with no filters, provide an empty iterable or the value `None`. compressors : Iterable[Codec] or "auto" or "keep", optional List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes. For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. + returns another bytestream. Multiple compressors may be provided for Zarr format 3. For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. @@ -4344,28 +4163,28 @@ async def from_array( - "auto": Automatically determine the compressors based on the array's dtype. - "keep": Retain the compressors of the input array if it is a zarr Array. - If no ``compressors`` are provided, defaults to "keep" if data is a zarr Array, otherwise "auto". + If no `compressors` are provided, defaults to "keep" if data is a zarr Array, otherwise "auto". serializer : dict[str, JSON] | ArrayBytesCodec or "auto" or "keep", optional Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. Following values are supported: - - dict[str, JSON]: A dict representation of an ``ArrayBytesCodec``. - - ArrayBytesCodec: An instance of ``ArrayBytesCodec``. + - dict[str, JSON]: A dict representation of an `ArrayBytesCodec`. + - ArrayBytesCodec: An instance of `ArrayBytesCodec`. - "auto": a default serializer will be used. These defaults can be changed by modifying the value of - ``array.v3_default_serializer`` in [`zarr.config`][zarr.config]. + `array.v3_default_serializer` in [`zarr.config`][zarr.config]. - "keep": Retain the serializer of the input array if it is a zarr Array. fill_value : Any, optional Fill value for the array. If not specified, defaults to the fill value of the data array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory - order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. If not specified, defaults to the memory order of the data array. zarr_format : {2, 3}, optional The zarr format to use when saving. @@ -4375,8 +4194,8 @@ async def from_array( If not specified, defaults to the attributes of the data array. chunk_key_encoding : ChunkKeyEncoding, optional A specification of how the chunk keys are represented in storage. - For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. - For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. If not specified and the data array has the same zarr format as the target array, the chunk key encoding of the data array is used. dimension_names : Iterable[str | None] | None @@ -4398,48 +4217,49 @@ async def from_array( Examples -------- - Create an array from an existing Array:: + Create an array from an existing Array: + >>> import asyncio >>> import zarr - >>> store = zarr.storage.MemoryStore() - >>> store2 = zarr.storage.LocalStore('example.zarr') + >>> store = zarr.storage.LocalStore("example.zarr") >>> arr = zarr.create_array( - >>> store=store, - >>> shape=(100,100), - >>> chunks=(10,10), - >>> dtype='int32', - >>> fill_value=0) - >>> arr2 = await zarr.api.asynchronous.from_array(store2, data=arr) + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="int32", + ... fill_value=0, + ... ) + + >>> arr2 = asyncio.run(from_array(store, data=arr, overwrite=True)) + >>> arr2 + >>> asyncio.run(store.clear()) # Remove files generated by test + + Create an array from an existing NumPy array: - Create an array from an existing NumPy array:: - - >>> arr3 = await zarr.api.asynchronous.from_array( - >>> zarr.storage.MemoryStore(), - >>> data=np.arange(10000, dtype='i4').reshape(100, 100), - >>> ) - - - Create an array from any array-like object:: - - >>> arr4 = await zarr.api.asynchronous.from_array( - >>> zarr.storage.MemoryStore(), - >>> data=[[1, 2], [3, 4]], - >>> ) - - >>> await arr4.getitem(...) - array([[1, 2],[3, 4]]) - - Create an array from an existing Array without copying the data:: - - >>> arr5 = await zarr.api.asynchronous.from_array( - >>> zarr.storage.MemoryStore(), - >>> data=Array(arr4), - >>> write_data=False, - >>> ) - - >>> await arr5.getitem(...) - array([[0, 0],[0, 0]]) + >>> arr3 = asyncio.run( + ... from_array({}, data=np.arange(10000, dtype="i4").reshape(100, 100)) + ... ) + >>> arr3 + + + Create an array from any array-like object: + + >>> arr4 = asyncio.run(from_array({}, data=[[1, 2], [3, 4]])) + >>> arr4 + + >>> asyncio.run(arr4.getitem(...)) + array([[1, 2], + [3, 4]]) + + Create an array from an existing Array without copying the data: + + >>> arr5 = asyncio.run(from_array({}, data=Array(arr4), write_data=False)) + >>> arr5 + + >>> asyncio.run(arr5.getitem(...)) + array([[0, 0], + [0, 0]]) """ mode: Literal["a"] = "a" config_parsed = parse_array_config(config) @@ -4525,7 +4345,7 @@ async def init_array( store_path: StorePath, shape: ShapeLike, dtype: ZDTypeLike, - chunks: tuple[int, ...] | Literal["auto"] = "auto", + chunks: ChunksLike | Literal["auto"] = "auto", shards: ShardsLike | None = None, filters: FiltersLike = "auto", compressors: CompressorsLike = "auto", @@ -4535,7 +4355,7 @@ async def init_array( zarr_format: ZarrFormat | None = 3, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, overwrite: bool = False, config: ArrayConfigLike | None = None, ) -> AnyAsyncArray: @@ -4553,7 +4373,7 @@ async def init_array( Chunk shape of the array. If not specified, default are guessed based on the shape and dtype. shards : tuple[int, ...], optional - Shard shape of the array. The default value of ``None`` results in no sharding at all. + Shard shape of the array. The default value of `None` results in no sharding at all. filters : Iterable[Codec] | Literal["auto"], optional Iterable of filters to apply to each chunk of the array, in order, before serializing that chunk to bytes. @@ -4563,49 +4383,49 @@ async def init_array( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of `"auto"` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters contains a single element which is a codec specific to that particular data type. - To create an array with no filters, provide an empty iterable or the value ``None``. + To create an array with no filters, provide an empty iterable or the value `None`. compressors : Iterable[Codec] | Literal["auto"], optional List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes. - The default value of ``"auto"`` instructs Zarr to use a default of [`zarr.codecs.ZstdCodec`][]. + The default value of `"auto"` instructs Zarr to use a default of [`zarr.codecs.ZstdCodec`][]. - To create an array with no compressors, provide an empty iterable or the value ``None``. + To create an array with no compressors, provide an empty iterable or the value `None`. serializer : dict[str, JSON] | ArrayBytesCodec | Literal["auto"], optional Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. - The default value of ``"auto"`` instructs Zarr to use a default codec based on the data type of the array. + The default value of `"auto"` instructs Zarr to use a default codec based on the data type of the array. For most data types this default codec is [`zarr.codecs.BytesCodec`][]. For [`zarr.dtype.VariableLengthUTF8`][], the default codec is [`zarr.codecs.VlenUTF8Codec`][]. For [`zarr.dtype.VariableLengthBytes`][], the default codec is [`zarr.codecs.VlenBytesCodec`][]. fill_value : Any, optional Fill value for the array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory - order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. - If no ``order`` is provided, a default order will be used. - This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config]. + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If no `order` is provided, a default order will be used. + This default can be changed by modifying the value of `array.order` in [`zarr.config`][zarr.config]. zarr_format : {2, 3}, optional The zarr format to use when saving. attributes : dict, optional Attributes for the array. chunk_key_encoding : ChunkKeyEncodingLike, optional A specification of how the chunk keys are represented in storage. - For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. - For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. dimension_names : Iterable[str], optional The names of the dimensions (default is None). Zarr format 3 only. Zarr format 2 arrays should not use this parameter. @@ -4613,7 +4433,7 @@ async def init_array( Whether to overwrite an array with the same name in the store, if one exists. config : ArrayConfigLike or None, default=None Configuration for this array. - If ``None``, the default array runtime configuration will be used. This default + If `None`, the default array runtime configuration will be used. This default is stored in the global configuration object. Returns @@ -4625,36 +4445,48 @@ async def init_array( if zarr_format is None: zarr_format = _default_zarr_format() - from zarr.codecs.sharding import ShardingCodec, ShardingCodecIndexLocation + from zarr.codecs.sharding import ShardingCodec zdtype = parse_dtype(dtype, zarr_format=zarr_format) shape_parsed = parse_shapelike(shape) + item_size = zdtype.item_size if isinstance(zdtype, HasItemSize) else 1 chunk_key_encoding_parsed = _parse_chunk_key_encoding( chunk_key_encoding, zarr_format=zarr_format ) - if overwrite: - if store_path.store.supports_deletes: - await store_path.delete_dir() - else: - await ensure_no_existing_node(store_path, zarr_format=zarr_format) - else: - await ensure_no_existing_node(store_path, zarr_format=zarr_format) + await _prepare_overwrite(store_path, zarr_format=zarr_format, overwrite=overwrite) + + # Validate rectilinear chunks constraints + if _is_rectilinear_chunks(chunks): + if zarr_format == 2: + raise ValueError("Zarr format 2 does not support rectilinear chunk grids.") + if shards is not None: + raise ValueError( + "Rectilinear chunks with sharding is not supported. " + "Use rectilinear shards instead: " + "chunks=(inner_size, ...), shards=[[shard_sizes], ...]" + ) - item_size = 1 - if isinstance(zdtype, HasItemSize): - item_size = zdtype.item_size + # Normalize the user's chunks into canonical ChunksTuple form + + if chunks == "auto": + max_bytes = None if shards is None else SHARDED_INNER_CHUNK_MAX_BYTES + chunks_normalized = guess_chunks(shape_parsed, item_size, max_bytes=max_bytes) + else: + chunks_normalized = normalize_chunks_nd(chunks, shape_parsed) - shard_shape_parsed, chunk_shape_parsed = _auto_partition( + # Resolve chunks + shards into outer_chunks (grid metadata) and + # inner (sub-chunk structure for ShardingCodec, None if no sharding) + outer_chunks, inner = resolve_outer_and_inner_chunks( array_shape=shape_parsed, + chunks=chunks_normalized, shard_shape=shards, - chunk_shape=chunks, item_size=item_size, ) - chunks_out: tuple[int, ...] + meta: ArrayV2Metadata | ArrayV3Metadata if zarr_format == 2: - if shard_shape_parsed is not None: + if inner is not None: msg = ( "Zarr format 2 arrays can only be created with `shard_shape` set to `None`. " f"Got `shard_shape={shards}` instead." @@ -4678,7 +4510,7 @@ async def init_array( meta = AsyncArray._create_metadata_v2( shape=shape_parsed, dtype=zdtype, - chunks=chunk_shape_parsed, + chunks=as_regular_shape(outer_chunks), dimension_separator=chunk_key_encoding_parsed.separator, fill_value=fill_value, order=order_parsed, @@ -4694,35 +4526,32 @@ async def init_array( dtype=zdtype, ) sub_codecs = cast("tuple[Codec, ...]", (*array_array, array_bytes, *bytes_bytes)) + grid = create_chunk_grid_metadata(outer_chunks) codecs_out: tuple[Codec, ...] - if shard_shape_parsed is not None: - index_location = None + if inner is not None: + inner_chunks_flat = as_regular_shape(inner.outer_chunks) + index_location: IndexLocation = "end" if isinstance(shards, dict): - index_location = ShardingCodecIndexLocation(shards.get("index_location", None)) - if index_location is None: - index_location = ShardingCodecIndexLocation.end + index_location = cast("IndexLocation", shards.get("index_location", "end")) sharding_codec = ShardingCodec( - chunk_shape=chunk_shape_parsed, codecs=sub_codecs, index_location=index_location + chunk_shape=inner_chunks_flat, codecs=sub_codecs, index_location=index_location ) sharding_codec.validate( - shape=chunk_shape_parsed, + shape=inner_chunks_flat, dtype=zdtype, - chunk_grid=RegularChunkGrid(chunk_shape=shard_shape_parsed), + chunk_grid=grid, ) codecs_out = (sharding_codec,) - chunks_out = shard_shape_parsed else: - chunks_out = chunk_shape_parsed codecs_out = sub_codecs if order is not None: _warn_order_kwarg() - meta = AsyncArray._create_metadata_v3( shape=shape_parsed, dtype=zdtype, fill_value=fill_value, - chunk_shape=chunks_out, + chunk_grid=grid, chunk_key_encoding=chunk_key_encoding_parsed, codecs=codecs_out, dimension_names=dimension_names, @@ -4741,7 +4570,7 @@ async def create_array( shape: ShapeLike | None = None, dtype: ZDTypeLike | None = None, data: np.ndarray[Any, np.dtype[Any]] | None = None, - chunks: tuple[int, ...] | Literal["auto"] = "auto", + chunks: ChunksLike | Literal["auto"] = "auto", shards: ShardsLike | None = None, filters: FiltersLike = "auto", compressors: CompressorsLike = "auto", @@ -4751,7 +4580,7 @@ async def create_array( zarr_format: ZarrFormat | None = 3, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, overwrite: bool = False, config: ArrayConfigLike | None = None, @@ -4766,20 +4595,24 @@ async def create_array( [storage documentation in the user guide][user-guide-store-like] for a description of all valid StoreLike values. name : str or None, optional - The name of the array within the store. If ``name`` is ``None``, the array will be located + The name of the array within the store. If `name` is `None`, the array will be located at the root of the store. shape : ShapeLike, optional - Shape of the array. Must be ``None`` if ``data`` is provided. + Shape of the array. Must be `None` if `data` is provided. dtype : ZDTypeLike | None - Data type of the array. Must be ``None`` if ``data`` is provided. + Data type of the array. Must be `None` if `data` is provided. data : np.ndarray, optional Array-like data to use for initializing the array. If this parameter is provided, the - ``shape`` and ``dtype`` parameters must be ``None``. - chunks : tuple[int, ...] | Literal["auto"], default="auto" + `shape` and `dtype` parameters must be `None`. + chunks : tuple[int, ...] | Sequence[Sequence[int]] | Literal["auto"], default="auto" Chunk shape of the array. If chunks is "auto", a chunk shape is guessed based on the shape of the array and the dtype. + A nested list of per-dimension edge sizes creates a rectilinear grid. + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. shards : tuple[int, ...], optional - Shard shape of the array. The default value of ``None`` results in no sharding at all. + Shard shape of the array. The default value of `None` results in no sharding at all. filters : Iterable[Codec] | Literal["auto"], optional Iterable of filters to apply to each chunk of the array, in order, before serializing that chunk to bytes. @@ -4790,56 +4623,56 @@ async def create_array( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of `"auto"` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters contains a single element which is a codec specific to that particular data type. - To create an array with no filters, provide an empty iterable or the value ``None``. + To create an array with no filters, provide an empty iterable or the value `None`. compressors : Iterable[Codec], optional List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes. For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. - If no ``compressors`` are provided, a default set of compressors will be used. - These defaults can be changed by modifying the value of ``array.v3_default_compressors`` + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + If no `compressors` are provided, a default set of compressors will be used. + These defaults can be changed by modifying the value of `array.v3_default_compressors` in [`zarr.config`][zarr.config]. - Use ``None`` to omit default compressors. + Use `None` to omit default compressors. For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. - If no ``compressor`` is provided, a default compressor will be used. + If no `compressor` is provided, a default compressor will be used. in [`zarr.config`][zarr.config]. - Use ``None`` to omit the default compressor. + Use `None` to omit the default compressor. serializer : dict[str, JSON] | ArrayBytesCodec, optional Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. - If no ``serializer`` is provided, a default serializer will be used. - These defaults can be changed by modifying the value of ``array.v3_default_serializer`` + If no `serializer` is provided, a default serializer will be used. + These defaults can be changed by modifying the value of `array.v3_default_serializer` in [`zarr.config`][zarr.config]. fill_value : Any, optional Fill value for the array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory - order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. - If no ``order`` is provided, a default order will be used. - This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config]. + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If no `order` is provided, a default order will be used. + This default can be changed by modifying the value of `array.order` in [`zarr.config`][zarr.config]. zarr_format : {2, 3}, optional The zarr format to use when saving. attributes : dict, optional Attributes for the array. chunk_key_encoding : ChunkKeyEncodingLike, optional A specification of how the chunk keys are represented in storage. - For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. - For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. dimension_names : Iterable[str], optional The names of the dimensions (default is None). Zarr format 3 only. Zarr format 2 arrays should not use this parameter. @@ -4848,13 +4681,13 @@ async def create_array( Ignored otherwise. overwrite : bool, default False Whether to overwrite an array with the same name in the store, if one exists. - If ``True``, all existing paths in the store will be deleted. + If `True`, all existing paths in the store will be deleted. config : ArrayConfigLike, optional Runtime configuration for the array. write_data : bool - If a pre-existing array-like object was provided to this function via the ``data`` parameter - then ``write_data`` determines whether the values in that array-like object should be - written to the Zarr array created by this function. If ``write_data`` is ``False``, then the + If a pre-existing array-like object was provided to this function via the `data` parameter + then `write_data` determines whether the values in that array-like object should be + written to the Zarr array created by this function. If `write_data` is `False`, then the array will be left empty. Returns @@ -4864,15 +4697,18 @@ async def create_array( Examples -------- + >>> import asyncio >>> import zarr - >>> store = zarr.storage.MemoryStore(mode='w') - >>> async_arr = await zarr.api.asynchronous.create_array( - >>> store=store, - >>> shape=(100,100), - >>> chunks=(10,10), - >>> dtype='i4', - >>> fill_value=0) - + >>> asyncio.run( + ... zarr.api.asynchronous.create_array( + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="i4", + ... fill_value=0 + ... ) + ... ) + """ data_parsed, shape_parsed, dtype_parsed = _parse_data_params( data=data, shape=shape, dtype=dtype @@ -4926,8 +4762,8 @@ async def create_array( def _parse_keep_array_attr( data: AnyArray | npt.ArrayLike, - chunks: Literal["auto", "keep"] | tuple[int, ...], - shards: ShardsLike | None | Literal["keep"], + chunks: ChunksLike | Literal["auto", "keep"], + shards: ShardsLike | Literal["keep"] | None, filters: FiltersLike | Literal["keep"], compressors: CompressorsLike | Literal["keep"], serializer: SerializerLike | Literal["keep"], @@ -4935,9 +4771,9 @@ def _parse_keep_array_attr( order: MemoryOrder | None, zarr_format: ZarrFormat | None, chunk_key_encoding: ChunkKeyEncodingLike | None, - dimension_names: DimensionNames, + dimension_names: DimensionNamesLike, ) -> tuple[ - tuple[int, ...] | Literal["auto"], + ChunksLike | Literal["auto"], ShardsLike | None, FiltersLike, CompressorsLike, @@ -4946,13 +4782,16 @@ def _parse_keep_array_attr( MemoryOrder | None, ZarrFormat, ChunkKeyEncodingLike | None, - DimensionNames, + DimensionNamesLike, ]: if isinstance(data, Array): if chunks == "keep": - chunks = data.chunks + if data._chunk_grid.is_regular: + chunks = data.chunks + else: + chunks = data.write_chunk_sizes if shards == "keep": - shards = data.shards + shards = data.shards if data._chunk_grid.is_regular else None if zarr_format is None: zarr_format = data.metadata.zarr_format if filters == "keep": @@ -5004,8 +4843,10 @@ def _parse_keep_array_attr( compressors = "auto" if serializer == "keep": serializer = "auto" + # After resolving "keep" above, chunks is never "keep" at this point. + chunks_out: ChunksLike | Literal["auto"] = chunks return ( - chunks, + chunks_out, shards, filters, compressors, @@ -5040,20 +4881,11 @@ def _parse_chunk_key_encoding( return result -def default_filters_v3(dtype: ZDType[Any, Any]) -> tuple[ArrayArrayCodec, ...]: - """ - Given a data type, return the default filters for that data type. - - This is an empty tuple. No data types have default filters. - """ - return () - - def default_compressors_v3(dtype: ZDType[Any, Any]) -> tuple[BytesBytesCodec, ...]: """ Given a data type, return the default compressors for that data type. - This is just a tuple containing ``ZstdCodec`` + This is just a tuple containing `ZstdCodec` """ return (ZstdCodec(),) @@ -5062,15 +4894,18 @@ def default_serializer_v3(dtype: ZDType[Any, Any]) -> ArrayBytesCodec: """ Given a data type, return the default serializer for that data type. - The default serializer for most data types is the ``BytesCodec``, which may or may not be + The default serializer for most data types is the `BytesCodec`, which may or may not be parameterized with an endianness, depending on whether the data type has endianness. Variable - length strings and variable length bytes have hard-coded serializers -- ``VLenUTF8Codec`` and - ``VLenBytesCodec``, respectively. + length strings and variable length bytes have hard-coded serializers -- `VLenUTF8Codec` and + `VLenBytesCodec`, respectively. + Structured data types with multi-byte fields use `BytesCodec` with little-endian encoding. """ serializer: ArrayBytesCodec = BytesCodec(endian=None) - if isinstance(dtype, HasEndianness): + if isinstance(dtype, HasEndianness) or ( + isinstance(dtype, Structured) and dtype.has_multi_byte_fields() + ): serializer = BytesCodec(endian="little") elif isinstance(dtype, HasObjectCodec): if dtype.object_codec_id == "vlen-bytes": @@ -5088,7 +4923,7 @@ def default_filters_v2(dtype: ZDType[Any, Any]) -> tuple[Numcodec] | None: Given a data type, return the default filters for that data type. For data types that require an object codec, namely variable length data types, - this is a tuple containing the object codec. Otherwise it's ``None``. + this is a tuple containing the object codec. Otherwise it's `None`. """ if isinstance(dtype, HasObjectCodec): if dtype.object_codec_id == "vlen-bytes": @@ -5109,7 +4944,7 @@ def default_compressor_v2(dtype: ZDType[Any, Any]) -> Numcodec: """ Given a data type, return the default compressors for that data type. - This is just the numcodecs ``Zstd`` codec. + This is just the numcodecs `Zstd` codec. """ from numcodecs import Zstd @@ -5198,7 +5033,8 @@ def _parse_chunk_encoding_v3( if filters is None: out_array_array: tuple[ArrayArrayCodec, ...] = () elif filters == "auto": - out_array_array = default_filters_v3(dtype) + # no data types have default filters + out_array_array = () else: maybe_array_array: Iterable[Codec | dict[str, JSON]] if isinstance(filters, dict | Codec): @@ -5265,7 +5101,7 @@ def _parse_data_params( dtype: ZDTypeLike | None, ) -> tuple[np.ndarray[Any, np.dtype[Any]] | None, ShapeLike, ZDTypeLike]: """ - Ensure an array-like ``data`` parameter is consistent with the ``dtype`` and ``shape`` + Ensure an array-like `data` parameter is consistent with the `dtype` and `shape` parameters. """ if data is None: @@ -5278,7 +5114,7 @@ def _parse_data_params( shape_out = shape if dtype is None: msg = ( - "The data parameter was set to None, but dtype was not specified." + "The data parameter was set to None, but dtype was not specified. " "Either provide an array-like value for data, or specify dtype." ) raise ValueError(msg) @@ -5461,9 +5297,7 @@ def _iter_chunk_regions( A tuple of slice objects representing the region spanned by each shard in the selection. """ - return _iter_regions( - array.shape, array.chunks, origin=origin, selection_shape=selection_shape, trim_excess=True - ) + return array._chunk_grid.iter_chunk_regions(origin=origin, selection_shape=selection_shape) async def _nchunks_initialized( @@ -5536,11 +5370,32 @@ async def _nbytes_stored( return await store_path.store.getsize_prefix(store_path.path) +def _get_chunk_spec( + metadata: ArrayMetadata, + chunk_grid: ChunkGrid, + chunk_coords: tuple[int, ...], + array_config: ArrayConfig, + prototype: BufferPrototype, +) -> ArraySpec: + """Build an ArraySpec for a single chunk using the ChunkGrid.""" + spec = chunk_grid[chunk_coords] + if spec is None: + raise IndexError(f"Chunk coordinates {chunk_coords} are out of bounds.") + return ArraySpec( + shape=spec.codec_shape, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=array_config, + prototype=prototype, + ) + + async def _get_selection( store_path: StorePath, metadata: ArrayMetadata, codec_pipeline: CodecPipeline, config: ArrayConfig, + chunk_grid: ChunkGrid, indexer: Indexer, *, prototype: BufferPrototype, @@ -5574,11 +5429,8 @@ async def _get_selection( NDArrayLikeOrScalar The selected data. """ - # Get dtype from metadata - if metadata.zarr_format == 2: - zdtype = metadata.dtype - else: - zdtype = metadata.data_type + # `dtype` returns the zarr dtype object for both v2 and v3 metadata. + zdtype = metadata.dtype dtype = zdtype.to_native_dtype() # Determine memory order @@ -5613,20 +5465,49 @@ async def _get_selection( _config = replace(_config, order=order) # reading chunks and decoding them - await codec_pipeline.read( + indexed_chunks = list(indexer) + # For regular grids, all chunks share the same ArraySpec, so build it once + # and reuse it to avoid per-chunk ChunkGrid lookups and ArraySpec construction. + regular_grid = chunk_grid.is_regular + if regular_grid: + regular_chunk_spec = ArraySpec( + shape=chunk_grid.chunk_shape, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=_config, + prototype=prototype, + ) + results = await codec_pipeline.read( [ ( store_path / metadata.encode_chunk_key(chunk_coords), - metadata.get_chunk_spec(chunk_coords, _config, prototype=prototype), + regular_chunk_spec + if regular_grid + else _get_chunk_spec(metadata, chunk_grid, chunk_coords, _config, prototype), chunk_selection, out_selection, is_complete_chunk, ) - for chunk_coords, chunk_selection, out_selection, is_complete_chunk in indexer + for chunk_coords, chunk_selection, out_selection, is_complete_chunk in indexed_chunks ], out_buffer, drop_axes=indexer.drop_axes, ) + if _config.read_missing_chunks is False: + missing_info = [] + for i, result in enumerate(results): + if result["status"] == "missing": + coords = indexed_chunks[i][0] + key = metadata.encode_chunk_key(coords) + missing_info.append(f" chunk '{key}' (grid position {coords})") + if missing_info: + chunks_str = "\n".join(missing_info) + raise ChunkNotFoundError( + f"{len(missing_info)} chunk(s) not found in store '{store_path}'.\n" + f"Set the 'array.read_missing_chunks' config to True to fill " + f"missing chunks with the fill value.\n" + f"Missing chunks:\n{chunks_str}" + ) if isinstance(indexer, BasicIndexer) and indexer.shape == (): return out_buffer.as_scalar() return out_buffer.as_ndarray_like() @@ -5637,6 +5518,7 @@ async def _getitem( metadata: ArrayMetadata, codec_pipeline: CodecPipeline, config: ArrayConfig, + chunk_grid: ChunkGrid, selection: BasicSelection, *, prototype: BufferPrototype | None = None, @@ -5654,6 +5536,8 @@ async def _getitem( The codec pipeline for encoding/decoding. config : ArrayConfig The array configuration. + chunk_grid : ChunkGrid + The chunk grid. selection : BasicSelection A selection object specifying the subset of data to retrieve. prototype : BufferPrototype, optional @@ -5669,182 +5553,19 @@ async def _getitem( indexer = BasicIndexer( selection, shape=metadata.shape, - chunk_grid=metadata.chunk_grid, - ) - return await _get_selection( - store_path, metadata, codec_pipeline, config, indexer, prototype=prototype - ) - - -async def _get_orthogonal_selection( - store_path: StorePath, - metadata: ArrayMetadata, - codec_pipeline: CodecPipeline, - config: ArrayConfig, - selection: OrthogonalSelection, - *, - out: NDBuffer | None = None, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, -) -> NDArrayLikeOrScalar: - """ - Get an orthogonal selection from the array. - - Parameters - ---------- - store_path : StorePath - The store path of the array. - metadata : ArrayMetadata - The array metadata. - codec_pipeline : CodecPipeline - The codec pipeline for encoding/decoding. - config : ArrayConfig - The array configuration. - selection : OrthogonalSelection - The orthogonal selection specification. - out : NDBuffer | None, optional - An output buffer to write the data to. - fields : Fields | None, optional - Fields to select from structured arrays. - prototype : BufferPrototype | None, optional - A buffer prototype to use for the retrieved data. - - Returns - ------- - NDArrayLikeOrScalar - The selected data. - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = OrthogonalIndexer(selection, metadata.shape, metadata.chunk_grid) - return await _get_selection( - store_path, - metadata, - codec_pipeline, - config, - indexer=indexer, - out=out, - fields=fields, - prototype=prototype, + chunk_grid=chunk_grid, ) - - -async def _get_mask_selection( - store_path: StorePath, - metadata: ArrayMetadata, - codec_pipeline: CodecPipeline, - config: ArrayConfig, - mask: MaskSelection, - *, - out: NDBuffer | None = None, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, -) -> NDArrayLikeOrScalar: - """ - Get a mask selection from the array. - - Parameters - ---------- - store_path : StorePath - The store path of the array. - metadata : ArrayMetadata - The array metadata. - codec_pipeline : CodecPipeline - The codec pipeline for encoding/decoding. - config : ArrayConfig - The array configuration. - mask : MaskSelection - The boolean mask specifying the selection. - out : NDBuffer | None, optional - An output buffer to write the data to. - fields : Fields | None, optional - Fields to select from structured arrays. - prototype : BufferPrototype | None, optional - A buffer prototype to use for the retrieved data. - - Returns - ------- - NDArrayLikeOrScalar - The selected data. - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = MaskIndexer(mask, metadata.shape, metadata.chunk_grid) return await _get_selection( - store_path, - metadata, - codec_pipeline, - config, - indexer=indexer, - out=out, - fields=fields, - prototype=prototype, + store_path, metadata, codec_pipeline, config, chunk_grid, indexer, prototype=prototype ) -async def _get_coordinate_selection( - store_path: StorePath, - metadata: ArrayMetadata, - codec_pipeline: CodecPipeline, - config: ArrayConfig, - selection: CoordinateSelection, - *, - out: NDBuffer | None = None, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, -) -> NDArrayLikeOrScalar: - """ - Get a coordinate selection from the array. - - Parameters - ---------- - store_path : StorePath - The store path of the array. - metadata : ArrayMetadata - The array metadata. - codec_pipeline : CodecPipeline - The codec pipeline for encoding/decoding. - config : ArrayConfig - The array configuration. - selection : CoordinateSelection - The coordinate selection specification. - out : NDBuffer | None, optional - An output buffer to write the data to. - fields : Fields | None, optional - Fields to select from structured arrays. - prototype : BufferPrototype | None, optional - A buffer prototype to use for the retrieved data. - - Returns - ------- - NDArrayLikeOrScalar - The selected data. - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = CoordinateIndexer(selection, metadata.shape, metadata.chunk_grid) - out_array = await _get_selection( - store_path, - metadata, - codec_pipeline, - config, - indexer=indexer, - out=out, - fields=fields, - prototype=prototype, - ) - - if hasattr(out_array, "shape"): - # restore shape - out_array = np.array(out_array).reshape(indexer.sel_shape) - return out_array - - async def _set_selection( store_path: StorePath, metadata: ArrayMetadata, codec_pipeline: CodecPipeline, config: ArrayConfig, + chunk_grid: ChunkGrid, indexer: Indexer, value: npt.ArrayLike, *, @@ -5864,6 +5585,8 @@ async def _set_selection( The codec pipeline for encoding/decoding. config : ArrayConfig The array configuration. + chunk_grid : ChunkGrid + The chunk grid. indexer : Indexer The indexer specifying the selection. value : npt.ArrayLike @@ -5873,11 +5596,8 @@ async def _set_selection( fields : Fields | None, optional Fields to select from structured arrays. """ - # Get dtype from metadata - if metadata.zarr_format == 2: - zdtype = metadata.dtype - else: - zdtype = metadata.data_type + # `dtype` returns the zarr dtype object for both v2 and v3 metadata. + zdtype = metadata.dtype dtype = zdtype.to_native_dtype() # check fields are sensible @@ -5923,11 +5643,24 @@ async def _set_selection( _config = replace(_config, order=order) # merging with existing data and encoding chunks + # For regular grids, all chunks share the same ArraySpec, so build it once + # and reuse it to avoid per-chunk ChunkGrid lookups and ArraySpec construction. + regular_grid = chunk_grid.is_regular + if regular_grid: + regular_chunk_spec = ArraySpec( + shape=chunk_grid.chunk_shape, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=_config, + prototype=prototype, + ) await codec_pipeline.write( [ ( store_path / metadata.encode_chunk_key(chunk_coords), - metadata.get_chunk_spec(chunk_coords, _config, prototype), + regular_chunk_spec + if regular_grid + else _get_chunk_spec(metadata, chunk_grid, chunk_coords, _config, prototype), chunk_selection, out_selection, is_complete_chunk, @@ -5944,6 +5677,7 @@ async def _setitem( metadata: ArrayMetadata, codec_pipeline: CodecPipeline, config: ArrayConfig, + chunk_grid: ChunkGrid, selection: BasicSelection, value: npt.ArrayLike, prototype: BufferPrototype | None = None, @@ -5961,6 +5695,8 @@ async def _setitem( The codec pipeline for encoding/decoding. config : ArrayConfig The array configuration. + chunk_grid : ChunkGrid + The chunk grid. selection : BasicSelection The selection defining the region of the array to set. value : npt.ArrayLike @@ -5974,10 +5710,17 @@ async def _setitem( indexer = BasicIndexer( selection, shape=metadata.shape, - chunk_grid=metadata.chunk_grid, + chunk_grid=chunk_grid, ) return await _set_selection( - store_path, metadata, codec_pipeline, config, indexer, value, prototype=prototype + store_path, + metadata, + codec_pipeline, + config, + chunk_grid, + indexer, + value, + prototype=prototype, ) @@ -6001,15 +5744,17 @@ async def _resize( """ new_shape = parse_shapelike(new_shape) assert len(new_shape) == len(array.metadata.shape) + new_metadata = array.metadata.update_shape(new_shape) + new_chunk_grid = ChunkGrid.from_metadata(new_metadata) # ensure deletion is only run if array is shrinking as the delete_outside_chunks path is unbounded in memory only_growing = all(new >= old for new, old in zip(new_shape, array.metadata.shape, strict=True)) if delete_outside_chunks and not only_growing: # Remove all chunks outside of the new shape - old_chunk_coords = set(array.metadata.chunk_grid.all_chunk_coords(array.metadata.shape)) - new_chunk_coords = set(array.metadata.chunk_grid.all_chunk_coords(new_shape)) + old_chunk_coords = set(array._chunk_grid.all_chunk_coords()) + new_chunk_coords = set(new_chunk_grid.all_chunk_coords()) async def _delete_key(key: str) -> None: await (array.store_path / key).delete() @@ -6026,8 +5771,9 @@ async def _delete_key(key: str) -> None: # Write new metadata await save_metadata(array.store_path, new_metadata) - # Update metadata (in place) + # Update metadata and chunk_grid (in place) object.__setattr__(array, "metadata", new_metadata) + object.__setattr__(array, "_chunk_grid", new_chunk_grid) async def _append( @@ -6093,6 +5839,7 @@ async def _append( array.metadata, array.codec_pipeline, array.config, + array._chunk_grid, append_selection, data, ) diff --git a/src/zarr/core/array_spec.py b/src/zarr/core/array_spec.py index 421dfbf145..1f4ffd6f09 100644 --- a/src/zarr/core/array_spec.py +++ b/src/zarr/core/array_spec.py @@ -3,10 +3,13 @@ from dataclasses import dataclass, fields from typing import TYPE_CHECKING, Any, Literal, Self, TypedDict, cast +import numpy as np + from zarr.core.common import ( MemoryOrder, parse_bool, parse_fill_value, + parse_int, parse_order, parse_shapelike, ) @@ -28,6 +31,9 @@ class ArrayConfigParams(TypedDict): order: NotRequired[MemoryOrder] write_empty_chunks: NotRequired[bool] + read_missing_chunks: NotRequired[bool] + sharding_coalesce_max_gap_bytes: NotRequired[int] + sharding_coalesce_max_bytes: NotRequired[int] @dataclass(frozen=True) @@ -41,17 +47,45 @@ class ArrayConfig: The memory layout of the arrays returned when reading data from the store. write_empty_chunks : bool If True, empty chunks will be written to the store. + read_missing_chunks : bool + If True, missing chunks will be filled with the array's fill value on read. + If False, reading missing chunks will raise a ``ChunkNotFoundError``. + sharding_coalesce_max_gap_bytes : int + When reading multiple chunks from the same shard, nearby byte ranges + separated by no more than this many bytes are coalesced into a single + request to the store. + sharding_coalesce_max_bytes : int + Requests will not be coalesced if doing so would exceed this byte size. """ order: MemoryOrder write_empty_chunks: bool + read_missing_chunks: bool + sharding_coalesce_max_gap_bytes: int + sharding_coalesce_max_bytes: int - def __init__(self, order: MemoryOrder, write_empty_chunks: bool) -> None: + def __init__( + self, + order: MemoryOrder, + write_empty_chunks: bool, + *, + read_missing_chunks: bool = True, + sharding_coalesce_max_gap_bytes: int = 1 << 20, # 1 MiB + sharding_coalesce_max_bytes: int = 16 << 20, # 16 MiB + ) -> None: order_parsed = parse_order(order) write_empty_chunks_parsed = parse_bool(write_empty_chunks) + read_missing_chunks_parsed = parse_bool(read_missing_chunks) + sharding_coalesce_max_gap_bytes_parsed = parse_int(sharding_coalesce_max_gap_bytes) + sharding_coalesce_max_bytes_parsed = parse_int(sharding_coalesce_max_bytes) object.__setattr__(self, "order", order_parsed) object.__setattr__(self, "write_empty_chunks", write_empty_chunks_parsed) + object.__setattr__(self, "read_missing_chunks", read_missing_chunks_parsed) + object.__setattr__( + self, "sharding_coalesce_max_gap_bytes", sharding_coalesce_max_gap_bytes_parsed + ) + object.__setattr__(self, "sharding_coalesce_max_bytes", sharding_coalesce_max_bytes_parsed) @classmethod def from_dict(cls, data: ArrayConfigParams) -> Self: @@ -62,7 +96,10 @@ def from_dict(cls, data: ArrayConfigParams) -> Self: """ kwargs_out: ArrayConfigParams = {} for f in fields(ArrayConfig): - field_name = cast("Literal['order', 'write_empty_chunks']", f.name) + field_name = cast( + "Literal['order', 'write_empty_chunks', 'read_missing_chunks', 'sharding_coalesce_max_gap_bytes', 'sharding_coalesce_max_bytes']", + f.name, + ) if field_name not in data: kwargs_out[field_name] = zarr_config.get(f"array.{field_name}") else: @@ -73,7 +110,13 @@ def to_dict(self) -> ArrayConfigParams: """ Serialize an instance of this class to a dict. """ - return {"order": self.order, "write_empty_chunks": self.write_empty_chunks} + return { + "order": self.order, + "write_empty_chunks": self.write_empty_chunks, + "read_missing_chunks": self.read_missing_chunks, + "sharding_coalesce_max_gap_bytes": self.sharding_coalesce_max_gap_bytes, + "sharding_coalesce_max_bytes": self.sharding_coalesce_max_bytes, + } ArrayConfigLike = ArrayConfig | ArrayConfigParams @@ -91,7 +134,7 @@ def parse_array_config(data: ArrayConfigLike | None) -> ArrayConfig: return ArrayConfig.from_dict(data) -@dataclass(frozen=True) +@dataclass(frozen=True, eq=False) class ArraySpec: shape: tuple[int, ...] dtype: ZDType[TBaseDType, TBaseScalar] @@ -116,6 +159,24 @@ def __init__( object.__setattr__(self, "config", config) object.__setattr__(self, "prototype", prototype) + def _key(self) -> tuple[object, ...]: + """Returns the tuple used for equality/hash identity.""" + fill_value = self.fill_value + if isinstance(fill_value, np.generic): + # fill_values should be byte-identical, otherwise they correspond to different values in memory / on disk. + # Importantly, this ensures np.nan == np.nan, NaT == NaT, and -0.0 != 0.0. + # It also fixes np.void fill_values being unhashable (#3054). + fill_value = fill_value.tobytes() + return (self.shape, self.dtype, fill_value, self.config, self.prototype) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ArraySpec): + return NotImplemented + return self._key() == other._key() + + def __hash__(self) -> int: + return hash(self._key()) + @property def ndim(self) -> int: return len(self.shape) diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py index 9602a55258..b8f7f11cd4 100644 --- a/src/zarr/core/buffer/core.py +++ b/src/zarr/core/buffer/core.py @@ -21,7 +21,7 @@ from collections.abc import Iterable, Sequence from typing import Self - from zarr.codecs.bytes import Endian + from zarr.codecs.bytes import EndianLiteral from zarr.core.common import BytesLike # Everything here is imported into ``zarr.core.buffer`` namespace. @@ -45,6 +45,8 @@ def __getitem__(self, key: slice) -> Self: ... def __setitem__(self, key: slice, value: Any) -> None: ... + def copy(self) -> Self: ... + @runtime_checkable class NDArrayLike(Protocol): @@ -71,8 +73,13 @@ def __setitem__(self, key: slice, value: Any) -> None: ... def __array__(self) -> npt.NDArray[Any]: ... def reshape( - self, shape: tuple[int, ...] | Literal[-1], *, order: Literal["A", "C", "F"] = ... - ) -> Self: ... + self, + shape: tuple[int, ...], + /, + *, + order: Literal["A", "C", "F"] | None = ..., + copy: bool | None = ..., + ) -> NDArrayLike: ... def view(self, dtype: npt.DTypeLike) -> Self: ... @@ -92,7 +99,7 @@ def transpose(self, axes: SupportsIndex | Sequence[SupportsIndex] | None) -> Sel def ravel(self, order: Literal["K", "A", "C", "F"] = ...) -> Self: ... - def all(self) -> bool: ... + def all(self) -> np.bool_: ... def __eq__(self, other: object) -> Self: # type: ignore[override] """Element-wise equal @@ -267,7 +274,7 @@ def as_buffer_like(self) -> BytesLike: ------- An object that implements the Python buffer protocol """ - return memoryview(self.as_numpy_array()) # type: ignore[arg-type] + return memoryview(self.as_numpy_array()) def to_bytes(self) -> bytes: """Returns the buffer as `bytes` (host memory). @@ -491,18 +498,19 @@ def shape(self) -> tuple[int, ...]: return self._data.shape @property - def byteorder(self) -> Endian: - from zarr.codecs.bytes import Endian - + def byteorder(self) -> EndianLiteral: if self.dtype.byteorder == "<": - return Endian.little + return "little" elif self.dtype.byteorder == ">": - return Endian.big + return "big" else: - return Endian(sys.byteorder) + return sys.byteorder def reshape(self, newshape: tuple[int, ...] | Literal[-1]) -> Self: - return self.__class__(self._data.reshape(newshape)) + # numpy accepts a bare -1, but the NDArrayLike protocol only types the + # tuple form; normalize so the forwarded value matches the protocol. + shape = (newshape,) if newshape == -1 else newshape + return self.__class__(self._data.reshape(shape)) def squeeze(self, axis: tuple[int, ...]) -> Self: newshape = tuple(a for i, a in enumerate(self.shape) if i not in axis) @@ -535,7 +543,7 @@ def all_equal(self, other: Any, equal_nan: bool = True) -> bool: and self._data.dtype.kind not in ("U", "S", "T", "O", "V") ): _data, other = np.broadcast_arrays(self._data, np.asarray(other, self._data.dtype)) - void_dtype = "V" + str(_data.dtype.itemsize) + void_dtype = f"V{_data.dtype.itemsize}" return np.array_equal(_data.view(void_dtype), other.view(void_dtype)) # use array_equal to obtain equal_nan=True functionality # Since fill-value is a scalar, isn't there a faster path than allocating a new array for fill value diff --git a/src/zarr/core/chunk_grids.py b/src/zarr/core/chunk_grids.py index c903eba013..584829bc6c 100644 --- a/src/zarr/core/chunk_grids.py +++ b/src/zarr/core/chunk_grids.py @@ -1,37 +1,647 @@ from __future__ import annotations +import bisect import itertools import math import numbers import operator import warnings -from abc import abstractmethod -from dataclasses import dataclass +from dataclasses import dataclass, field from functools import reduce -from typing import TYPE_CHECKING, Any, Literal +from typing import ( + TYPE_CHECKING, + Any, + NamedTuple, + NewType, + Protocol, + TypeGuard, + cast, + runtime_checkable, +) import numpy as np +import numpy.typing as npt import zarr -from zarr.abc.metadata import Metadata from zarr.core.common import ( - JSON, - NamedConfig, ShapeLike, ceildiv, - parse_named_configuration, parse_shapelike, ) from zarr.errors import ZarrUserWarning if TYPE_CHECKING: - from collections.abc import Iterator - from typing import Self + from collections.abc import Iterable, Iterator, Sequence from zarr.core.array import ShardsLike + from zarr.core.metadata import ArrayMetadata + +SHARDED_INNER_CHUNK_MAX_BYTES: int = 1048576 +"""Target ceiling in bytes for the auto-chunking heuristic when sharding is active (1 MiB). + +Applied when `chunks` is left to auto-chunking (`None` or `"auto"`) and `shards` +is not `None`. Explicit chunk sizes are not affected by this value. +""" + +ChunksTuple = NewType("ChunksTuple", tuple[np.ndarray[tuple[int], np.dtype[np.int64]], ...]) +"""Normalized chunk specification: one 1D int64 array of chunk sizes per dimension. + +Produced exclusively by `normalize_chunks_nd` and `guess_chunks`. +Consumers should use this type to ensure they receive validated, +canonical chunk specifications rather than raw user input. +""" + + +class ChunkLayout(NamedTuple): + """Result of resolving user `chunks`/`shards` into grid metadata inputs. + + outer_chunks + Chunk sizes for the chunk grid metadata. When sharding is active + these are the shard sizes; otherwise they are the user's chunk sizes. + inner + Recursive sub-structure inside each chunk. `None` means the chunk is + opaque (no sharding). When present, `inner.outer_chunks` gives the + sub-chunk sizes passed to `ShardingCodec`, and `inner.inner` gives + the next level of nesting (for nested sharding), or `None`. + """ + + outer_chunks: ChunksTuple + inner: ChunkLayout | None = None + + +@dataclass(frozen=True) +class FixedDimension: + """Uniform chunk size. Boundary chunks contain less data but are + encoded at full size by the codec pipeline.""" + + size: int # chunk edge length (>= 0) + extent: int # array dimension length + nchunks: int = field(init=False, repr=False) + ngridcells: int = field(init=False, repr=False) + + def __post_init__(self) -> None: + if self.size < 0: + raise ValueError(f"FixedDimension size must be >= 0, got {self.size}") + if self.extent < 0: + raise ValueError(f"FixedDimension extent must be >= 0, got {self.extent}") + if self.size == 0: + n = 0 + else: + n = ceildiv(self.extent, self.size) + object.__setattr__(self, "nchunks", n) + object.__setattr__(self, "ngridcells", n) + + def index_to_chunk(self, idx: int) -> int: + if idx < 0: + raise IndexError(f"Negative index {idx} is not allowed") + if idx >= self.extent: + raise IndexError(f"Index {idx} is out of bounds for extent {self.extent}") + if self.size == 0: + return 0 + return idx // self.size + + def chunk_offset(self, chunk_ix: int) -> int: + """Byte-aligned start position of chunk *chunk_ix* in array coordinates. + + Does not validate *chunk_ix* — callers must ensure it is in + ``[0, nchunks)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return chunk_ix * self.size + + def chunk_size(self, chunk_ix: int) -> int: + """Buffer size for codec processing — always uniform. + + Does not validate *chunk_ix* — callers must ensure it is in + ``[0, nchunks)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return self.size + + def data_size(self, chunk_ix: int) -> int: + """Valid data region within the buffer — clipped at extent. + + Does not validate *chunk_ix* — callers must ensure it is in + ``[0, nchunks)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + if self.size == 0: + return 0 + return max(0, min(self.size, self.extent - chunk_ix * self.size)) + + @property + def _unique_edge_lengths(self) -> Iterable[int]: + """Distinct chunk edge lengths for this dimension. + + Used by shard validation to check that every unique edge length + is divisible by the inner chunk size. O(1) for fixed dimensions + since there is only one edge length. + """ + return (self.size,) + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + if self.size == 0: + return np.zeros_like(indices) + return indices // self.size + + def with_extent(self, new_extent: int) -> FixedDimension: + """Re-bind to *new_extent* without modifying edges. + + Used when constructing a grid from existing metadata where edges + are already correct. Raises on + ``VaryingDimension`` if edges don't cover the new extent. + """ + return FixedDimension(size=self.size, extent=new_extent) + + def resize(self, new_extent: int) -> FixedDimension: + """Adapt for a user-initiated array resize, growing edges if needed. + + For ``FixedDimension`` this is identical to ``with_extent`` since + regular grids don't store explicit edges. + """ + return FixedDimension(size=self.size, extent=new_extent) + + @property + def _size_repr(self) -> str: + return str(self.size) + + +@dataclass(frozen=True) +class VaryingDimension: + """Explicit per-chunk sizes. The last chunk may extend past the array + extent (``extent < sum(edges)``), in which case ``data_size`` clips to + the valid region while ``chunk_size`` returns the full edge length for + codec processing. This underflow is allowed to match how regular grids + handle boundary chunks, and to support shrinking an array without + rewriting chunk edges (the spec allows trailing edges beyond the extent).""" + + edges: tuple[int, ...] # per-chunk edge lengths (all > 0) + cumulative: tuple[int, ...] # prefix sums for O(log n) lookup + extent: int # array dimension length (may be < sum(edges) after resize) + nchunks: int = field(init=False, repr=False) # cached at construction + ngridcells: int = field(init=False, repr=False) # cached at construction + + # TODO(perf): for long dimensions (O(million chunks)): + # - with_extent/resize recompute cumulative sums and nchunks from scratch; + # add a fast path that reuses the existing cumulative tuple. + # - Consider storing cumulative as ndarray so bisect calls can use + # np.searchsorted. Scalar lookups (chunk_offset, index_to_chunk) + # would need benchmarking to confirm no regression. + def __init__(self, edges: Sequence[int], extent: int) -> None: + edges_tuple = tuple(edges) + if not edges_tuple: + raise ValueError("VaryingDimension edges must not be empty") + if any(e <= 0 for e in edges_tuple): + raise ValueError(f"All edge lengths must be > 0, got {edges_tuple}") + cumulative = tuple(itertools.accumulate(edges_tuple)) + if extent < 0: + raise ValueError(f"VaryingDimension extent must be >= 0, got {extent}") + if extent > cumulative[-1]: + raise ValueError( + f"VaryingDimension extent {extent} exceeds sum of edges {cumulative[-1]}" + ) + object.__setattr__(self, "edges", edges_tuple) + object.__setattr__(self, "cumulative", cumulative) + object.__setattr__(self, "extent", extent) + # Cache nchunks: number of chunks that overlap [0, extent) + if extent == 0: + n = 0 + else: + n = bisect.bisect_left(cumulative, extent) + 1 + object.__setattr__(self, "nchunks", n) + object.__setattr__(self, "ngridcells", len(edges_tuple)) + + def index_to_chunk(self, idx: int) -> int: + if idx < 0 or idx >= self.extent: + raise IndexError(f"Index {idx} out of bounds for dimension with extent {self.extent}") + return bisect.bisect_right(self.cumulative, idx) + + def chunk_offset(self, chunk_ix: int) -> int: + """Start position of chunk *chunk_ix* in array coordinates. + + Does not validate *chunk_ix* — callers must ensure it is in + ``[0, ngridcells)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 + + def chunk_size(self, chunk_ix: int) -> int: + """Buffer size for codec processing. + + Does not validate *chunk_ix* — callers must ensure it is in + ``[0, ngridcells)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return self.edges[chunk_ix] + + def data_size(self, chunk_ix: int) -> int: + """Valid data region within the buffer — clipped at extent. + + Does not validate *chunk_ix* — callers must ensure it is in + ``[0, ngridcells)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + offset = self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 + return max(0, min(self.edges[chunk_ix], self.extent - offset)) + + @property + def _unique_edge_lengths(self) -> Iterable[int]: + """Distinct chunk edge lengths for this dimension (lazily deduplicated). + + Used by shard validation to check that every unique edge length + is divisible by the inner chunk size. Lazy deduplication avoids + materializing all edges for dimensions with many repeated sizes. + """ + seen: set[int] = set() + for e in self.edges: + if e not in seen: + seen.add(e) + yield e + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + return np.searchsorted(self.cumulative, indices, side="right") + + def with_extent(self, new_extent: int) -> VaryingDimension: + """Re-bind to *new_extent* without modifying edges. + + Used when constructing a grid from existing metadata where edges + are already correct. Raises if the + existing edges don't cover *new_extent*. + """ + edge_sum = self.cumulative[-1] + if edge_sum < new_extent: + raise ValueError( + f"VaryingDimension edge sum {edge_sum} is less than new extent {new_extent}" + ) + return VaryingDimension(self.edges, extent=new_extent) + + def resize(self, new_extent: int) -> VaryingDimension: + """Adapt for a user-initiated array resize, growing edges if needed. + + Unlike ``with_extent``, this never fails — if *new_extent* exceeds + the current edge sum, a new chunk is appended to cover the gap. + Shrinking preserves all edges (the spec allows trailing edges + beyond the array extent). + """ + if new_extent == self.extent: + return self + elif new_extent > self.cumulative[-1]: + expanded_edges = list(self.edges) + [new_extent - self.cumulative[-1]] + return VaryingDimension(expanded_edges, extent=new_extent) + else: + return VaryingDimension(self.edges, extent=new_extent) + + @property + def _size_repr(self) -> str: + return repr(tuple(self.edges)) + + +@runtime_checkable +class DimensionGrid(Protocol): + """Structural interface shared by FixedDimension and VaryingDimension.""" + + @property + def nchunks(self) -> int: ... + @property + def ngridcells(self) -> int: ... + @property + def extent(self) -> int: ... + def index_to_chunk(self, idx: int) -> int: ... + def chunk_offset(self, chunk_ix: int) -> int: ... + def chunk_size(self, chunk_ix: int) -> int: ... + def data_size(self, chunk_ix: int) -> int: ... + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: ... + @property + def _unique_edge_lengths(self) -> Iterable[int]: ... + def with_extent(self, new_extent: int) -> DimensionGrid: ... + def resize(self, new_extent: int) -> DimensionGrid: ... + @property + def _size_repr(self) -> str: ... + + +@dataclass(frozen=True) +class ChunkSpec: + """Specification of a single chunk's location and size. + + ``slices`` gives the valid data region in array coordinates. + ``codec_shape`` gives the buffer shape for codec processing. + For interior chunks these are equal. For boundary chunks of a regular + grid, ``codec_shape`` is the full declared chunk size while ``shape`` + is clipped. For rectilinear grids, ``shape == codec_shape`` unless the + last chunk extends past the array extent. + """ + + slices: tuple[slice, ...] + codec_shape: tuple[int, ...] + + @property + def shape(self) -> tuple[int, ...]: + return tuple(s.stop - s.start for s in self.slices) + + @property + def is_boundary(self) -> bool: + return self.shape != self.codec_shape + + +# A single dimension's rectilinear chunk spec: bare int (uniform shorthand), +# list of ints (explicit edges), or mixed RLE (e.g. [[10, 3], 5]). + + +def _is_rectilinear_chunks(chunks: Any) -> TypeGuard[Sequence[Sequence[int]]]: + """Check if chunks is a nested sequence (e.g. [[10, 20], [5, 5]]). + + Returns True for inputs like [[10, 20], [5, 5]] or [(10, 20), (5, 5)]. + Returns False for flat sequences like (10, 10) or [10, 10]. + """ + if isinstance(chunks, (str, int, ChunkGrid)): + return False + if not hasattr(chunks, "__iter__"): + return False + try: + first_elem = next(iter(chunks), None) + if first_elem is None: + return False + return hasattr(first_elem, "__iter__") and not isinstance(first_elem, (str, bytes, int)) + except (TypeError, StopIteration): + return False + + +def is_regular_1d( + dim_chunks: Sequence[int] | np.ndarray[tuple[int], np.dtype[np.int64]], +) -> bool: + """Check if a single dimension's chunk sizes represent a regular grid. + + A regular dimension has either all chunks the same size, or all + but the last chunk the same size with the last chunk smaller + (boundary chunk). + """ + if len(dim_chunks) <= 1: + return True + first = dim_chunks[0] + if isinstance(dim_chunks, np.ndarray): + # Vectorized comparison avoids per-element Python iteration over int64 arrays. + return bool((dim_chunks[1:-1] == first).all() and dim_chunks[-1] <= first) + for c in dim_chunks[1:-1]: + if c != first: + return False + # Last chunk must be the same size or a smaller boundary chunk + return dim_chunks[-1] <= first + + +def is_regular_nd( + chunks: Iterable[Sequence[int] | np.ndarray[tuple[int], np.dtype[np.int64]]], +) -> bool: + """Check if an N-dimensional chunk specification represents a regular grid.""" + return all(is_regular_1d(d) for d in chunks) + + +def as_regular_shape(chunks: ChunksTuple) -> tuple[int, ...]: + """Flatten a regular ChunksTuple to one int per dimension.""" + assert is_regular_nd(chunks), f"expected regular chunks, got {chunks}" + return tuple(int(dim[0]) for dim in chunks) + + +@dataclass(frozen=True) +class ChunkGrid: + """ + Unified chunk grid supporting both regular and rectilinear chunking. + + A chunk grid is a concrete arrangement of chunks for a specific array. + It stores the extent (array dimension length) per dimension, enabling + ``grid[coords]`` to return a ``ChunkSpec`` without external parameters. + + Internally represents each dimension as either FixedDimension (uniform chunks) + or VaryingDimension (per-chunk edge lengths with prefix sums). + """ + + _dimensions: tuple[DimensionGrid, ...] + _is_regular: bool + + def __init__(self, *, dimensions: tuple[DimensionGrid, ...]) -> None: + object.__setattr__(self, "_dimensions", dimensions) + object.__setattr__( + self, "_is_regular", all(isinstance(d, FixedDimension) for d in dimensions) + ) + + def __repr__(self) -> str: + sizes = ", ".join(d._size_repr for d in self._dimensions) + shape = tuple(d.extent for d in self._dimensions) + return f"ChunkGrid(chunk_sizes=({sizes}), array_shape={shape})" + + @classmethod + def from_metadata(cls, metadata: ArrayMetadata) -> ChunkGrid: + """Construct a ChunkGrid from array metadata. + + For v2 metadata, builds from shape and chunks. + For v3 metadata, dispatches on the chunk grid type. + """ + from zarr.core.metadata import ArrayV2Metadata + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata + + if isinstance(metadata, ArrayV2Metadata): + return cls.from_sizes(metadata.shape, tuple(metadata.chunks)) + chunk_grid_meta = metadata.chunk_grid + if isinstance(chunk_grid_meta, RegularChunkGridMetadata): + return cls.from_sizes(metadata.shape, tuple(chunk_grid_meta.chunk_shape)) + elif isinstance(chunk_grid_meta, RectilinearChunkGridMetadata): + return cls.from_sizes(metadata.shape, chunk_grid_meta.chunk_shapes) + else: + raise TypeError(f"Unknown chunk grid metadata type: {type(chunk_grid_meta)}") + + @classmethod + def from_sizes( + cls, + array_shape: ShapeLike, + chunk_sizes: Sequence[int | Sequence[int]], + ) -> ChunkGrid: + """Create a ChunkGrid from per-dimension chunk size specifications. + + Parameters + ---------- + array_shape + The array shape (one extent per dimension). + chunk_sizes + Per-dimension chunk sizes. Each element is either: + + - An ``int`` — regular (fixed) chunk size for that dimension. + - A ``Sequence[int]`` — explicit per-chunk edge lengths. If all + edges are identical and cover the extent, the dimension is + stored as ``FixedDimension``; otherwise as ``VaryingDimension``. + """ + extents = parse_shapelike(array_shape) + if len(extents) != len(chunk_sizes): + raise ValueError( + f"array_shape has {len(extents)} dimensions but chunk_sizes " + f"has {len(chunk_sizes)} dimensions" + ) + dims: list[DimensionGrid] = [] + for dim_spec, extent in zip(chunk_sizes, extents, strict=True): + if isinstance(dim_spec, int): + dims.append(FixedDimension(size=dim_spec, extent=extent)) + else: + edges_list = list(dim_spec) + if not edges_list: + raise ValueError("Each dimension must have at least one chunk") + edge_sum = sum(edges_list) + if ( + edges_list[0] > 0 + and all(e == edges_list[0] for e in edges_list) + and (extent == edge_sum or len(edges_list) == ceildiv(extent, edges_list[0])) + ): + dims.append(FixedDimension(size=edges_list[0], extent=extent)) + else: + dims.append(VaryingDimension(edges_list, extent=extent)) + return cls(dimensions=tuple(dims)) + + # -- Properties -- + + @property + def ndim(self) -> int: + return len(self._dimensions) + + @property + def is_regular(self) -> bool: + return self._is_regular + + @property + def grid_shape(self) -> tuple[int, ...]: + """Number of chunks per dimension.""" + return tuple(d.nchunks for d in self._dimensions) + + @property + def chunk_shape(self) -> tuple[int, ...]: + """Return the uniform chunk shape. Raises if grid is not regular.""" + if not self.is_regular: + raise ValueError( + "chunk_shape is only available for regular chunk grids. " + "Use grid[coords] for per-chunk sizes." + ) + return tuple(d.size for d in self._dimensions if isinstance(d, FixedDimension)) + + @property + def chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension chunk sizes, including the final boundary chunk. + + Returns the actual data size of each chunk (clipped at the array + extent), matching the dask ``Array.chunks`` convention. Works for + both regular and rectilinear grids. + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension, each containing the data size + of every chunk along that dimension. + """ + return tuple(tuple(d.data_size(i) for i in range(d.nchunks)) for d in self._dimensions) + + # -- Collection interface -- + + def __getitem__(self, coords: int | tuple[int, ...]) -> ChunkSpec | None: + """Return the ChunkSpec for a chunk at the given grid position, or None if OOB.""" + if isinstance(coords, int): + coords = (coords,) + if len(coords) != self.ndim: + raise ValueError( + f"Expected {self.ndim} coordinate(s) for a {self.ndim}-d chunk grid, " + f"got {len(coords)}." + ) + slices: list[slice] = [] + codec_shape: list[int] = [] + for dim, ix in zip(self._dimensions, coords, strict=True): + if ix < 0 or ix >= dim.nchunks: + return None + offset = dim.chunk_offset(ix) + slices.append(slice(offset, offset + dim.data_size(ix), 1)) + codec_shape.append(dim.chunk_size(ix)) + return ChunkSpec(tuple(slices), tuple(codec_shape)) + + def __iter__(self) -> Iterator[ChunkSpec]: + """Iterate all chunks, yielding ChunkSpec for each.""" + for coords in itertools.product(*(range(d.nchunks) for d in self._dimensions)): + spec = self[coords] + if spec is not None: + yield spec + + def all_chunk_coords( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[int, ...]]: + """Iterate over chunk coordinates, optionally restricted to a subregion. + + Parameters + ---------- + origin : Sequence[int] | None + The first chunk coordinate to return. Defaults to the grid origin. + selection_shape : Sequence[int] | None + The number of chunks per dimension to iterate. Defaults to the + remaining extent from origin. + """ + if origin is None: + origin_parsed = (0,) * self.ndim + else: + origin_parsed = tuple(origin) + if selection_shape is None: + selection_shape_parsed = tuple( + g - o for o, g in zip(origin_parsed, self.grid_shape, strict=True) + ) + else: + selection_shape_parsed = tuple(selection_shape) + ranges = tuple( + range(o, o + s) for o, s in zip(origin_parsed, selection_shape_parsed, strict=True) + ) + return itertools.product(*ranges) + + def iter_chunk_regions( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[slice, ...]]: + """Iterate over the data regions (slices) spanned by each chunk. + + Parameters + ---------- + origin : Sequence[int] | None + The first chunk coordinate to return. Defaults to the grid origin. + selection_shape : Sequence[int] | None + The number of chunks per dimension to iterate. Defaults to the + remaining extent from origin. + """ + for coords in self.all_chunk_coords(origin=origin, selection_shape=selection_shape): + spec = self[coords] + if spec is not None: + yield spec.slices + + def get_nchunks(self) -> int: + return reduce(operator.mul, (d.nchunks for d in self._dimensions), 1) + + # -- Resize -- + + def update_shape(self, new_shape: tuple[int, ...]) -> ChunkGrid: + """Return a new ChunkGrid adjusted for *new_shape*. + + For regular (FixedDimension) axes the extent is simply re-bound. + For varying (VaryingDimension) axes: + * **grow**: a new chunk whose size equals the growth is appended. + * **shrink**: trailing chunks that lie entirely beyond *new_shape* are + dropped; the last retained chunk is the one whose cumulative offset + first reaches or exceeds the new extent. + * **no change**: the dimension is kept as-is. + + Raises + ------ + ValueError + If *new_shape* has the wrong number of dimensions. + """ + if len(new_shape) != self.ndim: + raise ValueError( + f"new_shape has {len(new_shape)} dimensions but " + f"chunk grid has {self.ndim} dimensions" + ) + dims = tuple( + dim.resize(new_extent) + for dim, new_extent in zip(self._dimensions, new_shape, strict=True) + ) + return ChunkGrid(dimensions=dims) -def _guess_chunks( +def _guess_regular_chunks( shape: tuple[int, ...] | int, typesize: int, *, @@ -107,105 +717,124 @@ def _guess_chunks( return tuple(int(x) for x in chunks) -def normalize_chunks(chunks: Any, shape: tuple[int, ...], typesize: int) -> tuple[int, ...]: - """Convenience function to normalize the `chunks` argument for an array - with the given `shape`.""" +def normalize_chunks_1d( + chunks: int | Iterable[object], span: int +) -> np.ndarray[tuple[int], np.dtype[np.int64]]: + """ + Normalize a one-dimensional chunk specification into a 1D int64 array of + chunk sizes that cover the span. - # N.B., expect shape already normalized + `-1` means "one chunk covering the entire span." + For an integer chunk size, all chunks are uniform — the last chunk may + overhang the span. The actual data extent of each chunk is determined + by the chunk grid at runtime, not by this function. + """ + # `numbers.Integral` rather than `int` so that numpy integer scalars (which are not + # `int` subclasses) take the uniform-chunk path instead of being treated as a sequence. + if isinstance(chunks, numbers.Integral): + chunk_size = int(chunks) + if chunk_size == -1: + return np.array([span], dtype=np.int64) + if chunk_size <= 0: + raise ValueError(f"Chunk size must be positive, got {chunk_size}") + if span == 0: + return np.array([chunk_size], dtype=np.int64) + n = ceildiv(span, chunk_size) + return np.full(n, chunk_size, dtype=np.int64) + else: + try: + chunk_list = list(chunks) # type: ignore[arg-type] + except TypeError: + raise TypeError( + f"Chunk specification must be an integer or an iterable of integers; got " + f"{chunks!r} of type {type(chunks).__name__}." + ) from None + if not chunk_list: + raise ValueError("Chunk specification must not be empty") + non_int = [ + (idx, c) for idx, c in enumerate(chunk_list) if not isinstance(c, numbers.Integral) + ] + if non_int: + non_int_idxs, non_int_vals = [*zip(*non_int, strict=False)] + raise TypeError( + f"Each chunk size must be an integer; got non-integer element(s) {non_int_vals!r} " + f"at indices {non_int_idxs!r}. Chunk sizes must be declared as a flat sequence of " + f"positive integers (e.g. [3, 3, 1])." + ) + ints: list[int] = [int(c) for c in chunk_list] # type: ignore[call-overload] + if any(c <= 0 for c in ints): + raise ValueError(f"All chunk sizes must be positive, got {ints}") + if sum(ints) != span: + raise ValueError(f"Chunk sizes {ints} do not sum to span {span}") + return np.asarray(ints, dtype=np.int64) + + +def normalize_chunks_nd( + chunks: Any, + shape: tuple[int, ...], +) -> ChunksTuple: + """ + Normalize a chunk specification into a `ChunksTuple`. + + This is a mechanical transformation — no heuristics, no guessing. + Handles `False` ("all data in one chunk"), scalar ints, `-1` sentinels (one chunk + per dimension covering the full span), and explicit per-dimension lists + of chunk sizes (regular or rectilinear). - # handle auto-chunking + For auto-chunking, use `guess_chunks` which returns a + `ChunksTuple` directly. `chunks=None` and `chunks=True` are rejected + here — the caller is responsible for choosing between explicit sizes + and auto-chunking. + """ if chunks is None or chunks is True: - return _guess_chunks(shape, typesize) + raise ValueError( + f'{chunks!r} is not a valid chunk input. Use chunks=None or chunks="auto" from the top-level API for auto-chunking, or pass an int / tuple of ints.' + ) # handle no chunking if chunks is False: - return shape + return ChunksTuple(tuple(np.array([s], dtype=np.int64) for s in shape)) - # handle 1D convenience form + # handle 1D convenience form. bool is excluded above so this only catches actual ints. if isinstance(chunks, numbers.Integral): chunks = tuple(int(chunks) for _ in shape) - # handle dask-style chunks (iterable of iterables) - if all(isinstance(c, (tuple, list)) for c in chunks): - for i, c in enumerate(chunks): - if any(x != y for x, y in itertools.pairwise(c[:-1])) or (len(c) > 1 and c[-1] > c[0]): - raise ValueError( - f"Irregular chunk sizes in dimension {i}: {tuple(c)}. " - "Only uniform chunks (with an optional smaller final chunk) are supported." - ) - chunks = tuple(c[0] for c in chunks) - # handle bad dimensionality - if len(chunks) > len(shape): - raise ValueError("too many dimensions in chunks") - - # handle underspecified chunks - if len(chunks) < len(shape): - # assume chunks across remaining dimensions - chunks += shape[len(chunks) :] - - # handle None or -1 in chunks - if -1 in chunks or None in chunks: - chunks = tuple( - s if c == -1 or c is None else int(c) for s, c in zip(shape, chunks, strict=False) + if len(chunks) != len(shape): + raise ValueError( + f"chunks has {len(chunks)} dimensions but shape has {len(shape)} dimensions" ) - if not all(isinstance(c, numbers.Integral) for c in chunks): - raise TypeError("non integer value in chunks") - - return tuple(int(c) for c in chunks) - - -@dataclass(frozen=True) -class ChunkGrid(Metadata): - @classmethod - def from_dict(cls, data: dict[str, JSON] | ChunkGrid | NamedConfig[str, Any]) -> ChunkGrid: - if isinstance(data, ChunkGrid): - return data - - name_parsed, _ = parse_named_configuration(data) - if name_parsed == "regular": - return RegularChunkGrid._from_dict(data) - raise ValueError(f"Unknown chunk grid. Got {name_parsed}.") - - @abstractmethod - def all_chunk_coords(self, array_shape: tuple[int, ...]) -> Iterator[tuple[int, ...]]: - pass - - @abstractmethod - def get_nchunks(self, array_shape: tuple[int, ...]) -> int: - pass - - -@dataclass(frozen=True) -class RegularChunkGrid(ChunkGrid): - chunk_shape: tuple[int, ...] - - def __init__(self, *, chunk_shape: ShapeLike) -> None: - chunk_shape_parsed = parse_shapelike(chunk_shape) - - object.__setattr__(self, "chunk_shape", chunk_shape_parsed) - - @classmethod - def _from_dict(cls, data: dict[str, JSON] | NamedConfig[str, Any]) -> Self: - _, configuration_parsed = parse_named_configuration(data, "regular") + return ChunksTuple( + tuple(normalize_chunks_1d(c, span=s) for c, s in zip(chunks, shape, strict=True)) + ) - return cls(**configuration_parsed) # type: ignore[arg-type] - def to_dict(self) -> dict[str, JSON]: - return {"name": "regular", "configuration": {"chunk_shape": tuple(self.chunk_shape)}} +def guess_chunks( + shape: tuple[int, ...], typesize: int, *, max_bytes: int | None = None +) -> ChunksTuple: + """ + Heuristically determine chunk sizes for an array. - def all_chunk_coords(self, array_shape: tuple[int, ...]) -> Iterator[tuple[int, ...]]: - return itertools.product( - *(range(ceildiv(s, c)) for s, c in zip(array_shape, self.chunk_shape, strict=False)) - ) + This is the policy function — it makes opinionated choices about + chunk sizes based on array shape and element size, and returns a + normalized `ChunksTuple`. - def get_nchunks(self, array_shape: tuple[int, ...]) -> int: - return reduce( - operator.mul, - itertools.starmap(ceildiv, zip(array_shape, self.chunk_shape, strict=True)), - 1, - ) + Parameters + ---------- + shape : tuple[int, ...] + Array shape. + typesize : int + Size of one element in bytes. + max_bytes : int or None + Target maximum chunk size in bytes. If None, uses the default + heuristic from `_guess_regular_chunks`. + """ + if max_bytes is not None: + flat = _guess_regular_chunks(shape, typesize, max_bytes=max_bytes) + else: + flat = _guess_regular_chunks(shape, typesize) + return normalize_chunks_nd(flat, shape) def _guess_num_chunks_per_axis_shard( @@ -232,7 +861,7 @@ def _guess_num_chunks_per_axis_shard( ------- The number of chunks per axis. """ - bytes_per_chunk = np.prod(chunk_shape) * item_size + bytes_per_chunk = math.prod(chunk_shape) * item_size if max_bytes < bytes_per_chunk: return 1 num_axes = len(chunk_shape) @@ -245,62 +874,76 @@ def _guess_num_chunks_per_axis_shard( return chunks_per_shard -def _auto_partition( +def resolve_outer_and_inner_chunks( *, array_shape: tuple[int, ...], - chunk_shape: tuple[int, ...] | Literal["auto"], + chunks: ChunksTuple, shard_shape: ShardsLike | None, item_size: int, -) -> tuple[tuple[int, ...] | None, tuple[int, ...]]: - """ - Automatically determine the shard shape and chunk shape for an array, given the shape and dtype of the array. - If `shard_shape` is `None` and the chunk_shape is "auto", the chunks will be set heuristically based - on the dtype and shape of the array. - If `shard_shape` is "auto", then the shard shape will be set heuristically from the dtype and shape - of the array; if the `chunk_shape` is also "auto", then the chunks will be set heuristically as well, - given the dtype and shard shape. Otherwise, the chunks will be returned as-is. +) -> ChunkLayout: + """Resolve user `chunks`/`shards` into outer and inner chunk specs. + + Parameters + ---------- + array_shape + The array shape. + chunks + Normalized chunk specification (the user's `chunks=`). + shard_shape + Raw shard specification (the user's `shards=`). + `None` means no sharding, `"auto"` triggers heuristic inference, + a nested sequence is treated as rectilinear shard boundaries, + and anything else is used as a regular shard shape. + item_size + Element size in bytes. + + Returns + ------- + ChunkLayout + `outer_chunks` is the `ChunksTuple` for chunk grid + metadata. `inner` holds the sub-chunk structure for + `ShardingCodec`, or is `None` when sharding is not active. """ if shard_shape is None: - _shards_out: None | tuple[int, ...] = None - if chunk_shape == "auto": - _chunks_out = _guess_chunks(array_shape, item_size) - else: - _chunks_out = chunk_shape - else: - if chunk_shape == "auto": - # aim for a 1MiB chunk - _chunks_out = _guess_chunks(array_shape, item_size, max_bytes=1048576) - else: - _chunks_out = chunk_shape + return ChunkLayout(outer_chunks=chunks) - if shard_shape == "auto": - warnings.warn( - "Automatic shard shape inference is experimental and may change without notice.", - ZarrUserWarning, - stacklevel=2, - ) - _shards_out = () - target_shard_size_bytes = zarr.config.get("array.target_shard_size_bytes", None) - num_chunks_per_shard_axis = ( - _guess_num_chunks_per_axis_shard( - chunk_shape=_chunks_out, - item_size=item_size, - max_bytes=target_shard_size_bytes, - array_shape=array_shape, - ) - if (has_auto_shard := (target_shard_size_bytes is not None)) - else 2 + # Rectilinear shards: normalize the nested sequence directly. + if _is_rectilinear_chunks(shard_shape): + outer = normalize_chunks_nd(shard_shape, array_shape) + return ChunkLayout(outer_chunks=outer, inner=ChunkLayout(outer_chunks=chunks)) + + # Extract the flat chunk shape (first size per dimension) for arithmetic. + chunk_shape_flat = as_regular_shape(chunks) + + if shard_shape == "auto": + warnings.warn( + "Automatic shard shape inference is experimental and may change without notice.", + ZarrUserWarning, + stacklevel=2, + ) + _shards_out: tuple[int, ...] = () + target_shard_size_bytes = zarr.config.get("array.target_shard_size_bytes", None) + num_chunks_per_shard_axis = ( + _guess_num_chunks_per_axis_shard( + chunk_shape=chunk_shape_flat, + item_size=item_size, + max_bytes=target_shard_size_bytes, + array_shape=array_shape, ) - for a_shape, c_shape in zip(array_shape, _chunks_out, strict=True): - # The previous heuristic was `a_shape // c_shape > 8` and now, with target_shard_size_bytes, we only check that the shard size is less than the array size. - can_shard_axis = a_shape // c_shape > 8 if not has_auto_shard else True - if can_shard_axis: - _shards_out += (c_shape * num_chunks_per_shard_axis,) - else: - _shards_out += (c_shape,) - elif isinstance(shard_shape, dict): - _shards_out = tuple(shard_shape["shape"]) - else: - _shards_out = shard_shape + if (has_auto_shard := (target_shard_size_bytes is not None)) + else 2 + ) + for a_shape, c_shape in zip(array_shape, chunk_shape_flat, strict=True): + can_shard_axis = a_shape // c_shape > 8 if not has_auto_shard else True + if can_shard_axis: + _shards_out += (c_shape * num_chunks_per_shard_axis,) + else: + _shards_out += (c_shape,) + shard_flat = _shards_out + elif isinstance(shard_shape, dict): + shard_flat = tuple(shard_shape["shape"]) + else: + shard_flat = cast("tuple[int, ...]", shard_shape) - return _shards_out, _chunks_out + outer = normalize_chunks_nd(shard_flat, array_shape) + return ChunkLayout(outer_chunks=outer, inner=ChunkLayout(outer_chunks=chunks)) diff --git a/src/zarr/core/chunk_key_encodings.py b/src/zarr/core/chunk_key_encodings.py index 9eef80656d..d871e279d2 100644 --- a/src/zarr/core/chunk_key_encodings.py +++ b/src/zarr/core/chunk_key_encodings.py @@ -2,7 +2,7 @@ from abc import ABC, abstractmethod from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, ClassVar, Literal, TypeAlias, TypedDict, cast +from typing import TYPE_CHECKING, Any, ClassVar, Literal, TypedDict, cast if TYPE_CHECKING: from typing import NotRequired, Self @@ -13,15 +13,14 @@ NamedConfig, parse_named_configuration, ) +from zarr.core.json_parse import parse_field from zarr.registry import get_chunk_key_encoding_class, register_chunk_key_encoding SeparatorLiteral = Literal[".", "/"] def parse_separator(data: JSON) -> SeparatorLiteral: - if data not in (".", "/"): - raise ValueError(f"Expected an '.' or '/' separator. Got {data} instead.") - return cast("SeparatorLiteral", data) + return cast("SeparatorLiteral", parse_field(data, Literal[".", "/"], "separator")) class ChunkKeyEncodingParams(TypedDict): @@ -62,7 +61,7 @@ def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: """ -ChunkKeyEncodingLike: TypeAlias = ( +type ChunkKeyEncodingLike = ( dict[str, JSON] | ChunkKeyEncodingParams | ChunkKeyEncoding | NamedConfig[str, Any] ) @@ -79,7 +78,11 @@ def __post_init__(self) -> None: def decode_chunk_key(self, chunk_key: str) -> tuple[int, ...]: if chunk_key == "c": return () - return tuple(map(int, chunk_key[1:].split(self.separator))) + # Strip the "c" prefix (e.g. "c/" or "c.") before splitting. + prefix = "c" + self.separator + if chunk_key.startswith(prefix): + return tuple(map(int, chunk_key[len(prefix) :].split(self.separator))) + raise ValueError(f"Invalid chunk key for default encoding: {chunk_key!r}") def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: return self.separator.join(map(str, ("c",) + chunk_coords)) diff --git a/src/zarr/core/chunk_utils.py b/src/zarr/core/chunk_utils.py new file mode 100644 index 0000000000..b26d5478b2 --- /dev/null +++ b/src/zarr/core/chunk_utils.py @@ -0,0 +1,369 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, cast + +from zarr.abc.codec import GetResult, SupportsSyncCodec, _codec_supports_sync +from zarr.core.indexing import is_scalar + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + + from zarr.abc.codec import Codec + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer, NDBuffer + from zarr.core.indexing import SelectorTuple + + +def evolve_codecs(codecs: Iterable[Codec], array_spec: ArraySpec) -> tuple[Codec, ...]: + """Evolve a codec chain against ``array_spec``, threading the spec forward. + + Each codec is evolved against the spec produced by the previous one — NOT + the original ``array_spec`` — because earlier array->array codecs may + transform the chunk spec (e.g. ``cast_value`` widening int8 -> int16). A + later codec (notably the array->bytes serializer) must be evolved against + the spec it will actually see at run time; evolving every codec against the + unthreaded original spec would, for example, strip a ``BytesCodec``'s + ``endian`` (it sees the single-byte source dtype) and then fail at decode + time on the multi-byte target. + + This is the single source of truth for pipeline-construction-time codec + evolution, shared by every ``CodecPipeline.evolve_from_array_spec``. (The + per-chunk decode/encode counterpart is ``resolve_aa_specs``.) + """ + evolved: list[Codec] = [] + spec = array_spec + for codec in codecs: + evolved_codec = codec.evolve_from_array_spec(array_spec=spec) + evolved.append(evolved_codec) + spec = evolved_codec.resolve_metadata(spec) + return tuple(evolved) + + +def encode_or_elide_chunk( + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + encode: Callable[[NDBuffer, ArraySpec], Buffer | None], +) -> Buffer | None: + """Encode a merged chunk, normalizing empties to missing. + + Returns the bytes to store, or ``None`` meaning the chunk must NOT be + stored (either it normalized to empty per `chunk_is_empty`, or the codec + chain elided it). ``None`` is the single "missing" convention shared by + the chunk write paths and the shard dicts. + """ + + if chunk_is_empty(chunk_array, chunk_spec): + return None + return encode(chunk_array, chunk_spec) + + +def fill_value_or_default(chunk_spec: ArraySpec) -> Any: + fill_value = chunk_spec.fill_value + if fill_value is None: + # Zarr V2 allowed `fill_value` to be null in the metadata. + # Zarr V3 requires it to be set. This has already been + # validated when decoding the metadata, but we support reading + # Zarr V2 data and need to support the case where fill_value + # is None. + return chunk_spec.dtype.default_scalar() + else: + return fill_value + + +def chunk_is_empty(chunk_array: NDBuffer, chunk_spec: ArraySpec) -> bool: + """THE empty-chunk normalization rule, in one place. + + With ``write_empty_chunks=False`` (the default), a chunk whose decoded + content equals the fill value normalizes to *missing*: it must not be + stored, and readers reconstruct it from the fill value. Every write path + (fused, async fallback, shard inner chunks) must apply this same rule — + scattering inline ``all_equal`` checks is how the rule drifts. + """ + return not chunk_spec.config.write_empty_chunks and chunk_array.all_equal( + fill_value_or_default(chunk_spec) + ) + + +def scatter_chunk( + selected: NDBuffer | None, + out: NDBuffer, + *, + chunk_spec: ArraySpec, + out_selection: SelectorTuple, + drop_axes: tuple[int, ...], +) -> GetResult: + """Scatter one chunk's (already-selected) decoded region into ``out``. + + ``None`` = the chunk is missing: the fill value is scattered instead and a + ``missing`` status is returned. POLICY-FREE by design: whether a missing + chunk is an error (``read_missing_chunks=False``) is decided by the array + layer from the returned statuses — which is also what makes missing INNER + chunks of a present shard fill rather than raise (the sharding codec + discards the nested read's statuses; only top-level statuses reach the + array layer). + """ + if selected is None: + out[out_selection] = fill_value_or_default(chunk_spec) + return GetResult(status="missing") + if drop_axes: + selected = selected.squeeze(axis=drop_axes) + out[out_selection] = selected + return GetResult(status="present") + + +def _merge_chunk_array( + existing_chunk_array: NDBuffer | None, + value: NDBuffer, + out_selection: SelectorTuple, + chunk_spec: ArraySpec, + chunk_selection: SelectorTuple, + is_complete_chunk: bool, + drop_axes: tuple[int, ...], +) -> NDBuffer: + """Merge `value` into a full-chunk-shaped NDBuffer at `chunk_selection`. + + If `is_complete_chunk` and `value[out_selection]` is exactly chunk-shaped, + that VIEW of the caller's `value` is returned without copying — callers + (and the codecs they pass it to) must treat it as read-only, since + mutating it would corrupt the user's source array. Otherwise, a writable + buffer is materialized — either from `existing_chunk_array.copy()` if + one was read from the store, or freshly allocated and filled with the + chunk's fill value — and the relevant slice of `value` is written into it. + """ + if is_complete_chunk and value.shape != (): + selected = value[out_selection] + # The shape check guards against a partial edge chunk arriving with + # is_complete_chunk=True, and against dropped axes (size-1 integer + # dims), where the selection is not exactly chunk-shaped. + if selected.shape == chunk_spec.shape: + return selected + if existing_chunk_array is None: + chunk_array = chunk_spec.prototype.nd_buffer.create( + shape=chunk_spec.shape, + dtype=chunk_spec.dtype.to_native_dtype(), + order=chunk_spec.order, + fill_value=fill_value_or_default(chunk_spec), + ) + else: + chunk_array = existing_chunk_array.copy() + if chunk_selection == () or is_scalar( + value.as_ndarray_like(), chunk_spec.dtype.to_native_dtype() + ): + chunk_value = value + else: + chunk_value = value[out_selection] + if drop_axes: + item = tuple( + None if idx in drop_axes else slice(None) for idx in range(chunk_spec.ndim) + ) + chunk_value = chunk_value[item] + chunk_array[chunk_selection] = chunk_value + return chunk_array + + +def merge_and_encode_chunk( + existing_bytes: Buffer | None, + value: NDBuffer, + *, + chunk_spec: ArraySpec, + chunk_selection: SelectorTuple, + out_selection: SelectorTuple, + is_complete: bool, + drop_axes: tuple[int, ...], + decode: Callable[[Buffer, ArraySpec], NDBuffer], + encode: Callable[[NDBuffer, ArraySpec], Buffer | None], +) -> Buffer | None: + """The canonical single-chunk write: merge, normalize, encode. + + decode existing (``None`` = chunk currently missing) -> merge ``value`` at + ``chunk_selection`` -> normalize empties to missing -> encode. Returns the + bytes to store or ``None`` = do not store / delete. This is the one + state-transition every per-chunk write path expresses; only the IO around + it (where ``existing_bytes`` comes from, where the result goes) differs. + """ + + existing_array = decode(existing_bytes, chunk_spec) if existing_bytes is not None else None + merged = _merge_chunk_array( + existing_array, value, out_selection, chunk_spec, chunk_selection, is_complete, drop_axes + ) + return encode_or_elide_chunk(merged, chunk_spec, encode) + + +def decode_and_scatter_chunk( + chunk_bytes: Buffer | None, + out: NDBuffer, + *, + chunk_spec: ArraySpec, + chunk_selection: SelectorTuple, + out_selection: SelectorTuple, + drop_axes: tuple[int, ...], + decode: Callable[[Buffer, ArraySpec], NDBuffer], +) -> GetResult: + """The canonical single-chunk read: decode stored bytes (``None`` = + missing), select, and scatter into ``out`` via `scatter_chunk`. The read + twin of `merge_and_encode_chunk`. + """ + if chunk_bytes is None: + return scatter_chunk( + None, out, chunk_spec=chunk_spec, out_selection=out_selection, drop_axes=drop_axes + ) + selected = decode(chunk_bytes, chunk_spec)[chunk_selection] + return scatter_chunk( + selected, out, chunk_spec=chunk_spec, out_selection=out_selection, drop_axes=drop_axes + ) + + +@dataclass(slots=True, kw_only=True) +class ChunkTransform: + """A synchronous codec chain. + + Provides `encode_chunk` and `decode_chunk` for pure-compute codec + operations (no IO, no threading, no batching). The `chunk_spec` is + supplied per call so the same transform can be reused across chunks + with different shapes, prototypes, etc. + + All codecs must implement `SupportsSyncCodec`. Construction will + raise `TypeError` if any codec does not. + """ + + codecs: tuple[Codec, ...] + + _aa_codecs: tuple[SupportsSyncCodec[NDBuffer, NDBuffer], ...] = field( + init=False, repr=False, compare=False + ) + _ab_codec: SupportsSyncCodec[NDBuffer, Buffer] = field(init=False, repr=False, compare=False) + _bb_codecs: tuple[SupportsSyncCodec[Buffer, Buffer], ...] = field( + init=False, repr=False, compare=False + ) + + def __post_init__(self) -> None: + from zarr.core.codec_pipeline import codecs_from_list_unchecked + + # _codec_supports_sync, not a bare isinstance check: a codec can satisfy + # the SupportsSyncCodec protocol structurally yet be unable to run + # synchronously (ShardingCodec whose inner/index chain contains an + # async-only codec). Such codecs opt out via `_sync_capable`, and the + # TypeError here is what makes FusedCodecPipeline.evolve_from_array_spec + # decline the sync fast path and fall back to the async pipeline. + non_sync = [c for c in self.codecs if not _codec_supports_sync(c)] + if non_sync: + names = ", ".join(type(c).__name__ for c in non_sync) + raise TypeError( + f"All codecs must implement SupportsSyncCodec. The following do not: {names}" + ) + + # `ChunkTransform` is built from a codec chain that already went + # through `codecs_from_list` when the owning pipeline was constructed + # (see `FusedCodecPipeline.evolve_from_array_spec`), so re-splitting it + # here must not re-emit that chain's advisory warnings. + aa, ab, bb = codecs_from_list_unchecked(list(self.codecs)) + # SupportsSyncCodec was verified above; the cast is purely for mypy. + self._aa_codecs = cast("tuple[SupportsSyncCodec[NDBuffer, NDBuffer], ...]", tuple(aa)) + self._ab_codec = cast("SupportsSyncCodec[NDBuffer, Buffer]", ab) + self._bb_codecs = cast("tuple[SupportsSyncCodec[Buffer, Buffer], ...]", tuple(bb)) + + # The whole cache entry — (key, aa_specs, ab_spec) — is stored as ONE field + # and replaced with a single attribute write. A `ChunkTransform` is shared + # across thread-pool workers (read_sync/write_sync with max_workers > 1), and + # storing the key separately from the specs would race: a worker could read a + # freshly-set key while the matching specs were still the previous (or None) + # value. A single tuple assignment is atomic under the GIL, so a reader sees + # either the complete old entry or the complete new one — never a torn mix. + _cache: tuple[ArraySpec, tuple[ArraySpec, ...], ArraySpec] | None = field( + init=False, repr=False, compare=False, default=None + ) + + def _resolve_specs(self, chunk_spec: ArraySpec) -> tuple[tuple[ArraySpec, ...], ArraySpec]: + """Return per-AA-codec input specs and the AB spec for `chunk_spec`. + + The resolved chain depends only on the value of `chunk_spec`, so we cache + it keyed on `chunk_spec` itself (ArraySpec is a frozen, hashable dataclass + — value identity). Keying on `id(chunk_spec)` would be unsafe: ids are + recycled after garbage collection, so a freed spec's id reused by a + different spec (same shape, different prototype/dtype/config) could yield + a stale hit. Value identity avoids that entirely. + + Thread-safety: a benign construction race is possible (two workers with + different specs may each compute and overwrite the single-entry cache — + last writer wins), but a torn read is not, because the entry is written + atomically as one tuple. Worst case is a recompute, never a wrong result. + """ + from zarr.core.codec_pipeline import resolve_aa_specs + + if not self._aa_codecs: + return (), chunk_spec + cache = self._cache + if cache is not None and cache[0] == chunk_spec: + return cache[1], cache[2] + + aa_specs_t, spec = resolve_aa_specs(cast("tuple[Codec, ...]", self._aa_codecs), chunk_spec) + self._cache = (chunk_spec, aa_specs_t, spec) + return aa_specs_t, spec + + def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + """Decode a single chunk through the full codec chain, synchronously. + + Pure compute -- no IO. + + Parameters + ---------- + chunk_bytes : Buffer + The encoded chunk bytes. + chunk_spec : ArraySpec + The array spec describing shape, dtype, fill value, and codec + configuration for this chunk. + """ + aa_specs, ab_spec = self._resolve_specs(chunk_spec) + + data: Buffer = chunk_bytes + for bb_codec in reversed(self._bb_codecs): + data = bb_codec._decode_sync(data, ab_spec) + + chunk_array: NDBuffer = self._ab_codec._decode_sync(data, ab_spec) + + for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): + chunk_array = aa_codec._decode_sync(chunk_array, aa_spec) + + return chunk_array + + def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + """Encode a single chunk through the full codec chain, synchronously. + + Pure compute -- no IO. + + Parameters + ---------- + chunk_array : NDBuffer + The chunk data to encode. + chunk_spec : ArraySpec + The array spec describing shape, dtype, fill value, and codec + configuration for this chunk. + """ + aa_specs, ab_spec = self._resolve_specs(chunk_spec) + + aa_data: NDBuffer = chunk_array + for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): + aa_result = aa_codec._encode_sync(aa_data, aa_spec) + if aa_result is None: + return None + aa_data = aa_result + + ab_result = self._ab_codec._encode_sync(aa_data, ab_spec) + if ab_result is None: + return None + + bb_data: Buffer = ab_result + for bb_codec in self._bb_codecs: + bb_result = bb_codec._encode_sync(bb_data, ab_spec) + if bb_result is None: + return None + bb_data = bb_result + + return bb_data + + def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: + for codec in self.codecs: + byte_length = codec.compute_encoded_size(byte_length, array_spec) + array_spec = codec.resolve_metadata(array_spec) + return byte_length diff --git a/src/zarr/core/codec_pipeline.py b/src/zarr/core/codec_pipeline.py index eed49556d3..597f338c42 100644 --- a/src/zarr/core/codec_pipeline.py +++ b/src/zarr/core/codec_pipeline.py @@ -1,8 +1,11 @@ from __future__ import annotations -from dataclasses import dataclass -from itertools import islice, pairwise -from typing import TYPE_CHECKING, Any, TypeVar +import asyncio +import threading +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +from itertools import batched, chain, pairwise +from typing import TYPE_CHECKING, Any, cast from warnings import warn from zarr.abc.codec import ( @@ -13,28 +16,91 @@ BytesBytesCodec, Codec, CodecPipeline, + GetResult, ) -from zarr.core.common import concurrent_map +from zarr.core.chunk_utils import ( + ChunkTransform, + _merge_chunk_array, + chunk_is_empty, + decode_and_scatter_chunk, + evolve_codecs, + fill_value_or_default, + merge_and_encode_chunk, + scatter_chunk, +) +from zarr.core.common import concurrent_iter, concurrent_map from zarr.core.config import config -from zarr.core.indexing import SelectorTuple, is_scalar from zarr.errors import ZarrUserWarning from zarr.registry import register_pipeline if TYPE_CHECKING: - from collections.abc import Iterable, Iterator + from collections.abc import Iterable, Iterator, Sequence from typing import Self from zarr.abc.store import ByteGetter, ByteSetter from zarr.core.array_spec import ArraySpec from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer - from zarr.core.chunk_grids import ChunkGrid from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.indexing import SelectorTuple + from zarr.core.metadata.v3 import ChunkGridMetadata + + +_pool: ThreadPoolExecutor | None = None +_pool_size: int = 0 +_pool_lock = threading.Lock() + + +def _resolve_max_workers() -> int: + """Helper for getting the maximum number of workers available to the `FusedCodecPipeline`""" + import os as _os + + default = _os.cpu_count() or 1 + cfg = config.get("codec_pipeline.max_workers", default=None) + if cfg is None: + return default + try: + return max(1, int(cfg)) + except (TypeError, ValueError): + # This value arrives via the config/env layer (e.g. + # `ZARR_CODEC_PIPELINE__MAX_WORKERS`), so tolerate bad input here + # instead of raising mid-read. + warn( + f"Ignoring invalid `codec_pipeline.max_workers` config value {cfg!r}; " + f"falling back to {default}.", + category=ZarrUserWarning, + stacklevel=2, + ) + return default + -T = TypeVar("T") -U = TypeVar("U") +def _get_pool(max_workers: int) -> ThreadPoolExecutor: + """Get or create the module-level thread pool, sized to `max_workers`. + The pool grows on demand — if a request arrives for more workers than the + current pool has, it is replaced with a larger one. The previous pool is NOT + shut down here: another thread may be holding a reference to it and about to + submit (`shutdown` would make its `pool.map` raise "cannot schedule new + futures after shutdown"). The orphaned pool finishes its in-flight tasks and + is garbage-collected once no caller references it. The pool only grows, never + shrinks (a shrink request reuses the larger pool, leaving workers idle). -def _unzip2(iterable: Iterable[tuple[T, U]]) -> tuple[list[T], list[U]]: + Callers that want sequential execution should not call this — they + should run the task list inline. `max_workers` must be >= 1. + """ + global _pool, _pool_size + if max_workers < 1: + raise ValueError(f"max_workers must be >= 1, got {max_workers}") + if _pool is None or _pool_size < max_workers: + with _pool_lock: + if _pool is None or _pool_size < max_workers: + # Replace without shutting down the old pool (see docstring): + # avoids a race with a concurrent in-flight pool.map on it. + _pool = ThreadPoolExecutor(max_workers=max_workers) + _pool_size = max_workers + return _pool + + +def _unzip2[T, U](iterable: Iterable[tuple[T, U]]) -> tuple[list[T], list[U]]: out0: list[T] = [] out1: list[U] = [] for item0, item1 in iterable: @@ -43,29 +109,465 @@ def _unzip2(iterable: Iterable[tuple[T, U]]) -> tuple[list[T], list[U]]: return (out0, out1) -def batched(iterable: Iterable[T], n: int) -> Iterable[tuple[T, ...]]: - if n < 1: - raise ValueError("n must be at least one") - it = iter(iterable) - while batch := tuple(islice(it, n)): - yield batch - - def resolve_batched(codec: Codec, chunk_specs: Iterable[ArraySpec]) -> Iterable[ArraySpec]: return [codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] -def fill_value_or_default(chunk_spec: ArraySpec) -> Any: - fill_value = chunk_spec.fill_value - if fill_value is None: - # Zarr V2 allowed `fill_value` to be null in the metadata. - # Zarr V3 requires it to be set. This has already been - # validated when decoding the metadata, but we support reading - # Zarr V2 data and need to support the case where fill_value - # is None. - return chunk_spec.dtype.default_scalar() +def resolve_aa_specs( + aa_codecs: tuple[Codec, ...], chunk_spec: ArraySpec +) -> tuple[tuple[ArraySpec, ...], ArraySpec]: + """Resolve the per-stage chunk specs for a single chunk's codec chain. + + Threads `chunk_spec` forward through the array->array codecs via + `resolve_metadata` (each codec sees the spec produced by the previous one), + returning `(aa_specs, ab_spec)`: + + * `aa_specs[i]` is the spec the i-th AA codec operates on (its *input* on + encode / *output* on decode); + * `ab_spec` is the spec after all AA codecs — what the array->bytes codec + and the bytes->bytes codecs operate on. + + This is the single source of truth for per-stage spec evolution, shared by + the synchronous `ChunkTransform` and the asynchronous + `AsyncChunkTransform`. It is pure metadata (only `resolve_metadata`), so + it places no synchronous-codec requirement on the codecs. + """ + aa_specs: list[ArraySpec] = [] + spec = chunk_spec + for aa_codec in aa_codecs: + aa_specs.append(spec) + spec = aa_codec.resolve_metadata(spec) + return tuple(aa_specs), spec + + +def pipeline_supports_partial_decode( + array_bytes_codec: ArrayBytesCodec, + *, + array_array_codecs: tuple[ArrayArrayCodec, ...], + bytes_bytes_codecs: tuple[BytesBytesCodec, ...], + require_no_aa_bb: bool, +) -> bool: + """Whether a codec pipeline can decode a partial selection without a full read. + + Requires the array->bytes codec to implement + ``ArrayBytesCodecPartialDecodeMixin``. When ``require_no_aa_bb`` is True it + additionally requires no array->array / bytes->bytes codecs, because those + can change the slice<->byte-range correspondence (an AA codec can make the + selection non-contiguous, a BB codec can rewrite the bytes), making partial + decode infeasible. + + Both pipelines pass `require_no_aa_bb=True`: an outer AA/BB codec (e.g. a + compressor wrapping a sharding serializer) must see every byte of the + chunk, so a partial branch that only re-decodes/re-encodes the inner + sharding codec would silently bypass it. + """ + if require_no_aa_bb and (len(array_array_codecs) + len(bytes_bytes_codecs)) != 0: + return False + return isinstance(array_bytes_codec, ArrayBytesCodecPartialDecodeMixin) + + +def pipeline_supports_partial_encode( + array_bytes_codec: ArrayBytesCodec, + *, + array_array_codecs: tuple[ArrayArrayCodec, ...], + bytes_bytes_codecs: tuple[BytesBytesCodec, ...], + require_no_aa_bb: bool, +) -> bool: + """Whether a codec pipeline can encode a partial selection without a full rewrite. + + Mirror of `pipeline_supports_partial_decode` for encoding. + """ + if require_no_aa_bb and (len(array_array_codecs) + len(bytes_bytes_codecs)) != 0: + return False + return isinstance(array_bytes_codec, ArrayBytesCodecPartialEncodeMixin) + + +async def _cancel_and_drain(futures: Iterable[asyncio.Future[Any]]) -> None: + """Cancel every not-yet-done future/task and await its outcome. + + Used to clean up work spawned by a drain loop (`asyncio.as_completed` + + `await`) when the loop exits early via exception. Without this, tasks + already spawned keep running unattended after the caller has moved on, + and an eventual failure surfaces as an unraisable "exception was never + retrieved" warning instead of being observed here. + """ + pending = [f for f in futures if not f.done()] + if len(pending) == 0: + return + for f in pending: + f.cancel() + await asyncio.gather(*pending, return_exceptions=True) + + +async def _fetch_and_decode_as_completed( + batch: Sequence[tuple[ByteGetter | None, ArraySpec]], + transform: ChunkTransform, +) -> list[NDBuffer | None]: + """Concurrently fetch each chunk's bytes and decode it as fetches complete. + + Decoding overlaps with in-flight fetches: each chunk is decoded the moment + its bytes arrive (in a thread pool when one is available, otherwise inline) + rather than waiting for the whole batch to land. A `None` byte getter fetches + nothing and decodes to `None`. Results are returned in input order. + """ + max_workers = _resolve_max_workers() + pool = _get_pool(max_workers) if max_workers > 1 else None + loop = asyncio.get_running_loop() + decode_futures: list[asyncio.Future[NDBuffer | None]] = [loop.create_future() for _ in batch] + + async def _fetch( + idx: int, byte_getter: ByteGetter | None, prototype: BufferPrototype + ) -> tuple[int, Buffer | None]: + return idx, None if byte_getter is None else await byte_getter.get(prototype) + + def _decode(buffer: Buffer | None, chunk_spec: ArraySpec) -> NDBuffer | None: + return None if buffer is None else transform.decode_chunk(buffer, chunk_spec) + + fetch_tasks = concurrent_iter( + [ + (idx, byte_getter, chunk_spec.prototype) + for idx, (byte_getter, chunk_spec) in enumerate(batch) + ], + _fetch, + config.get("async.concurrency"), + ) + try: + for fetch_coro in asyncio.as_completed(fetch_tasks): + idx, buffer = await fetch_coro + chunk_spec = batch[idx][1] + # Bridge both paths to asyncio.Future so the final collection loop + # can `await` uniformly without blocking the event loop. For the + # pool path that means `wrap_future` (not `pool.submit(...).result()`, + # which would block the loop thread for the duration of every decode + # — freezing any unrelated coroutines sharing this loop). + if pool is None: + decode_futures[idx].set_result(_decode(buffer, chunk_spec)) + else: + decode_futures[idx] = asyncio.wrap_future(pool.submit(_decode, buffer, chunk_spec)) + + return await asyncio.gather(*decode_futures) + finally: + # On the happy path every future here is already done, so this is a + # no-op; on failure it stops abandoned fetches/decodes from + # continuing to run unattended after this function has raised. A + # single call over both iterables (not two sequential calls) so that + # outer-task cancellation during the first drain can't skip the + # second, leaving its futures/tasks unobserved. + await _cancel_and_drain(chain(fetch_tasks, decode_futures)) + + +async def _encode_and_write_as_completed( + batch: Sequence[tuple[ByteSetter, NDBuffer | None, ArraySpec]], + transform: ChunkTransform, +) -> None: + """Encode each chunk and write it out as encodes complete. + + The reverse of `_fetch_and_decode_as_completed`: each chunk is encoded (in a + thread pool when one is available, otherwise inline) and its write is launched + the moment that chunk's encode finishes — overlapping IO writes with + still-running encodes rather than waiting for the whole batch to encode. + A `None` chunk array encodes to `None` and is `delete`d. Writes are bounded + by `async.concurrency`. + """ + max_workers = _resolve_max_workers() + pool = _get_pool(max_workers) if max_workers > 1 else None + loop = asyncio.get_running_loop() + semaphore = asyncio.Semaphore(config.get("async.concurrency")) + + def _encode( + idx: int, chunk_array: NDBuffer | None, chunk_spec: ArraySpec + ) -> tuple[int, Buffer | None]: + return idx, None if chunk_array is None else transform.encode_chunk(chunk_array, chunk_spec) + + async def _write(idx: int, chunk_bytes: Buffer | None) -> None: + byte_setter = batch[idx][0] + async with semaphore: + if chunk_bytes is None: + await byte_setter.delete() + else: + await byte_setter.set(chunk_bytes) + + # Submit every encode up front. The pool path bridges to asyncio.Future via + # `wrap_future` (not `pool.submit(...).result()`, which would block the loop + # thread); the inline path resolves immediately. + encode_futures: list[asyncio.Future[tuple[int, Buffer | None]]] = [] + for idx, (_, chunk_array, chunk_spec) in enumerate(batch): + if pool is None: + fut: asyncio.Future[tuple[int, Buffer | None]] = loop.create_future() + fut.set_result(_encode(idx, chunk_array, chunk_spec)) + else: + fut = asyncio.wrap_future(pool.submit(_encode, idx, chunk_array, chunk_spec)) + encode_futures.append(fut) + + # Kick off each chunk's write the instant its encode lands, so writes of + # already-compressed chunks proceed while the rest are still encoding. + write_tasks: list[asyncio.Task[None]] = [] + try: + for encode_coro in asyncio.as_completed(encode_futures): + idx, chunk_bytes = await encode_coro + write_tasks.append(asyncio.ensure_future(_write(idx, chunk_bytes))) + await asyncio.gather(*write_tasks) + finally: + # On the happy path every future here is already done, so this is a + # no-op; on failure (an encode or a write raising) it stops + # already-spawned writes from continuing in the background after + # this function has raised. A single call over both iterables (not + # two sequential calls) so that outer-task cancellation during the + # first drain can't skip the second, leaving its futures/tasks + # unobserved. + await _cancel_and_drain(chain(write_tasks, encode_futures)) + + +async def _async_read_fallback( + pipeline: CodecPipeline, + batch: list[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...], +) -> tuple[GetResult, ...]: + """Async fallback read used when no fast-path is available. + + Fetches every chunk's bytes via `concurrent_map` (sized by + `async.concurrency`), decodes the batch through `pipeline.decode`, + then scatters each decoded chunk into `out` at its `out_selection`. + + Used by both `BatchedCodecPipeline.read_batch` (non-partial-decode + branch) and `FusedCodecPipeline.read` (when the store does not advertise + sync IO / sync transform is unavailable). + """ + + chunk_array_batch: list[NDBuffer | None] + + if isinstance(pipeline, FusedCodecPipeline) and pipeline.sync_transform is not None: + chunk_array_batch = await _fetch_and_decode_as_completed( + [(byte_getter, chunk_spec) for byte_getter, chunk_spec, *_ in batch], + pipeline.sync_transform, + ) else: - return fill_value + chunk_bytes_batch = await concurrent_map( + [(byte_getter, array_spec.prototype) for byte_getter, array_spec, *_ in batch], + lambda byte_getter, prototype: byte_getter.get(prototype), + config.get("async.concurrency"), + ) + chunk_array_batch = list( + await pipeline.decode( + [ + (chunk_bytes, chunk_spec) + for chunk_bytes, (_, chunk_spec, *_) in zip( + chunk_bytes_batch, batch, strict=False + ) + ], + ) + ) + + results: list[GetResult] = [] + for chunk_array, (_, chunk_spec, chunk_selection, out_selection, _) in zip( + chunk_array_batch, batch, strict=True + ): + selected = None if chunk_array is None else chunk_array[chunk_selection] + results.append( + scatter_chunk( + selected, + out, + chunk_spec=chunk_spec, + out_selection=out_selection, + drop_axes=drop_axes, + ) + ) + return tuple(results) + + +async def _async_write_fallback( + pipeline: CodecPipeline, + batch: list[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...], +) -> None: + """Async fallback write used when no fast-path is available. + + For each chunk in `batch`: read its existing bytes from the store + (skipping the read for complete chunks), decode the batch via + `pipeline.decode`, merge `value` into each decoded chunk via + `_merge_chunk_array`, drop chunks that are all-fill when + `write_empty_chunks` is False, encode the surviving chunks via + `pipeline.encode`, then `set` the encoded bytes (or `delete` + if encoding produced `None` or the chunk dropped). + + Used by both `BatchedCodecPipeline.write_batch` (non-partial-encode + branch) and `FusedCodecPipeline.write` (when the store does not advertise + sync IO / sync transform is unavailable). + """ + + if use_sync := ( + isinstance(pipeline, FusedCodecPipeline) and pipeline.sync_transform is not None + ): + # Read each chunk's existing bytes (skipping complete chunks) and decode + # as fetches complete, overlapping the sync decode with in-flight reads. + chunk_array_decoded: Iterable[NDBuffer | None] = await _fetch_and_decode_as_completed( + [ + (None if is_complete_chunk else byte_setter, chunk_spec) + for byte_setter, chunk_spec, _, _, is_complete_chunk in batch + ], + pipeline.sync_transform, + ) + else: + + async def _read_key( + byte_setter: ByteSetter | None, prototype: BufferPrototype + ) -> Buffer | None: + if byte_setter is None: + return None + return await byte_setter.get(prototype=prototype) + + chunk_bytes_batch: Iterable[Buffer | None] = await concurrent_map( + [ + ( + None if is_complete_chunk else byte_setter, + chunk_spec.prototype, + ) + for byte_setter, chunk_spec, chunk_selection, _, is_complete_chunk in batch + ], + _read_key, + config.get("async.concurrency"), + ) + chunk_array_decoded = await pipeline.decode( + [ + (chunk_bytes, chunk_spec) + for chunk_bytes, (_, chunk_spec, *_) in zip(chunk_bytes_batch, batch, strict=False) + ], + ) + chunk_array_merged = [ + _merge_chunk_array( + chunk_array, + value, + out_selection, + chunk_spec, + chunk_selection, + is_complete_chunk, + drop_axes, + ) + for chunk_array, ( + _, + chunk_spec, + chunk_selection, + out_selection, + is_complete_chunk, + ) in zip(chunk_array_decoded, batch, strict=False) + ] + # _merge_chunk_array always returns a real NDBuffer (never None), so the only + # way a chunk drops to None here is the empty-chunk normalization. + chunk_array_batch: list[NDBuffer | None] = [ + None if chunk_is_empty(chunk_array, chunk_spec) else chunk_array + for chunk_array, (_, chunk_spec, *_) in zip(chunk_array_merged, batch, strict=False) + ] + + if use_sync: + sync_transform = cast(FusedCodecPipeline, pipeline).sync_transform + assert sync_transform is not None + await _encode_and_write_as_completed( + [ + (byte_setter, chunk_array, chunk_spec) + for chunk_array, (byte_setter, chunk_spec, *_) in zip( + chunk_array_batch, batch, strict=False + ) + ], + sync_transform, + ) + else: + chunk_bytes_batch = await pipeline.encode( + [ + (chunk_array, chunk_spec) + for chunk_array, (_, chunk_spec, *_) in zip(chunk_array_batch, batch, strict=False) + ], + ) + + async def _write_key(byte_setter: ByteSetter, chunk_bytes: Buffer | None) -> None: + if chunk_bytes is None: + await byte_setter.delete() + else: + await byte_setter.set(chunk_bytes) + + await concurrent_map( + [ + (byte_setter, chunk_bytes) + for chunk_bytes, (byte_setter, *_) in zip(chunk_bytes_batch, batch, strict=False) + ], + _write_key, + config.get("async.concurrency"), + ) + + +@dataclass(slots=True, kw_only=True) +class AsyncChunkTransform: + """A per-chunk asynchronous codec chain — the async mirror of ChunkTransform. + + Decodes/encodes a SINGLE chunk through the full codec chain, awaiting each + codec's per-chunk async method (`_decode_single`/`_encode_single`) with the + correctly-evolved per-stage spec (via the shared `resolve_aa_specs`). + + Unlike ChunkTransform it places no `SupportsSyncCodec` requirement on the + codecs, so it works for async-only codecs. Unlike the batched codec API it + operates on one chunk at a time — the mini-batch fan-out is a + BatchedCodecPipeline concern and deliberately not reintroduced here. + """ + + codecs: tuple[Codec, ...] + + _aa_codecs: tuple[ArrayArrayCodec, ...] = field(init=False, repr=False, compare=False) + _ab_codec: ArrayBytesCodec = field(init=False, repr=False, compare=False) + _bb_codecs: tuple[BytesBytesCodec, ...] = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + # `AsyncChunkTransform` is (re)constructed per decode/encode call from a + # codec chain that already went through `codecs_from_list` when the + # pipeline itself was built, so re-splitting it here must not re-emit + # that chain's advisory warnings on every call. + aa, ab, bb = codecs_from_list_unchecked(list(self.codecs)) + self._aa_codecs = aa + self._ab_codec = ab + self._bb_codecs = bb + + async def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + """Decode one chunk through the chain (bb -> ab -> aa), async.""" + aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) + + data: Buffer = chunk_bytes + for bb_codec in reversed(self._bb_codecs): + data = await bb_codec._decode_single(data, ab_spec) + + chunk_array: NDBuffer = await self._ab_codec._decode_single(data, ab_spec) + + for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): + chunk_array = await aa_codec._decode_single(chunk_array, aa_spec) + + return chunk_array + + async def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + """Encode one chunk through the chain (aa -> ab -> bb), async. + + Returns None if any stage drops the chunk (e.g. an all-fill chunk under + write_empty_chunks=False), matching ChunkTransform.encode_chunk. + """ + aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) + + aa_data: NDBuffer = chunk_array + for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): + aa_result = await aa_codec._encode_single(aa_data, aa_spec) + if aa_result is None: + return None + aa_data = aa_result + + ab_result = await self._ab_codec._encode_single(aa_data, ab_spec) + if ab_result is None: + return None + + bb_data: Buffer = ab_result + for bb_codec in self._bb_codecs: + bb_result = await bb_codec._encode_single(bb_data, ab_spec) + if bb_result is None: + return None + bb_data = bb_result + + return bb_data @dataclass(frozen=True) @@ -83,7 +585,19 @@ class BatchedCodecPipeline(CodecPipeline): batch_size: int def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: - return type(self).from_codecs(c.evolve_from_array_spec(array_spec=array_spec) for c in self) + # Re-splits an already-`codecs_from_list`-validated (and warned-about) + # chain against the evolved spec, so this uses the quiet variant rather + # than routing through `from_codecs` (which would re-warn). + evolved_codecs = evolve_codecs(self, array_spec) + array_array_codecs, array_bytes_codec, bytes_bytes_codecs = codecs_from_list_unchecked( + evolved_codecs + ) + return type(self)( + array_array_codecs=array_array_codecs, + array_bytes_codec=array_bytes_codec, + bytes_bytes_codecs=bytes_bytes_codecs, + batch_size=self.batch_size, + ) @classmethod def from_codecs(cls, codecs: Iterable[Codec], *, batch_size: int | None = None) -> Self: @@ -98,34 +612,22 @@ def from_codecs(cls, codecs: Iterable[Codec], *, batch_size: int | None = None) @property def supports_partial_decode(self) -> bool: - """Determines whether the codec pipeline supports partial decoding. - - Currently, only codec pipelines with a single ArrayBytesCodec that supports - partial decoding can support partial decoding. This limitation is due to the fact - that ArrayArrayCodecs can change the slice selection leading to non-contiguous - slices and BytesBytesCodecs can change the chunk bytes in a way that slice - selections cannot be attributed to byte ranges anymore which renders partial - decoding infeasible. - - This limitation may softened in the future.""" - return (len(self.array_array_codecs) + len(self.bytes_bytes_codecs)) == 0 and isinstance( - self.array_bytes_codec, ArrayBytesCodecPartialDecodeMixin + # Only a single ArrayBytesCodec that supports partial decoding, and no + # AA/BB codecs (they break the slice<->byte-range correspondence). + return pipeline_supports_partial_decode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, ) @property def supports_partial_encode(self) -> bool: - """Determines whether the codec pipeline supports partial encoding. - - Currently, only codec pipelines with a single ArrayBytesCodec that supports - partial encoding can support partial encoding. This limitation is due to the fact - that ArrayArrayCodecs can change the slice selection leading to non-contiguous - slices and BytesBytesCodecs can change the chunk bytes in a way that slice - selections cannot be attributed to byte ranges anymore which renders partial - encoding infeasible. - - This limitation may softened in the future.""" - return (len(self.array_array_codecs) + len(self.bytes_bytes_codecs)) == 0 and isinstance( - self.array_bytes_codec, ArrayBytesCodecPartialEncodeMixin + return pipeline_supports_partial_encode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, ) def __iter__(self) -> Iterator[Codec]: @@ -138,7 +640,7 @@ def validate( *, shape: tuple[int, ...], dtype: ZDType[TBaseDType, TBaseScalar], - chunk_grid: ChunkGrid, + chunk_grid: ChunkGridMetadata, ) -> None: for codec in self: codec.validate(shape=shape, dtype=dtype, chunk_grid=chunk_grid) @@ -251,91 +753,29 @@ async def read_batch( batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], out: NDBuffer, drop_axes: tuple[int, ...] = (), - ) -> None: + ) -> tuple[GetResult, ...]: if self.supports_partial_decode: + results: list[GetResult] = [] + batch_info_list = list(batch_info) chunk_array_batch = await self.decode_partial_batch( [ (byte_getter, chunk_selection, chunk_spec) - for byte_getter, chunk_spec, chunk_selection, *_ in batch_info + for byte_getter, chunk_spec, chunk_selection, *_ in batch_info_list ] ) for chunk_array, (_, chunk_spec, _, out_selection, _) in zip( - chunk_array_batch, batch_info, strict=False + chunk_array_batch, batch_info_list, strict=False ): if chunk_array is not None: if drop_axes: chunk_array = chunk_array.squeeze(axis=drop_axes) out[out_selection] = chunk_array + results.append(GetResult(status="present")) else: out[out_selection] = fill_value_or_default(chunk_spec) - else: - chunk_bytes_batch = await concurrent_map( - [(byte_getter, array_spec.prototype) for byte_getter, array_spec, *_ in batch_info], - lambda byte_getter, prototype: byte_getter.get(prototype), - config.get("async.concurrency"), - ) - chunk_array_batch = await self.decode_batch( - [ - (chunk_bytes, chunk_spec) - for chunk_bytes, (_, chunk_spec, *_) in zip( - chunk_bytes_batch, batch_info, strict=False - ) - ], - ) - for chunk_array, (_, chunk_spec, chunk_selection, out_selection, _) in zip( - chunk_array_batch, batch_info, strict=False - ): - if chunk_array is not None: - tmp = chunk_array[chunk_selection] - if drop_axes: - tmp = tmp.squeeze(axis=drop_axes) - out[out_selection] = tmp - else: - out[out_selection] = fill_value_or_default(chunk_spec) - - def _merge_chunk_array( - self, - existing_chunk_array: NDBuffer | None, - value: NDBuffer, - out_selection: SelectorTuple, - chunk_spec: ArraySpec, - chunk_selection: SelectorTuple, - is_complete_chunk: bool, - drop_axes: tuple[int, ...], - ) -> NDBuffer: - if ( - is_complete_chunk - and value.shape == chunk_spec.shape - # Guard that this is not a partial chunk at the end with is_complete_chunk=True - and value[out_selection].shape == chunk_spec.shape - ): - return value - if existing_chunk_array is None: - chunk_array = chunk_spec.prototype.nd_buffer.create( - shape=chunk_spec.shape, - dtype=chunk_spec.dtype.to_native_dtype(), - order=chunk_spec.order, - fill_value=fill_value_or_default(chunk_spec), - ) - else: - chunk_array = existing_chunk_array.copy() # make a writable copy - if chunk_selection == () or is_scalar( - value.as_ndarray_like(), chunk_spec.dtype.to_native_dtype() - ): - chunk_value = value - else: - chunk_value = value[out_selection] - # handle missing singleton dimensions - if drop_axes: - item = tuple( - None # equivalent to np.newaxis - if idx in drop_axes - else slice(None) - for idx in range(chunk_spec.ndim) - ) - chunk_value = chunk_value[item] - chunk_array[chunk_selection] = chunk_value - return chunk_array + results.append(GetResult(status="missing")) + return tuple(results) + return await _async_read_fallback(self, list(batch_info), out, drop_axes) async def write_batch( self, @@ -360,93 +800,8 @@ async def write_batch( ], ) - else: - # Read existing bytes if not total slice - async def _read_key( - byte_setter: ByteSetter | None, prototype: BufferPrototype - ) -> Buffer | None: - if byte_setter is None: - return None - return await byte_setter.get(prototype=prototype) - - chunk_bytes_batch: Iterable[Buffer | None] - chunk_bytes_batch = await concurrent_map( - [ - ( - None if is_complete_chunk else byte_setter, - chunk_spec.prototype, - ) - for byte_setter, chunk_spec, chunk_selection, _, is_complete_chunk in batch_info - ], - _read_key, - config.get("async.concurrency"), - ) - chunk_array_decoded = await self.decode_batch( - [ - (chunk_bytes, chunk_spec) - for chunk_bytes, (_, chunk_spec, *_) in zip( - chunk_bytes_batch, batch_info, strict=False - ) - ], - ) - - chunk_array_merged = [ - self._merge_chunk_array( - chunk_array, - value, - out_selection, - chunk_spec, - chunk_selection, - is_complete_chunk, - drop_axes, - ) - for chunk_array, ( - _, - chunk_spec, - chunk_selection, - out_selection, - is_complete_chunk, - ) in zip(chunk_array_decoded, batch_info, strict=False) - ] - chunk_array_batch: list[NDBuffer | None] = [] - for chunk_array, (_, chunk_spec, *_) in zip( - chunk_array_merged, batch_info, strict=False - ): - if chunk_array is None: - chunk_array_batch.append(None) # type: ignore[unreachable] - else: - if not chunk_spec.config.write_empty_chunks and chunk_array.all_equal( - fill_value_or_default(chunk_spec) - ): - chunk_array_batch.append(None) - else: - chunk_array_batch.append(chunk_array) - - chunk_bytes_batch = await self.encode_batch( - [ - (chunk_array, chunk_spec) - for chunk_array, (_, chunk_spec, *_) in zip( - chunk_array_batch, batch_info, strict=False - ) - ], - ) - - async def _write_key(byte_setter: ByteSetter, chunk_bytes: Buffer | None) -> None: - if chunk_bytes is None: - await byte_setter.delete() - else: - await byte_setter.set(chunk_bytes) - - await concurrent_map( - [ - (byte_setter, chunk_bytes) - for chunk_bytes, (byte_setter, *_) in zip( - chunk_bytes_batch, batch_info, strict=False - ) - ], - _write_key, - config.get("async.concurrency"), - ) + return + await _async_write_fallback(self, list(batch_info), value, drop_axes) async def decode( self, @@ -471,8 +826,8 @@ async def read( batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], out: NDBuffer, drop_axes: tuple[int, ...] = (), - ) -> None: - await concurrent_map( + ) -> tuple[GetResult, ...]: + batch_results = await concurrent_map( [ (single_batch_info, out, drop_axes) for single_batch_info in batched(batch_info, self.batch_size) @@ -480,6 +835,10 @@ async def read( self.read_batch, config.get("async.concurrency"), ) + results: list[GetResult] = [] + for batch in batch_results: + results.extend(batch) + return tuple(results) async def write( self, @@ -500,19 +859,44 @@ async def write( def codecs_from_list( codecs: Iterable[Codec], ) -> tuple[tuple[ArrayArrayCodec, ...], ArrayBytesCodec, tuple[BytesBytesCodec, ...]]: + """Split `codecs` into `(array_array, array_bytes, bytes_bytes)`, validating order. + + Emits user-facing advisory warnings about the codec chain (e.g. sharding's + "disables partial reads" warning). Use this for the FIRST construction of a + codec chain from user-supplied codecs. Use `codecs_from_list_unchecked` when + re-splitting a chain that was already validated and warned about by a prior + `codecs_from_list` call (e.g. `evolve_from_array_spec` re-splitting the same + codecs against an evolved spec) — re-warning there would fire the same + advisory once per reconstruction instead of once per user-facing chain. + """ from zarr.codecs.sharding import ShardingCodec - array_array: tuple[ArrayArrayCodec, ...] = () - array_bytes_maybe: ArrayBytesCodec | None = None - bytes_bytes: tuple[BytesBytesCodec, ...] = () + codecs = tuple(codecs) # materialize to avoid generator consumption issues - if any(isinstance(codec, ShardingCodec) for codec in codecs) and len(tuple(codecs)) > 1: + if any(isinstance(codec, ShardingCodec) for codec in codecs) and len(codecs) > 1: warn( "Combining a `sharding_indexed` codec disables partial reads and " "writes, which may lead to inefficient performance.", category=ZarrUserWarning, stacklevel=3, ) + return codecs_from_list_unchecked(codecs) + + +def codecs_from_list_unchecked( + codecs: Iterable[Codec], +) -> tuple[tuple[ArrayArrayCodec, ...], ArrayBytesCodec, tuple[BytesBytesCodec, ...]]: + """Split `codecs` into `(array_array, array_bytes, bytes_bytes)`, validating order. + + Same structural validation as `codecs_from_list` (raises on bad codec + ordering or a missing/duplicate array-bytes codec) but does NOT emit + user-facing advisory warnings. See `codecs_from_list` for when to use each. + """ + codecs = tuple(codecs) # materialize to avoid generator consumption issues + + array_array: tuple[ArrayArrayCodec, ...] = () + array_bytes_maybe: ArrayBytesCodec | None = None + bytes_bytes: tuple[BytesBytesCodec, ...] = () for prev_codec, cur_codec in pairwise((None, *codecs)): if isinstance(cur_codec, ArrayArrayCodec): @@ -549,6 +933,7 @@ def codecs_from_list( "must be preceded by either another BytesBytesCodec, or an ArrayBytesCodec. " f"Got {type(prev_codec)} instead." ) + raise TypeError(msg) bytes_bytes += (cur_codec,) else: raise TypeError @@ -560,3 +945,411 @@ def codecs_from_list( register_pipeline(BatchedCodecPipeline) + + +@dataclass(frozen=True) +class FusedCodecPipeline(CodecPipeline): + """Codec pipeline that runs codec compute synchronously, in bulk. + + This is an opt-in alternative to `BatchedCodecPipeline`. The win is NOT + "separating IO from compute" — the codecs (notably `ShardingCodec`) still + perform their own storage IO. The win is replacing the batched pipeline's + per-chunk *async scheduling* (≈one coroutine per chunk, which dominates real + codec work) with synchronous, batched/coalesced execution: + + 1. When every codec implements `SupportsSyncCodec`, a `ChunkTransform` + runs the codec chain synchronously (no event loop, no per-chunk coroutine) + — optionally across a thread pool for CPU-heavy decode/encode. + 2. Sharded reads use the codec's synchronous IO methods: byte-range reads + coalesced via `Store.get_ranges_sync`, and a vectorized whole-shard bulk + decode for dense, fixed-size, uncompressed shards. Sharded writes go + through the codec's synchronous full-shard-rewrite path. + 3. When the store lacks synchronous IO (e.g. ZipStore) the pipeline falls + back to the async path, equivalent to `BatchedCodecPipeline`. + + IO ownership: the sharding codec holds the byte getter/setter and reads/ + writes storage directly (the same model as zarrs; unlike tensorstore, which + keeps codecs storage-free). A storage-free codec is a possible future + direction (see the pure-codec design notes) but is explicitly NOT what this + pipeline does. + """ + + codecs: tuple[Codec, ...] + array_array_codecs: tuple[ArrayArrayCodec, ...] + array_bytes_codec: ArrayBytesCodec + bytes_bytes_codecs: tuple[BytesBytesCodec, ...] + sync_transform: ChunkTransform | None + batch_size: int + + @classmethod + def from_codecs(cls, codecs: Iterable[Codec], *, batch_size: int | None = None) -> Self: + codec_list = tuple(codecs) + aa, ab, bb = codecs_from_list(codec_list) + + if batch_size is None: + batch_size = config.get("codec_pipeline.batch_size") + + return cls( + codecs=codec_list, + array_array_codecs=aa, + array_bytes_codec=ab, + bytes_bytes_codecs=bb, + sync_transform=None, + batch_size=batch_size, + ) + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: + # Re-splits an already-`codecs_from_list`-validated (and warned-about) + # chain against the evolved spec, so this uses the quiet variant to + # avoid re-emitting the same advisory warning on every array open. + evolved_codecs = evolve_codecs(self.codecs, array_spec) + aa, ab, bb = codecs_from_list_unchecked(evolved_codecs) + + try: + sync_transform: ChunkTransform | None = ChunkTransform(codecs=evolved_codecs) + except TypeError: + sync_transform = None + + return type(self)( + codecs=evolved_codecs, + array_array_codecs=aa, + array_bytes_codec=ab, + bytes_bytes_codecs=bb, + sync_transform=sync_transform, + batch_size=self.batch_size, + ) + + def __iter__(self) -> Iterator[Codec]: + return iter(self.codecs) + + @property + def supports_partial_decode(self) -> bool: + return pipeline_supports_partial_decode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, + ) + + @property + def supports_partial_encode(self) -> bool: + return pipeline_supports_partial_encode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, + ) + + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: + for codec in self.codecs: + codec.validate(shape=shape, dtype=dtype, chunk_grid=chunk_grid) + + def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: + for codec in self: + byte_length = codec.compute_encoded_size(byte_length, array_spec) + array_spec = codec.resolve_metadata(array_spec) + return byte_length + + # -- async decode/encode (required by ABC) and sync versions -- + + async def decode( + self, + chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], + ) -> Iterable[NDBuffer | None]: + # Decode each chunk through AsyncChunkTransform, which threads the + # per-stage spec correctly (via resolve_aa_specs). This is the single + # source of truth for async per-chunk decode; earlier this method + # reused one flat `chunk_specs` across every codec stage, which silently + # corrupted/crashed spec-changing codecs (transpose/cast/scale_offset) + # on the async fallback path. + async_transform = AsyncChunkTransform(codecs=self.codecs) + out: list[NDBuffer | None] = [] + for chunk_bytes, chunk_spec in chunk_bytes_and_specs: + if chunk_bytes is None: + out.append(None) + else: + out.append(await async_transform.decode_chunk(chunk_bytes, chunk_spec)) + return out + + async def encode( + self, + chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], + ) -> Iterable[Buffer | None]: + async_transform = AsyncChunkTransform(codecs=self.codecs) + out: list[Buffer | None] = [] + for chunk_array, chunk_spec in chunk_arrays_and_specs: + if chunk_array is None: + out.append(None) + else: + out.append(await async_transform.encode_chunk(chunk_array, chunk_spec)) + return out + + # -- sync read/write -- + + def read_sync( + self, + batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...] = (), + max_workers: int = 1, + ) -> tuple[GetResult, ...]: + """Synchronous read: fetch -> decode -> scatter, per chunk. + + When `max_workers > 1` and there are multiple chunks, each + chunk's full lifecycle (fetch + decode + scatter) runs as one + task on a thread pool sized to `max_workers` — overlapping IO + of one chunk with decode/scatter of another. Scatter is + thread-safe because the chunks have non-overlapping output + selections. + + `max_workers=1` runs everything sequentially in the calling + thread (no pool involvement). + + Mirrors `BatchedCodecPipeline.read_batch`: when the AB codec + supports partial decoding (e.g. sharding), the codec handles its + own IO and only fetches the inner-chunk byte ranges that overlap + the read selection. Otherwise the pipeline fetches the full + blob and decodes the whole chunk. + """ + assert self.sync_transform is not None + transform = self.sync_transform + + batch = list(batch_info) + if not batch: + return () + + # Partial-decode fast path: the AB codec owns IO (read only the + # byte ranges needed for the requested selection). Same condition + # and dispatch as BatchedCodecPipeline.read_batch, plus a gate on the + # sync partial method: the public partial-decode contract + # (`ArrayBytesCodecPartialDecodeMixin`) only requires the async + # `_decode_partial_single`, so a codec may support partial decode + # without `_decode_partial_sync` — such codecs take the full-chunk + # path below instead. + codec = self.array_bytes_codec + if self.supports_partial_decode and hasattr(codec, "_decode_partial_sync"): + + def _read_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> GetResult: + byte_getter, chunk_spec, chunk_selection, out_selection, _ = item + # the partial decode returns the already-selected region + decoded = codec._decode_partial_sync(byte_getter, chunk_selection, chunk_spec) + return scatter_chunk( + decoded, + out, + chunk_spec=chunk_spec, + out_selection=out_selection, + drop_axes=drop_axes, + ) + + else: + # Per-chunk fused path: fetch + decode + scatter as one task. + def _read_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> GetResult: + byte_getter, chunk_spec, chunk_selection, out_selection, _ = item + raw = byte_getter.get_sync(prototype=chunk_spec.prototype) + return decode_and_scatter_chunk( + raw, + out, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + drop_axes=drop_axes, + decode=transform.decode_chunk, + ) + + if max_workers > 1 and len(batch) > 1: + pool = _get_pool(max_workers) + return tuple(pool.map(_read_one, batch)) + return tuple(_read_one(item) for item in batch) + + def write_sync( + self, + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...] = (), + max_workers: int = 1, + ) -> None: + """Synchronous write: fetch existing -> merge+encode -> store. + + When `max_workers > 1` and there are multiple chunks, each + chunk's full lifecycle (get-existing + merge + encode + set/delete) + runs as one task on a thread pool sized to `max_workers` — + overlapping IO of one chunk with compute of another. + + `max_workers=1` runs everything sequentially in the calling + thread (no pool involvement). + + When the codec pipeline supports partial encoding (e.g. a + sharding codec with no outer AA/BB codecs), the AB codec handles + the full write cycle — reading existing data, merging, encoding, + and writing — matching the async `BatchedCodecPipeline` path. + """ + assert self.sync_transform is not None + transform = self.sync_transform + + batch = list(batch_info) + if not batch: + return + + # Partial-encode path: the AB codec owns IO (read, merge, encode, + # write). Same condition and calling convention as + # BatchedCodecPipeline.write_batch, plus a gate on the sync partial + # method: the public partial-encode contract + # (`ArrayBytesCodecPartialEncodeMixin`) only requires the async + # `_encode_partial_single`, so a codec may support partial encode + # without `_encode_partial_sync` — such codecs take the full-chunk + # path below instead. + codec = self.array_bytes_codec + if self.supports_partial_encode and hasattr(codec, "_encode_partial_sync"): + scalar = len(value.shape) == 0 + + def _write_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> None: + bs, chunk_spec, chunk_selection, out_selection, _is_complete = item + chunk_value = value if scalar else value[out_selection] + codec._encode_partial_sync(bs, chunk_value, chunk_selection, chunk_spec) + + else: + # Per-chunk fused path: get-existing + merge + encode + set/delete as one task. + def _write_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> None: + bs, chunk_spec, chunk_selection, out_selection, is_complete = item + existing_bytes: Buffer | None = None + if not is_complete: + existing_bytes = bs.get_sync(prototype=chunk_spec.prototype) + + encoded = merge_and_encode_chunk( + existing_bytes, + value, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + is_complete=is_complete, + drop_axes=drop_axes, + decode=transform.decode_chunk, + encode=transform.encode_chunk, + ) + if encoded is None: + bs.delete_sync() + else: + bs.set_sync(encoded) + + if max_workers > 1 and len(batch) > 1: + pool = _get_pool(max_workers) + list(pool.map(_write_one, batch)) + else: + for item in batch: + _write_one(item) + + # -- async read/write -- + + async def read( + self, + batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> tuple[GetResult, ...]: + batch = list(batch_info) + if not batch: + return () + + # Fast path: sync transform plus synchronous IO. For StorePath the gate + # is the STORE's sync-IO capability (`_store_supports_sync_io`) (StorePath always has a + # get_sync method, but it only works when its store implements the full + # sync surface); for other byte getters (e.g. the sharding codec's + # in-memory _ShardingByteGetter) the SyncByteGetter protocol is the + # gate. + from zarr.abc.store import SyncByteGetter, _store_supports_sync_io + from zarr.storage._common import StorePath + + first_bg = batch[0][0] + if self.sync_transform is not None and ( + (isinstance(first_bg, StorePath) and _store_supports_sync_io(first_bg.store)) + or (not isinstance(first_bg, StorePath) and isinstance(first_bg, SyncByteGetter)) + ): + # One thread hop for the WHOLE batch — not per chunk, so the fused + # design's win over per-chunk async scheduling is preserved. Running + # read_sync inline here would block the event loop for the duration + # of the batch's IO+compute; every sync-API call from every user + # thread shares this one loop, so inline execution serializes + # concurrent callers behind each other's codec compute. + return await asyncio.to_thread( + self.read_sync, batch, out, drop_axes, max_workers=_resolve_max_workers() + ) + + # Non-sync store (e.g. ZipStore): can't use the sync fast path. But if the + # array-bytes codec supports partial decoding (sharding), still route + # through the async partial-decode path — it fetches only the needed + # inner-chunk byte ranges (coalesced via get_ranges), matching + # BatchedCodecPipeline. Without this, the whole-shard _async_read_fallback + # below would over-read and diverge from the batched pipeline's IO. + if self.supports_partial_decode: + assert isinstance(self.array_bytes_codec, ArrayBytesCodecPartialDecodeMixin) + chunk_array_batch = await self.array_bytes_codec.decode_partial( + [ + (byte_getter, chunk_selection, chunk_spec) + for byte_getter, chunk_spec, chunk_selection, *_ in batch + ] + ) + results: list[GetResult] = [] + for chunk_array, (_, chunk_spec, _, out_selection, _) in zip( + chunk_array_batch, batch, strict=False + ): + if chunk_array is not None: + if drop_axes: + chunk_array = chunk_array.squeeze(axis=drop_axes) + out[out_selection] = chunk_array + results.append(GetResult(status="present")) + else: + out[out_selection] = fill_value_or_default(chunk_spec) + results.append(GetResult(status="missing")) + return tuple(results) + + return await _async_read_fallback(self, batch, out, drop_axes) + + async def write( + self, + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> None: + batch = list(batch_info) + if not batch: + return + + # Fast path: sync transform plus synchronous IO. Mirrors `read`: gate + # StorePath on the store's sync-IO capability (`_store_supports_sync_io`) — write_sync + # needs the FULL sync surface (get_sync for partial-chunk + # read-modify-write, delete_sync for all-fill chunks), not just + # set_sync — and other byte setters (e.g. the sharding codec's + # in-memory _ShardingByteSetter) on SyncByteSetter. + from zarr.abc.store import SyncByteSetter, _store_supports_sync_io + from zarr.storage._common import StorePath + + first_bs = batch[0][0] + if self.sync_transform is not None and ( + (isinstance(first_bs, StorePath) and _store_supports_sync_io(first_bs.store)) + or (not isinstance(first_bs, StorePath) and isinstance(first_bs, SyncByteSetter)) + ): + # One thread hop for the whole batch; see the matching comment in + # `read` for why write_sync must not run inline on the event loop. + await asyncio.to_thread( + self.write_sync, batch, value, drop_axes, max_workers=_resolve_max_workers() + ) + return + + await _async_write_fallback(self, batch, value, drop_axes) + + +register_pipeline(FusedCodecPipeline) diff --git a/src/zarr/core/common.py b/src/zarr/core/common.py index 275d062eba..3da5c108b6 100644 --- a/src/zarr/core/common.py +++ b/src/zarr/core/common.py @@ -1,22 +1,17 @@ from __future__ import annotations import asyncio -import functools import math -import operator import warnings from collections.abc import Iterable, Mapping, Sequence from enum import Enum -from itertools import starmap from typing import ( TYPE_CHECKING, Any, Final, - Generic, Literal, NotRequired, TypedDict, - TypeVar, cast, overload, ) @@ -25,6 +20,7 @@ from typing_extensions import ReadOnly from zarr.core.config import config as zarr_config +from zarr.core.json_parse import convert, parse_field from zarr.errors import ZarrRuntimeWarning if TYPE_CHECKING: @@ -39,6 +35,7 @@ BytesLike = bytes | bytearray | memoryview ShapeLike = Iterable[int | np.integer[Any]] | int | np.integer[Any] +ChunksLike = ShapeLike | Iterable[Iterable[int]] # For backwards compatibility ChunkCoords = tuple[int, ...] ZarrFormat = Literal[2, 3] @@ -47,13 +44,11 @@ MemoryOrder = Literal["C", "F"] AccessModeLiteral = Literal["r", "r+", "a", "w", "w-"] ANY_ACCESS_MODE: Final = "r", "r+", "a", "w", "w-" -DimensionNames = Iterable[str | None] | None +DimensionNamesLike = Iterable[str | None] | None +DimensionNames = DimensionNamesLike # for backwards compatibility -TName = TypeVar("TName", bound=str) -TConfig = TypeVar("TConfig", bound=Mapping[str, object]) - -class NamedConfig(TypedDict, Generic[TName, TConfig]): +class NamedConfig[TName: str, TConfig: Mapping[str, object]](TypedDict): """ A typed dictionary representing an object with a name and configuration, where the configuration is an optional mapping of string keys to values, e.g. another typed dictionary or a JSON object. @@ -69,7 +64,7 @@ class NamedConfig(TypedDict, Generic[TName, TConfig]): """The configuration of the object. Not required.""" -class NamedRequiredConfig(TypedDict, Generic[TName, TConfig]): +class NamedRequiredConfig[TName: str, TConfig: Mapping[str, object]](TypedDict): """ A typed dictionary representing an object with a name and configuration, where the configuration is a mapping of string keys to values, e.g. another typed dictionary or a JSON object. @@ -86,7 +81,7 @@ class NamedRequiredConfig(TypedDict, Generic[TName, TConfig]): def product(tup: tuple[int, ...]) -> int: - return functools.reduce(operator.mul, tup, 1) + return math.prod(tup) def ceildiv(a: float, b: float) -> int: @@ -95,37 +90,54 @@ def ceildiv(a: float, b: float) -> int: return math.ceil(a / b) -T = TypeVar("T", bound=tuple[Any, ...]) -V = TypeVar("V") - - -async def concurrent_map( +def concurrent_iter[T: tuple[Any, ...], V]( items: Iterable[T], func: Callable[..., Awaitable[V]], limit: int | None = None, -) -> list[V]: +) -> list[asyncio.Task[V]]: + """Launch `func(*item)` for each item concurrently, returning the tasks. + + When `limit` is set, no more than `limit` calls are in flight at once. + Tasks are returned in input order; callers that want completion order + should wrap the result in `asyncio.as_completed`. + + Every task is scheduled (via `ensure_future`) before this function + returns, not on first iteration of the result. That matters for callers + that await the returned tasks one at a time — without eager scheduling, + each coroutine would only start when individually awaited, serializing + the work and defeating the semaphore. It also makes the return type + honest (real `Task`s support `.cancel()`, `.done()`, callbacks) rather + than bare coroutines. + + See https://docs.python.org/3/library/asyncio-task.html#coroutines: + "Note that simply calling a coroutine will not schedule it to be executed:" + """ if limit is None: - return await asyncio.gather(*list(starmap(func, items))) + return [asyncio.ensure_future(func(*item)) for item in items] - else: - sem = asyncio.Semaphore(limit) + sem = asyncio.Semaphore(limit) - async def run(item: tuple[Any]) -> V: - async with sem: - return await func(*item) + async def run(item: T) -> V: + async with sem: + return await func(*item) - return await asyncio.gather(*[asyncio.ensure_future(run(item)) for item in items]) + return [asyncio.ensure_future(run(item)) for item in items] -E = TypeVar("E", bound=Enum) +async def concurrent_map[T: tuple[Any, ...], V]( + items: Iterable[T], + func: Callable[..., Awaitable[V]], + limit: int | None = None, +) -> list[V]: + return await asyncio.gather(*concurrent_iter(items, func, limit)) -def enum_names(enum: type[E]) -> Iterator[str]: +def enum_names[E: Enum](enum: type[E]) -> Iterator[str]: for item in enum: yield item.name -def parse_enum(data: object, cls: type[E]) -> E: +def parse_enum[E: Enum](data: object, cls: type[E]) -> E: if isinstance(data, cls): return data if not isinstance(data, str): @@ -136,12 +148,13 @@ def parse_enum(data: object, cls: type[E]) -> E: def parse_name(data: JSON, expected: str | None = None) -> str: - if isinstance(data, str): - if expected is None or data == expected: - return data - raise ValueError(f"Expected '{expected}'. Got {data} instead.") - else: - raise TypeError(f"Expected a string, got an instance of {type(data)}.") + try: + data = cast("str", convert(data, str)) + except (ValueError, TypeError) as exc: + raise TypeError(f"Expected a string, got an instance of {type(data)}.") from exc + if expected is None or data == expected: + return data + raise ValueError(f"Expected '{expected}'. Got {data} instead.") def parse_configuration(data: JSON) -> JSON: @@ -216,15 +229,17 @@ def parse_fill_value(data: Any) -> Any: def parse_order(data: Any) -> Literal["C", "F"]: - if data in ("C", "F"): - return cast("Literal['C', 'F']", data) - raise ValueError(f"Expected one of ('C', 'F'), got {data} instead.") + return cast("Literal['C', 'F']", parse_field(data, Literal["C", "F"], "order")) def parse_bool(data: Any) -> bool: - if isinstance(data, bool): + return cast("bool", convert(data, bool)) + + +def parse_int(data: Any) -> int: + if isinstance(data, int) and not isinstance(data, bool): return data - raise ValueError(f"Expected bool, got {data} instead.") + raise ValueError(f"Expected int, got {data} instead.") def _warn_write_empty_chunks_kwarg() -> None: @@ -250,5 +265,91 @@ def _warn_order_kwarg() -> None: def _default_zarr_format() -> ZarrFormat: - """Return the default zarr_version""" + """Return the default zarr_format.""" return cast("ZarrFormat", int(zarr_config.get("default_zarr_format", 3))) + + +def expand_rle(data: Sequence[int | list[int]]) -> list[int]: + """Expand a mixed array of bare integers and RLE pairs. + + Per the rectilinear chunk grid spec, each element can be: + - a bare integer (an explicit edge length) + - a two-element array ``[value, count]`` (run-length encoded) + """ + result: list[int] = [] + for item in data: + if isinstance(item, (int, float)) and not isinstance(item, bool): + val = int(item) + if val < 1: + raise ValueError(f"Chunk edge length must be >= 1, got {val}") + result.append(val) + elif isinstance(item, list) and len(item) == 2: + size, count = int(item[0]), int(item[1]) + if size < 1: + raise ValueError(f"Chunk edge length must be >= 1, got {size}") + if count < 1: + raise ValueError(f"RLE repeat count must be >= 1, got {count}") + result.extend([size] * count) + else: + raise ValueError(f"RLE entries must be an integer or [size, count], got {item}") + return result + + +def compress_rle(sizes: Sequence[int]) -> list[int | list[int]]: + """Compress chunk sizes to mixed RLE format per the rectilinear spec. + + Runs of length > 1 are emitted as ``[value, count]`` pairs; runs of + length 1 are emitted as bare integers:: + + [10, 10, 10, 5] -> [[10, 3], 5] + """ + if not sizes: + return [] + result: list[int | list[int]] = [] + current = sizes[0] + count = 1 + for s in sizes[1:]: + if s == current: + count += 1 + else: + result.append([current, count] if count > 1 else current) + current = s + count = 1 + result.append([current, count] if count > 1 else current) + return result + + +def validate_rectilinear_kind(kind: str | None) -> None: + """Validate the ``kind`` field of a rectilinear chunk grid configuration. + + The rectilinear spec requires ``kind: "inline"``. + """ + if kind is None: + raise ValueError( + "Rectilinear chunk grid configuration requires a 'kind' field. " + "Only 'inline' is currently supported." + ) + if kind != "inline": + raise ValueError( + f"Unsupported rectilinear chunk grid kind: {kind!r}. " + "Only 'inline' is currently supported." + ) + + +def validate_rectilinear_edges( + chunk_shapes: Sequence[int | Sequence[int]], array_shape: Sequence[int] +) -> None: + """Validate that rectilinear chunk edges cover the array extent per dimension. + + Bare-int dimensions (regular step) always cover any extent, so they are + skipped. Explicit edge lists must sum to at least the array extent. + """ + for i, (dim_spec, extent) in enumerate(zip(chunk_shapes, array_shape, strict=True)): + if isinstance(dim_spec, int): + continue + edge_sum = sum(dim_spec) + if edge_sum < extent: + raise ValueError( + f"Rectilinear chunk edges for dimension {i} sum to {edge_sum} " + f"but array shape extent is {extent} (edge sum must be >= extent)" + ) diff --git a/src/zarr/core/config.py b/src/zarr/core/config.py index f8f8ea4f5f..c0ebb31353 100644 --- a/src/zarr/core/config.py +++ b/src/zarr/core/config.py @@ -33,6 +33,8 @@ from donfig import Config as DConfig +from zarr.core.json_parse import parse_field + if TYPE_CHECKING: from donfig.config_obj import ConfigSet @@ -96,14 +98,26 @@ def enable_gpu(self) -> ConfigSet: "array": { "order": "C", "write_empty_chunks": False, + "read_missing_chunks": True, "target_shard_size_bytes": None, + "rectilinear_chunks": False, + "sharding_coalesce_max_gap_bytes": 1 << 20, # 1 MiB + "sharding_coalesce_max_bytes": 16 << 20, # 16 MiB }, "async": {"concurrency": 10, "timeout": None}, "threading": {"max_workers": None}, "json_indent": 2, "codec_pipeline": { + # FusedCodecPipeline is the faster synchronous pipeline, but it stays + # opt-in for now so behavior is unchanged for existing users. Early + # adopters can switch with + # zarr.config.set( + # {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} + # ) "path": "zarr.core.codec_pipeline.BatchedCodecPipeline", "batch_size": 1, + # Only read by FusedCodecPipeline (BatchedCodecPipeline ignores it). + "max_workers": None, }, "codecs": { "blosc": "zarr.codecs.blosc.BloscCodec", @@ -147,7 +161,4 @@ def enable_gpu(self) -> ConfigSet: def parse_indexing_order(data: Any) -> Literal["C", "F"]: - if data in ("C", "F"): - return cast("Literal['C', 'F']", data) - msg = f"Expected one of ('C', 'F'), got {data} instead." - raise ValueError(msg) + return cast("Literal['C', 'F']", parse_field(data, Literal["C", "F"], "order")) diff --git a/src/zarr/core/dtype/__init__.py b/src/zarr/core/dtype/__init__.py index 1049a2063f..d1dbd6e2c8 100644 --- a/src/zarr/core/dtype/__init__.py +++ b/src/zarr/core/dtype/__init__.py @@ -1,12 +1,8 @@ from __future__ import annotations from collections.abc import Sequence -from typing import TYPE_CHECKING, Final, TypeAlias +from typing import TYPE_CHECKING, Final -from zarr.core.dtype.common import ( - DataTypeValidationError, - DTypeJSON, -) from zarr.core.dtype.npy.bool import Bool from zarr.core.dtype.npy.bytes import ( NullTerminatedBytes, @@ -21,7 +17,13 @@ from zarr.core.dtype.npy.complex import Complex64, Complex128 from zarr.core.dtype.npy.float import Float16, Float32, Float64 from zarr.core.dtype.npy.int import Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64 -from zarr.core.dtype.npy.structured import Structured, StructuredJSON_V2, StructuredJSON_V3 +from zarr.core.dtype.npy.structured import ( + Struct, + StructJSON_V3, + Structured, + StructuredJSON_V2, + StructuredJSON_V3, +) from zarr.core.dtype.npy.time import ( DateTime64, DateTime64JSON_V2, @@ -33,6 +35,7 @@ if TYPE_CHECKING: from zarr.core.common import ZarrFormat + from zarr.core.dtype.common import DTypeJSON from collections.abc import Mapping @@ -55,7 +58,6 @@ "Complex64", "Complex128", "DataTypeRegistry", - "DataTypeValidationError", "DateTime64", "DateTime64JSON_V2", "DateTime64JSON_V3", @@ -75,6 +77,8 @@ "RawBytes", "RawBytesJSON_V2", "RawBytesJSON_V3", + "Struct", + "StructJSON_V3", "Structured", "StructuredJSON_V2", "StructuredJSON_V3", @@ -124,7 +128,7 @@ | ComplexFloatDType | StringDType | BytesDType - | Structured + | Struct | TimeDType | VariableLengthBytes ) @@ -137,7 +141,7 @@ *COMPLEX_FLOAT_DTYPE, *STRING_DTYPE, *BYTES_DTYPE, - Structured, + Struct, *TIME_DTYPE, VariableLengthBytes, ) @@ -149,7 +153,7 @@ VLEN_UTF8_ALIAS: Final = ("str", str, "string") # This type models inputs that can be coerced to a ZDType -ZDTypeLike: TypeAlias = npt.DTypeLike | ZDType[TBaseDType, TBaseScalar] | Mapping[str, JSON] | str +type ZDTypeLike = npt.DTypeLike | ZDType[TBaseDType, TBaseScalar] | Mapping[str, JSON] | str for dtype in ANY_DTYPE: # mypy does not know that all the elements of ANY_DTYPE are subclasses of ZDType @@ -268,7 +272,7 @@ def parse_dtype( # First attempt to interpret the input as JSON if isinstance(dtype_spec, Mapping | str | Sequence): try: - return get_data_type_from_json(dtype_spec, zarr_format=zarr_format) # type: ignore[arg-type] + return get_data_type_from_json(dtype_spec, zarr_format=zarr_format) except ValueError: # no data type matched this JSON-like input pass @@ -279,3 +283,19 @@ def parse_dtype( # otherwise, we have either a numpy dtype string, or a zarr v3 dtype string, and in either case # we can create a native dtype from it, and do the dtype inference from that return get_data_type_from_native_dtype(dtype_spec) # type: ignore[arg-type] + + +def __getattr__(name: str) -> object: + if name == "DataTypeValidationError": + import warnings + + from zarr.errors import DataTypeValidationError, ZarrDeprecationWarning + + warnings.warn( + "Importing DataTypeValidationError from zarr.core.dtype is deprecated. " + "Use zarr.errors.DataTypeValidationError instead.", + ZarrDeprecationWarning, + stacklevel=2, + ) + return DataTypeValidationError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/zarr/core/dtype/common.py b/src/zarr/core/dtype/common.py index 6b70f595ba..61cbfe0360 100644 --- a/src/zarr/core/dtype/common.py +++ b/src/zarr/core/dtype/common.py @@ -6,11 +6,9 @@ from typing import ( ClassVar, Final, - Generic, Literal, TypedDict, TypeGuard, - TypeVar, ) from typing_extensions import ReadOnly @@ -53,13 +51,10 @@ # This models the type of the name a dtype might have in zarr v2 array metadata DTypeName_V2 = StructuredName_V2 | str -TDTypeNameV2_co = TypeVar("TDTypeNameV2_co", bound=DTypeName_V2, covariant=True) -TObjectCodecID_co = TypeVar("TObjectCodecID_co", bound=None | str, covariant=True) - -class DTypeConfig_V2(TypedDict, Generic[TDTypeNameV2_co, TObjectCodecID_co]): - name: ReadOnly[TDTypeNameV2_co] - object_codec_id: ReadOnly[TObjectCodecID_co] +class DTypeConfig_V2[TDTypeNameV2: DTypeName_V2, TObjectCodecID: str | None](TypedDict): + name: ReadOnly[TDTypeNameV2] + object_codec_id: ReadOnly[TObjectCodecID] DTypeSpec_V2 = DTypeConfig_V2[DTypeName_V2, None | str] @@ -151,7 +146,20 @@ def unpack_dtype_json(data: DTypeSpec_V2 | DTypeSpec_V3) -> DTypeJSON: return data -class DataTypeValidationError(ValueError): ... +def __getattr__(name: str) -> object: + if name == "DataTypeValidationError": + import warnings + + from zarr.errors import DataTypeValidationError, ZarrDeprecationWarning + + warnings.warn( + "Importing DataTypeValidationError from zarr.core.dtype.common is deprecated. " + "Use zarr.errors.DataTypeValidationError or zarr.dtype.DataTypeValidationError instead.", + ZarrDeprecationWarning, + stacklevel=2, + ) + return DataTypeValidationError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") class ScalarTypeValidationError(ValueError): ... diff --git a/src/zarr/core/dtype/npy/bool.py b/src/zarr/core/dtype/npy/bool.py index 3e7f5b72f0..f92476a455 100644 --- a/src/zarr/core/dtype/npy/bool.py +++ b/src/zarr/core/dtype/npy/bool.py @@ -6,13 +6,13 @@ import numpy as np from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasItemSize, check_dtype_spec_v2, ) from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from zarr.core.common import JSON, ZarrFormat diff --git a/src/zarr/core/dtype/npy/bytes.py b/src/zarr/core/dtype/npy/bytes.py index 2cf5985d69..e60f3c6c48 100644 --- a/src/zarr/core/dtype/npy/bytes.py +++ b/src/zarr/core/dtype/npy/bytes.py @@ -9,7 +9,6 @@ from zarr.core.common import JSON, NamedConfig, ZarrFormat from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasItemSize, @@ -20,6 +19,7 @@ ) from zarr.core.dtype.npy.common import check_json_str from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError BytesLike = np.bytes_ | str | bytes | int @@ -1069,7 +1069,7 @@ def _from_json_v2(cls, data: DTypeJSON) -> Self: Raises ------ DataTypeValidationError - If the input data is not a valid representation of this class class. + If the input data is not a valid representation of this class. """ if cls._check_json_v2(data): diff --git a/src/zarr/core/dtype/npy/common.py b/src/zarr/core/dtype/npy/common.py index 107b3bd12d..f413f5f678 100644 --- a/src/zarr/core/dtype/npy/common.py +++ b/src/zarr/core/dtype/npy/common.py @@ -15,7 +15,6 @@ SupportsIndex, SupportsInt, TypeGuard, - TypeVar, ) import numpy as np @@ -67,20 +66,6 @@ NumpyEndiannessStr = Literal[">", "<", "="] NUMPY_ENDIANNESS_STR: Final = ">", "<", "=" -TFloatDType_co = TypeVar( - "TFloatDType_co", - bound=np.dtypes.Float16DType | np.dtypes.Float32DType | np.dtypes.Float64DType, - covariant=True, -) -TFloatScalar_co = TypeVar( - "TFloatScalar_co", bound=np.float16 | np.float32 | np.float64, covariant=True -) - -TComplexDType_co = TypeVar( - "TComplexDType_co", bound=np.dtypes.Complex64DType | np.dtypes.Complex128DType, covariant=True -) -TComplexScalar_co = TypeVar("TComplexScalar_co", bound=np.complex64 | np.complex128, covariant=True) - def endianness_from_numpy_str(endianness: NumpyEndiannessStr) -> EndiannessStr: """ diff --git a/src/zarr/core/dtype/npy/complex.py b/src/zarr/core/dtype/npy/complex.py index 99abee5e24..0286d42380 100644 --- a/src/zarr/core/dtype/npy/complex.py +++ b/src/zarr/core/dtype/npy/complex.py @@ -13,7 +13,6 @@ import numpy as np from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasEndianness, @@ -22,8 +21,6 @@ ) from zarr.core.dtype.npy.common import ( ComplexLike, - TComplexDType_co, - TComplexScalar_co, check_json_complex_float_v2, check_json_complex_float_v3, complex_float_from_json_v2, @@ -34,13 +31,17 @@ get_endianness_from_numpy_dtype, ) from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from zarr.core.common import JSON, ZarrFormat @dataclass(frozen=True) -class BaseComplex(ZDType[TComplexDType_co, TComplexScalar_co], HasEndianness, HasItemSize): +class BaseComplex[ + DType: np.dtypes.Complex64DType | np.dtypes.Complex128DType, + Scalar: np.complex64 | np.complex128, +](ZDType[DType, Scalar], HasEndianness, HasItemSize): """ A base class for Zarr data types that wrap NumPy complex float data types. """ @@ -74,18 +75,18 @@ def from_native_dtype(cls, dtype: TBaseDType) -> Self: f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" ) - def to_native_dtype(self) -> TComplexDType_co: + def to_native_dtype(self) -> DType: """ Convert this class to a NumPy complex dtype with the appropriate byte order. Returns ------- - TComplexDType_co + DType A NumPy data type object representing the complex data type with the specified byte order. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[no-any-return,call-overload] @classmethod def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[DTypeConfig_V2[str, None]]: @@ -235,7 +236,7 @@ def _check_scalar(self, data: object) -> TypeGuard[ComplexLike]: """ return isinstance(data, ComplexLike) - def _cast_scalar_unchecked(self, data: ComplexLike) -> TComplexScalar_co: + def _cast_scalar_unchecked(self, data: ComplexLike) -> Scalar: """ Cast the provided scalar data to the native scalar type of this class. @@ -246,7 +247,7 @@ def _cast_scalar_unchecked(self, data: ComplexLike) -> TComplexScalar_co: Returns ------- - TComplexScalar_co + Scalar The casted data as a numpy complex scalar. Notes @@ -256,7 +257,7 @@ def _cast_scalar_unchecked(self, data: ComplexLike) -> TComplexScalar_co: """ return self.to_native_dtype().type(data) # type: ignore[return-value] - def cast_scalar(self, data: object) -> TComplexScalar_co: + def cast_scalar(self, data: object) -> Scalar: """ Attempt to cast a given object to a numpy complex scalar. @@ -267,7 +268,7 @@ def cast_scalar(self, data: object) -> TComplexScalar_co: Returns ------- - TComplexScalar_co + Scalar The data cast as a numpy complex scalar. Raises @@ -283,7 +284,7 @@ def cast_scalar(self, data: object) -> TComplexScalar_co: ) raise TypeError(msg) - def default_scalar(self) -> TComplexScalar_co: + def default_scalar(self) -> Scalar: """ Get the default value, which is 0 cast to this dtype @@ -294,7 +295,7 @@ def default_scalar(self) -> TComplexScalar_co: """ return self._cast_scalar_unchecked(0) - def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TComplexScalar_co: + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: """ Read a JSON-serializable value as a numpy float. @@ -307,7 +308,7 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TComplexSc Returns ------- - TScalar_co + Scalar The numpy float. """ if zarr_format == 2: diff --git a/src/zarr/core/dtype/npy/float.py b/src/zarr/core/dtype/npy/float.py index 2a23cb429d..d041416b81 100644 --- a/src/zarr/core/dtype/npy/float.py +++ b/src/zarr/core/dtype/npy/float.py @@ -6,7 +6,6 @@ import numpy as np from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasEndianness, @@ -15,8 +14,6 @@ ) from zarr.core.dtype.npy.common import ( FloatLike, - TFloatDType_co, - TFloatScalar_co, check_json_float_v2, check_json_float_v3, check_json_floatish_str, @@ -28,13 +25,17 @@ get_endianness_from_numpy_dtype, ) from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from zarr.core.common import JSON, ZarrFormat @dataclass(frozen=True) -class BaseFloat(ZDType[TFloatDType_co, TFloatScalar_co], HasEndianness, HasItemSize): +class BaseFloat[ + DType: np.dtypes.Float16DType | np.dtypes.Float32DType | np.dtypes.Float64DType, + Scalar: np.float16 | np.float32 | np.float64, +](ZDType[DType, Scalar], HasEndianness, HasItemSize): """ A base class for Zarr data types that wrap NumPy float data types. """ @@ -63,17 +64,17 @@ def from_native_dtype(cls, dtype: TBaseDType) -> Self: f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" ) - def to_native_dtype(self) -> TFloatDType_co: + def to_native_dtype(self) -> DType: """ Convert the wrapped data type to a NumPy data type. Returns ------- - TFloatDType_co + DType The NumPy data type. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[no-any-return,call-overload] @classmethod def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[DTypeConfig_V2[str, None]]: @@ -213,7 +214,7 @@ def _check_scalar(self, data: object) -> TypeGuard[FloatLike]: return True return isinstance(data, FloatLike) - def _cast_scalar_unchecked(self, data: FloatLike) -> TFloatScalar_co: + def _cast_scalar_unchecked(self, data: FloatLike) -> Scalar: """ Cast a scalar value to a NumPy float scalar. @@ -224,12 +225,12 @@ def _cast_scalar_unchecked(self, data: FloatLike) -> TFloatScalar_co: Returns ------- - TFloatScalar_co + Scalar The NumPy float scalar. """ return self.to_native_dtype().type(data) # type: ignore[return-value] - def cast_scalar(self, data: object) -> TFloatScalar_co: + def cast_scalar(self, data: object) -> Scalar: """ Cast a scalar value to a NumPy float scalar. @@ -240,7 +241,7 @@ def cast_scalar(self, data: object) -> TFloatScalar_co: Returns ------- - TFloatScalar_co + Scalar The NumPy float scalar. """ if self._check_scalar(data): @@ -251,18 +252,18 @@ def cast_scalar(self, data: object) -> TFloatScalar_co: ) raise TypeError(msg) - def default_scalar(self) -> TFloatScalar_co: + def default_scalar(self) -> Scalar: """ Get the default value, which is 0 cast to this zdtype. Returns ------- - TFloatScalar_co + Scalar The default value. """ return self._cast_scalar_unchecked(0) - def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TFloatScalar_co: + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: """ Read a JSON-serializable value as a NumPy float scalar. @@ -275,7 +276,7 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TFloatScal Returns ------- - TFloatScalar_co + Scalar The NumPy float scalar. """ if zarr_format == 2: diff --git a/src/zarr/core/dtype/npy/int.py b/src/zarr/core/dtype/npy/int.py index f71f535abb..c18fd01dd8 100644 --- a/src/zarr/core/dtype/npy/int.py +++ b/src/zarr/core/dtype/npy/int.py @@ -9,14 +9,12 @@ SupportsIndex, SupportsInt, TypeGuard, - TypeVar, overload, ) import numpy as np from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasEndianness, @@ -31,6 +29,7 @@ get_endianness_from_numpy_dtype, ) from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from zarr.core.common import JSON, ZarrFormat @@ -48,13 +47,15 @@ _NumpyIntScalar = ( np.int8 | np.int16 | np.int32 | np.int64 | np.uint8 | np.uint16 | np.uint32 | np.uint64 ) -TIntDType_co = TypeVar("TIntDType_co", bound=_NumpyIntDType, covariant=True) -TIntScalar_co = TypeVar("TIntScalar_co", bound=_NumpyIntScalar, covariant=True) + IntLike = SupportsInt | SupportsIndex | bytes | str @dataclass(frozen=True) -class BaseInt(ZDType[TIntDType_co, TIntScalar_co], HasItemSize): +class BaseInt[ + DType: _NumpyIntDType, + Scalar: np.int8 | np.int16 | np.int32 | np.int64 | np.uint8 | np.uint16 | np.uint32 | np.uint64, +](ZDType[DType, Scalar], HasItemSize): """ A base class for integer data types in Zarr. @@ -129,7 +130,7 @@ def _check_scalar(self, data: object) -> TypeGuard[IntLike]: return isinstance(data, IntLike) - def _cast_scalar_unchecked(self, data: IntLike) -> TIntScalar_co: + def _cast_scalar_unchecked(self, data: IntLike) -> Scalar: """ Casts a given scalar value to the native integer scalar type without type checking. @@ -140,13 +141,13 @@ def _cast_scalar_unchecked(self, data: IntLike) -> TIntScalar_co: Returns ------- - TIntScalar_co + Scalar The casted integer scalar of the native dtype. """ return self.to_native_dtype().type(data) # type: ignore[return-value] - def cast_scalar(self, data: object) -> TIntScalar_co: + def cast_scalar(self, data: object) -> Scalar: """ Attempt to cast a given object to a NumPy integer scalar. @@ -157,7 +158,7 @@ def cast_scalar(self, data: object) -> TIntScalar_co: Returns ------- - TIntScalar_co + Scalar The data cast as a NumPy integer scalar. Raises @@ -174,18 +175,18 @@ def cast_scalar(self, data: object) -> TIntScalar_co: ) raise TypeError(msg) - def default_scalar(self) -> TIntScalar_co: + def default_scalar(self) -> Scalar: """ Get the default value, which is 0 cast to this dtype. Returns ------- - TIntScalar_co + Scalar The default value. """ return self._cast_scalar_unchecked(0) - def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TIntScalar_co: + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: """ Read a JSON-serializable value as a NumPy int scalar. @@ -198,7 +199,7 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TIntScalar Returns ------- - TIntScalar_co + Scalar The NumPy int scalar. Raises @@ -599,7 +600,8 @@ def to_native_dtype(self) -> np.dtypes.Int16DType: The np.dtype('int16') instance. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] @classmethod def _from_json_v2(cls, data: DTypeJSON) -> Self: @@ -761,7 +763,8 @@ def to_native_dtype(self) -> np.dtypes.UInt16DType: The np.dtype('uint16') instance. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] @classmethod def _from_json_v2(cls, data: DTypeJSON) -> Self: @@ -944,7 +947,8 @@ def to_native_dtype(self: Self) -> np.dtypes.Int32DType: The np.dtype('int32') instance. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] @classmethod def _from_json_v2(cls, data: DTypeJSON) -> Self: @@ -1070,6 +1074,28 @@ class UInt32(BaseInt[np.dtypes.UInt32DType, np.uint32], HasEndianness): _zarr_v3_name: ClassVar[Literal["uint32"]] = "uint32" _zarr_v2_names: ClassVar[tuple[Literal[">u4"], Literal["u4", " TypeGuard[np.dtypes.UInt32DType]: + """ + A type guard that checks if the input is assignable to the type of ``cls.dtype_class`` + + This method is overridden for this particular data type because of a Windows-specific issue + where ``np.array([1], dtype=np.uint32) & 1`` creates an instance of ``np.dtypes.UIntDType``, + rather than an instance of ``np.dtypes.UInt32DType``, even though both represent 32-bit + unsigned integers. (In contrast to ``np.dtype('i')``, ``np.dtype('u')`` raises an error.) + + Parameters + ---------- + dtype : TDType + The dtype to check. + + Returns + ------- + Bool + True if the dtype matches, False otherwise. + """ + return super()._check_native_dtype(dtype) or dtype == np.dtypes.UInt32DType() + @classmethod def from_native_dtype(cls, dtype: TBaseDType) -> Self: """ @@ -1107,7 +1133,8 @@ def to_native_dtype(self) -> np.dtypes.UInt32DType: The NumPy unsigned 32-bit integer dtype. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] @classmethod def _from_json_v2(cls, data: DTypeJSON) -> Self: @@ -1265,7 +1292,8 @@ def to_native_dtype(self) -> np.dtypes.Int64DType: The NumPy signed 64-bit integer dtype. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] @classmethod def _from_json_v2(cls, data: DTypeJSON) -> Self: @@ -1396,7 +1424,8 @@ def to_native_dtype(self) -> np.dtypes.UInt64DType: The native NumPy dtype.eeeeeeeeeeeeeeeee """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls().newbyteorder(byte_order) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] @classmethod def _from_json_v2(cls, data: DTypeJSON) -> Self: diff --git a/src/zarr/core/dtype/npy/string.py b/src/zarr/core/dtype/npy/string.py index 904280a330..3f84e8123f 100644 --- a/src/zarr/core/dtype/npy/string.py +++ b/src/zarr/core/dtype/npy/string.py @@ -18,7 +18,6 @@ from zarr.core.common import NamedConfig from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasEndianness, @@ -26,21 +25,19 @@ HasLength, HasObjectCodec, check_dtype_spec_v2, - v3_unstable_dtype_warning, ) from zarr.core.dtype.npy.common import ( check_json_str, endianness_to_numpy_str, get_endianness_from_numpy_dtype, ) -from zarr.core.dtype.wrapper import TDType_co, ZDType +from zarr.core.dtype.wrapper import ZDType +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from zarr.core.common import JSON, ZarrFormat from zarr.core.dtype.wrapper import TBaseDType -_NUMPY_SUPPORTS_VLEN_STRING = hasattr(np.dtypes, "StringDType") - @runtime_checkable class SupportsStr(Protocol): @@ -115,6 +112,9 @@ class FixedLengthUTF32( Wraps the ``np.dtypes.StrDType`` data type. Scalars for this data type are instances of ``np.str_``. + The Zarr V3 specification for this data type is defined at + https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/fixed_length_utf32. + Attributes ---------- dtype_cls : Type[np.dtypes.StrDType] @@ -172,7 +172,8 @@ def to_native_dtype(self) -> np.dtypes.StrDType[int]: The NumPy data type. """ byte_order = endianness_to_numpy_str(self.endianness) - return self.dtype_cls(self.length).newbyteorder(byte_order) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls(self.length).newbyteorder(byte_order) # type: ignore[return-value] @classmethod def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[FixedLengthUTF32JSON_V2]: @@ -246,7 +247,6 @@ def to_json( if zarr_format == 2: return {"name": self.to_native_dtype().str, "object_codec_id": None} elif zarr_format == 3: - v3_unstable_dtype_warning(self) return { "name": self._zarr_v3_name, "configuration": {"length_bytes": self.length * self.code_point_bytes}, @@ -449,28 +449,31 @@ class VariableLengthUTF8JSON_V2(DTypeConfig_V2[Literal["|O"], Literal["vlen-utf8 """ -# VariableLengthUTF8 is defined in two places, conditioned on the version of NumPy. -# If NumPy 2 is installed, then VariableLengthUTF8 is defined with the NumPy variable length -# string dtype as the native dtype. Otherwise, VariableLengthUTF8 is defined with the NumPy object -# dtype as the native dtype. -class UTF8Base(ZDType[TDType_co, str], HasObjectCodec): +@dataclass(frozen=True, kw_only=True) +class VariableLengthUTF8(ZDType[np.dtypes.StringDType, str], HasObjectCodec): # type: ignore[type-var] """ - A base class for variable-length UTF-8 string data types. + A Zarr data type for arrays containing variable-length UTF-8 strings. + + Wraps the ``np.dtypes.StringDType`` data type. Scalars for this data type are instances + of ``str``. - Not intended for direct use, but as a base for concrete implementations. Attributes ---------- - object_codec_id : ClassVar[Literal["vlen-utf8"]] + dtype_cls : Type[np.dtypes.StringDType] + The NumPy dtype class for this data type. + _zarr_v3_name : ClassVar[Literal["variable_length_utf8"]] = "variable_length_utf8" + The name of this data type in Zarr V3. + object_codec_id : ClassVar[Literal["vlen-utf8"]] = "vlen-utf8" The object codec ID for this data type. References ---------- - This data type does not have a Zarr V3 specification. + https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/string - The Zarr V2 data type specification can be found [here](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). """ + dtype_cls = np.dtypes.StringDType # type: ignore[assignment] _zarr_v3_name: ClassVar[Literal["string"]] = "string" object_codec_id: ClassVar[Literal["vlen-utf8"]] = "vlen-utf8" @@ -478,7 +481,8 @@ class UTF8Base(ZDType[TDType_co, str], HasObjectCodec): def from_native_dtype(cls, dtype: TBaseDType) -> Self: """ Create an instance of this data type from a compatible NumPy data type. - + We reject NumPy StringDType instances that have the `na_object` field set, + because this is not representable by the Zarr `string` data type. Parameters ---------- @@ -494,13 +498,33 @@ def from_native_dtype(cls, dtype: TBaseDType) -> Self: ------ DataTypeValidationError If the input is not compatible with this data type. + ValueError + If the input is `numpy.dtypes.StringDType` and has `na_object` set. """ if cls._check_native_dtype(dtype): + if hasattr(dtype, "na_object"): + msg = ( + f"Zarr data type resolution from {dtype} failed. " + "Attempted to resolve a zarr data type from a `numpy.dtypes.StringDType` " + "with `na_object` set, which is not supported." + ) + raise ValueError(msg) return cls() raise DataTypeValidationError( f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" ) + def to_native_dtype(self) -> np.dtypes.StringDType: + """ + Create a NumPy string dtype from this VariableLengthUTF8 ZDType. + + Returns + ------- + np.dtypes.StringDType + The NumPy string dtype. + """ + return self.dtype_cls() + @classmethod def _check_json_v2( cls, @@ -717,109 +741,3 @@ def cast_scalar(self, data: object) -> str: f"data type {self}." ) raise TypeError(msg) # pragma: no cover - - -if _NUMPY_SUPPORTS_VLEN_STRING: - - @dataclass(frozen=True, kw_only=True) - class VariableLengthUTF8(UTF8Base[np.dtypes.StringDType]): # type: ignore[type-var] - """ - A Zarr data type for arrays containing variable-length UTF-8 strings. - - Wraps the ``np.dtypes.StringDType`` data type. Scalars for this data type are instances - of ``str``. - - - Attributes - ---------- - dtype_cls : Type[np.dtypes.StringDType] - The NumPy dtype class for this data type. - _zarr_v3_name : ClassVar[Literal["variable_length_utf8"]] = "variable_length_utf8" - The name of this data type in Zarr V3. - object_codec_id : ClassVar[Literal["vlen-utf8"]] = "vlen-utf8" - The object codec ID for this data type. - """ - - dtype_cls = np.dtypes.StringDType - - @classmethod - def from_native_dtype(cls, dtype: TBaseDType) -> Self: - """ - Create an instance of this data type from a compatible NumPy data type. - We reject NumPy StringDType instances that have the `na_object` field set, - because this is not representable by the Zarr `string` data type. - - Parameters - ---------- - dtype : TBaseDType - The native data type. - - Returns - ------- - Self - An instance of this data type. - - Raises - ------ - DataTypeValidationError - If the input is not compatible with this data type. - ValueError - If the input is `numpy.dtypes.StringDType` and has `na_object` set. - """ - if cls._check_native_dtype(dtype): - if hasattr(dtype, "na_object"): - msg = ( - f"Zarr data type resolution from {dtype} failed. " - "Attempted to resolve a zarr data type from a `numpy.dtypes.StringDType` " - "with `na_object` set, which is not supported." - ) - raise ValueError(msg) - return cls() - raise DataTypeValidationError( - f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" - ) - - def to_native_dtype(self) -> np.dtypes.StringDType: - """ - Create a NumPy string dtype from this VariableLengthUTF8 ZDType. - - Returns - ------- - np.dtypes.StringDType - The NumPy string dtype. - """ - return self.dtype_cls() - -else: - # Numpy pre-2 does not have a variable length string dtype, so we use the Object dtype instead. - @dataclass(frozen=True, kw_only=True) - class VariableLengthUTF8(UTF8Base[np.dtypes.ObjectDType]): # type: ignore[no-redef] - """ - A Zarr data type for arrays containing variable-length UTF-8 strings. - - Wraps the ``np.dtypes.ObjectDType`` data type. Scalars for this data type are instances - of ``str``. - - - Attributes - ---------- - dtype_cls : Type[np.dtypes.ObjectDType] - The NumPy dtype class for this data type. - _zarr_v3_name : ClassVar[Literal["variable_length_utf8"]] = "variable_length_utf8" - The name of this data type in Zarr V3. - object_codec_id : ClassVar[Literal["vlen-utf8"]] = "vlen-utf8" - The object codec ID for this data type. - """ - - dtype_cls = np.dtypes.ObjectDType - - def to_native_dtype(self) -> np.dtypes.ObjectDType: - """ - Create a NumPy object dtype from this VariableLengthUTF8 ZDType. - - Returns - ------- - np.dtypes.ObjectDType - The NumPy object dtype. - """ - return self.dtype_cls() diff --git a/src/zarr/core/dtype/npy/structured.py b/src/zarr/core/dtype/npy/structured.py index 8bedee07ef..dcc523d1d2 100644 --- a/src/zarr/core/dtype/npy/structured.py +++ b/src/zarr/core/dtype/npy/structured.py @@ -8,7 +8,6 @@ from zarr.core.common import NamedConfig from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasItemSize, @@ -23,6 +22,7 @@ check_json_str, ) from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from zarr.core.common import JSON, ZarrFormat @@ -61,11 +61,10 @@ class StructuredJSON_V3( NamedConfig[Literal["structured"], dict[str, Sequence[Sequence[str | DTypeJSON]]]] ): """ - A JSON representation of a structured data type in Zarr V3. + A JSON representation of a structured data type in Zarr V3 (legacy format). - References - ---------- - This representation is not currently defined in an external specification. + This is the legacy format using tuple-style field definitions. + For the canonical format, see ``StructJSON_V3``. Examples -------- @@ -83,14 +82,44 @@ class StructuredJSON_V3( """ +class StructJSON_V3( + NamedConfig[Literal["struct"], dict[str, Sequence[dict[str, str | DTypeJSON]]]] +): + """ + A JSON representation of a structured data type in Zarr V3 (canonical format). + + References + ---------- + The Zarr V3 specification for this data type is defined in the zarr-extensions repository: + https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/struct + + Examples + -------- + ```python + { + "name": "struct", + "configuration": { + "fields": [ + {"name": "f0", "data_type": "int32"}, + {"name": "f1", "data_type": "float64"}, + ] + } + } + ``` + """ + + @dataclass(frozen=True, kw_only=True) class Structured(ZDType[np.dtypes.VoidDType[int], np.void], HasItemSize): """ - A Zarr data type for arrays containing structured scalars, AKA "record arrays". + A Zarr data type for arrays containing structured scalars, AKA "record arrays" (legacy format). Wraps the NumPy `np.dtypes.VoidDType` if the data type has fields. Scalars for this data type are instances of `np.void`, with a ``fields`` attribute. + This class handles the legacy "structured" format with tuple-style field definitions. + For the canonical "struct" format, see ``Struct``. + Attributes ---------- fields : Sequence[tuple[str, ZDType]] @@ -98,8 +127,6 @@ class Structured(ZDType[np.dtypes.VoidDType[int], np.void], HasItemSize): References ---------- - This data type does not have a Zarr V3 specification. - The Zarr V2 data type specification can be found [here](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). """ @@ -234,7 +261,6 @@ def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[StructuredJSON_V3]: True if the input is a valid JSON representation of a structured data type for Zarr V3, False otherwise. """ - return ( isinstance(data, dict) and set(data.keys()) == {"name", "configuration"} @@ -252,15 +278,16 @@ def _from_json_v2(cls, data: DTypeJSON) -> Self: # structured dtypes are constructed directly from a list of lists # note that we do not handle the object codec here! this will prevent structured # dtypes from containing object dtypes. + name = data["name"] return cls( - fields=tuple( # type: ignore[misc] + fields=tuple( # type: ignore[str-unpack] ( # type: ignore[misc] f_name, get_data_type_from_json( {"name": f_dtype, "object_codec_id": None}, zarr_format=2 ), ) - for f_name, f_dtype in data["name"] + for f_name, f_dtype in name ) ) msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a JSON array of arrays" @@ -268,7 +295,6 @@ def _from_json_v2(cls, data: DTypeJSON) -> Self: @classmethod def _from_json_v3(cls, data: DTypeJSON) -> Self: - # avoid circular import from zarr.core.dtype import get_data_type_from_json if cls._check_json_v3(data): @@ -445,7 +471,7 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.void: return cast("np.void", np.array([as_bytes]).view(dtype)[0]) raise TypeError(f"Invalid type: {data}. Expected a string.") - def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str: + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str | dict[str, JSON]: """ Convert a scalar to a JSON-serializable string representation. @@ -458,9 +484,10 @@ def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str: Returns ------- - str + str | dict[str, JSON] A string representation of the scalar, which is a base64-encoded - string of the bytes that make up the scalar. + string of the bytes that make up the scalar. Subclasses may return + a dict for V3 format. """ return bytes_to_json(self.cast_scalar(data).tobytes(), zarr_format) @@ -475,3 +502,168 @@ def item_size(self) -> int: The size of a single scalar in bytes. """ return self.to_native_dtype().itemsize + + def has_multi_byte_fields(self) -> bool: + """ + Check if this structured dtype has any fields with item_size > 1. + + Returns + ------- + bool + True if any field has item_size > 1, False otherwise. + """ + return any( + isinstance(field_dtype, HasItemSize) and field_dtype.item_size > 1 + for _, field_dtype in self.fields + ) + + +@dataclass(frozen=True, kw_only=True) +class Struct(Structured): + """ + A Zarr data type for arrays containing structured scalars, AKA "record arrays". + + Wraps the NumPy `np.dtypes.VoidDType` if the data type has fields. Scalars for this data + type are instances of `np.void`, with a ``fields`` attribute. + + This is the canonical data type registered for structured arrays. It reads both + the canonical ``"struct"`` format (object-style fields) and the legacy ``"structured"`` + format (tuple-style fields), but always writes the canonical ``"struct"`` format. + + Attributes + ---------- + fields : Sequence[tuple[str, ZDType]] + The fields of the structured dtype. + + References + ---------- + The Zarr V3 specification for this data type is defined in the zarr-extensions repository: + https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/struct + + The Zarr V2 data type specification can be found [here](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + """ + + _zarr_v3_name: ClassVar[Literal["struct"]] = "struct" # type: ignore[assignment] + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[StructJSON_V3]: # type: ignore[override] + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] in ("struct", "structured") + and isinstance(data["configuration"], dict) + and set(data["configuration"].keys()) == {"fields"} + ) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + from zarr.core.dtype import get_data_type_from_json + + if cls._check_json_v3(data): + config = data["configuration"] + meta_fields = config["fields"] + parsed_fields: list[tuple[str, ZDType[TBaseDType, TBaseScalar]]] = [] + for field in meta_fields: + if isinstance(field, dict): + f_name = field["name"] + f_dtype = field["data_type"] + else: + # Legacy tuple-style field format from "structured" dtype + f_name, f_dtype = field # type: ignore[unreachable] + parsed_fields.append((f_name, get_data_type_from_json(f_dtype, zarr_format=3))) # type: ignore[arg-type] + return cls(fields=tuple(parsed_fields)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a JSON object with the key {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload # type: ignore[override] + def to_json(self, zarr_format: Literal[2]) -> StructuredJSON_V2: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> StructJSON_V3: ... + + def to_json(self, zarr_format: ZarrFormat) -> StructuredJSON_V2 | StructJSON_V3: + if zarr_format == 2: + fields_v2 = [ + [f_name, f_dtype.to_json(zarr_format=zarr_format)["name"]] + for f_name, f_dtype in self.fields + ] + return {"name": fields_v2, "object_codec_id": None} + elif zarr_format == 3: + # The "struct" data type has a stable Zarr V3 specification + # (https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/struct), + # so unlike the legacy "structured" alias it does not emit an unstable-spec warning. + fields_v3 = [ + {"name": f_name, "data_type": f_dtype.to_json(zarr_format=zarr_format)} + for f_name, f_dtype in self.fields + ] + return cast( + "StructJSON_V3", + {"name": self._zarr_v3_name, "configuration": {"fields": fields_v3}}, + ) + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.void: + """ + Read a JSON-serializable value as a NumPy structured scalar. + + Parameters + ---------- + data : JSON + The JSON-serializable value. Can be either: + - A dict mapping field names to values (primary format for V3) + - A base64-encoded string (legacy format, for backward compatibility) + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + np.void + The NumPy structured scalar. + + Raises + ------ + TypeError + If the input is not a dict or base64-encoded string. + """ + if isinstance(data, dict): + field_values = [] + for field_name, field_dtype in self.fields: + if field_name in data: + field_values.append( + field_dtype.from_json_scalar(data[field_name], zarr_format=zarr_format) + ) + else: + field_values.append(field_dtype.default_scalar()) + return self._cast_scalar_unchecked(tuple(field_values)) + elif check_json_str(data): + as_bytes = bytes_from_json(data, zarr_format=zarr_format) + dtype = self.to_native_dtype() + return cast("np.void", np.array([as_bytes]).view(dtype)[0]) + raise TypeError(f"Invalid type: {data}. Expected a dict or base64-encoded string.") + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str | dict[str, JSON]: + """ + Convert a scalar to a JSON-serializable representation. + + Parameters + ---------- + data : object + The scalar to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + str | dict[str, JSON] + For V2: A base64-encoded string of the bytes that make up the scalar. + For V3: A dict mapping field names to their JSON-serialized values. + """ + scalar = self.cast_scalar(data) + if zarr_format == 2: + return bytes_to_json(scalar.tobytes(), zarr_format) + result: dict[str, JSON] = {} + for field_name, field_dtype in self.fields: + result[field_name] = field_dtype.to_json_scalar( + scalar[field_name], zarr_format=zarr_format + ) + return result diff --git a/src/zarr/core/dtype/npy/time.py b/src/zarr/core/dtype/npy/time.py index 402a140321..4efa0be7bb 100644 --- a/src/zarr/core/dtype/npy/time.py +++ b/src/zarr/core/dtype/npy/time.py @@ -9,7 +9,6 @@ Self, TypedDict, TypeGuard, - TypeVar, cast, get_args, overload, @@ -18,9 +17,8 @@ import numpy as np from typing_extensions import ReadOnly -from zarr.core.common import NamedConfig +from zarr.core.common import NamedRequiredConfig from zarr.core.dtype.common import ( - DataTypeValidationError, DTypeConfig_V2, DTypeJSON, HasEndianness, @@ -35,6 +33,7 @@ get_endianness_from_numpy_dtype, ) from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from zarr.core.common import JSON, ZarrFormat @@ -90,16 +89,6 @@ def check_json_time(data: JSON) -> TypeGuard[Literal["NaT"] | int]: return check_json_int(data) or data == "NaT" -BaseTimeDType_co = TypeVar( - "BaseTimeDType_co", - bound=np.dtypes.TimeDelta64DType | np.dtypes.DateTime64DType, - covariant=True, -) -BaseTimeScalar_co = TypeVar( - "BaseTimeScalar_co", bound=np.timedelta64 | np.datetime64, covariant=True -) - - class TimeConfig(TypedDict): """ The configuration for the numpy.timedelta64 or numpy.datetime64 data type in Zarr V3. @@ -122,14 +111,14 @@ class TimeConfig(TypedDict): scale_factor: ReadOnly[int] -class DateTime64JSON_V3(NamedConfig[Literal["numpy.datetime64"], TimeConfig]): +class DateTime64JSON_V3(NamedRequiredConfig[Literal["numpy.datetime64"], TimeConfig]): """ The JSON representation of the ``numpy.datetime64`` data type in Zarr V3. References ---------- This representation is defined in the ``numpy.datetime64`` - [specification document](https://zarr-specs.readthedocs.io/en/latest/spec/v3/datatypes.html#numpy-datetime64). + [specification document](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.datetime64). Examples -------- @@ -139,20 +128,20 @@ class DateTime64JSON_V3(NamedConfig[Literal["numpy.datetime64"], TimeConfig]): "configuration": { "unit": "ms", "scale_factor": 1 - } + } } ``` """ -class TimeDelta64JSON_V3(NamedConfig[Literal["numpy.timedelta64"], TimeConfig]): +class TimeDelta64JSON_V3(NamedRequiredConfig[Literal["numpy.timedelta64"], TimeConfig]): """ The JSON representation of the ``TimeDelta64`` data type in Zarr V3. References ---------- This representation is defined in the numpy.timedelta64 - [specification document](https://zarr-specs.readthedocs.io/en/latest/spec/v3/datatypes.html#numpy-timedelta64). + [specification document](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.timedelta64). Examples -------- @@ -162,7 +151,7 @@ class TimeDelta64JSON_V3(NamedConfig[Literal["numpy.timedelta64"], TimeConfig]): "configuration": { "unit": "ms", "scale_factor": 1 - } + } } ``` """ @@ -217,7 +206,10 @@ class DateTime64JSON_V2(DTypeConfig_V2[str, None]): @dataclass(frozen=True, kw_only=True, slots=True) -class TimeDTypeBase(ZDType[BaseTimeDType_co, BaseTimeScalar_co], HasEndianness, HasItemSize): +class TimeDTypeBase[ + DType: np.dtypes.TimeDelta64DType | np.dtypes.DateTime64DType, + Scalar: np.timedelta64 | np.datetime64, +](ZDType[DType, Scalar], HasEndianness, HasItemSize): """ A base class for data types that represent time via the NumPy TimeDelta64 and DateTime64 data types. @@ -275,7 +267,7 @@ def from_native_dtype(cls, dtype: TBaseDType) -> Self: f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" ) - def to_native_dtype(self) -> BaseTimeDType_co: + def to_native_dtype(self) -> DType: # Numpy does not allow creating datetime64 or timedelta64 via # np.dtypes.{dtype_name}() # so we use np.dtype with a formatted string. @@ -285,7 +277,7 @@ def to_native_dtype(self) -> BaseTimeDType_co: Returns ------- - BaseTimeDType_co + DType A NumPy data type object representing the time data type with the specified unit, scale factor, and byte order. """ @@ -545,7 +537,9 @@ def _cast_scalar_unchecked(self, data: TimeDeltaLike) -> np.timedelta64: numpy.timedelta64 The input data cast as a numpy timedelta64 scalar. """ - return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") + # numpy 2.x stub: timedelta64(scalar, formatted_unit_str) is runtime-valid + # but no overload matches the dynamic f-string unit argument. + return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return] def cast_scalar(self, data: object) -> np.timedelta64: """ @@ -553,6 +547,9 @@ def cast_scalar(self, data: object) -> np.timedelta64: raise a TypeError. """ if self._check_scalar(data): + if isinstance(data, np.timedelta64) and np.isnat(data): + # numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload. + return np.timedelta64("NaT", self.unit) # type: ignore[arg-type] return self._cast_scalar_unchecked(data) msg = ( f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " @@ -567,7 +564,8 @@ def default_scalar(self) -> np.timedelta64: This method provides a default value for the timedelta64 scalar, which is a 'Not-a-Time' (NaT) value. """ - return np.timedelta64("NaT") + # numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload. + return np.timedelta64("NaT", self.unit) # type: ignore[arg-type] def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.timedelta64: """ @@ -591,7 +589,9 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.timedel If the input JSON is not a valid representation of a scalar for this data type. """ if check_json_time(data): - return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") + # numpy 2.x stub: timedelta64(scalar, formatted_unit_str) is runtime-valid + # but no overload matches the dynamic f-string unit argument. + return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return] raise TypeError(f"Invalid type: {data}. Expected an integer.") # pragma: no cover @@ -818,7 +818,9 @@ def _cast_scalar_unchecked(self, data: DateTimeLike) -> np.datetime64: numpy.datetime64 The input cast to a NumPy datetime scalar. """ - return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") + # numpy 2.x stub: datetime64(scalar, formatted_unit_str) is runtime-valid + # but no overload matches the dynamic f-string unit argument. + return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return] def cast_scalar(self, data: object) -> np.datetime64: """ @@ -857,7 +859,8 @@ def default_scalar(self) -> np.datetime64: The default scalar value, which is a 'Not-a-Time' (NaT) value """ - return np.datetime64("NaT") + # numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload. + return np.datetime64("NaT", self.unit) # type: ignore[arg-type] def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.datetime64: """ diff --git a/src/zarr/core/dtype/registry.py b/src/zarr/core/dtype/registry.py index 315945cf4e..0a9b2aa64a 100644 --- a/src/zarr/core/dtype/registry.py +++ b/src/zarr/core/dtype/registry.py @@ -6,15 +6,13 @@ import numpy as np -from zarr.core.dtype.common import ( - DataTypeValidationError, - DTypeJSON, -) +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from importlib.metadata import EntryPoint from zarr.core.common import ZarrFormat + from zarr.core.dtype.common import DTypeJSON from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType diff --git a/src/zarr/core/dtype/wrapper.py b/src/zarr/core/dtype/wrapper.py index fdc5f747f0..42d5d88473 100644 --- a/src/zarr/core/dtype/wrapper.py +++ b/src/zarr/core/dtype/wrapper.py @@ -28,11 +28,9 @@ from typing import ( TYPE_CHECKING, ClassVar, - Generic, Literal, Self, TypeGuard, - TypeVar, overload, ) @@ -44,20 +42,14 @@ # This the upper bound for the scalar types we support. It's numpy scalars + str, # because the new variable-length string dtype in numpy does not have a corresponding scalar type -TBaseScalar = np.generic | str | bytes +type TBaseScalar = np.generic | str | bytes # This is the bound for the dtypes that we support. If we support non-numpy dtypes, # then this bound will need to be widened. -TBaseDType = np.dtype[np.generic] - -# These two type parameters are covariant because we want -# x : ZDType[BaseDType, BaseScalar] = ZDType[SubDType, SubScalar] -# to type check -TScalar_co = TypeVar("TScalar_co", bound=TBaseScalar, covariant=True) -TDType_co = TypeVar("TDType_co", bound=TBaseDType, covariant=True) +type TBaseDType = np.dtype[np.generic] @dataclass(frozen=True, kw_only=True, slots=True) -class ZDType(ABC, Generic[TDType_co, TScalar_co]): +class ZDType[DType: TBaseDType, Scalar: TBaseScalar](ABC): """ Abstract base class for wrapping native array data types, e.g. numpy dtypes @@ -71,11 +63,11 @@ class variable, and it should generally be unique across different data types. """ # this class will create a native data type - dtype_cls: ClassVar[type[TDType_co]] + dtype_cls: ClassVar[type[TBaseDType]] _zarr_v3_name: ClassVar[str] @classmethod - def _check_native_dtype(cls: type[Self], dtype: TBaseDType) -> TypeGuard[TDType_co]: + def _check_native_dtype(cls: type[Self], dtype: TBaseDType) -> TypeGuard[DType]: """ Check that a native data type matches the dtype_cls class attribute. @@ -120,7 +112,7 @@ def from_native_dtype(cls: type[Self], dtype: TBaseDType) -> Self: raise NotImplementedError # pragma: no cover @abstractmethod - def to_native_dtype(self: Self) -> TDType_co: + def to_native_dtype(self: Self) -> DType: """ Return an instance of the wrapped data type. This operation inverts ``from_native_dtype``. @@ -206,7 +198,7 @@ def _check_scalar(self, data: object) -> bool: raise NotImplementedError # pragma: no cover @abstractmethod - def cast_scalar(self, data: object) -> TScalar_co: + def cast_scalar(self, data: object) -> Scalar: """ Cast a python object to the wrapped scalar type. @@ -226,7 +218,7 @@ def cast_scalar(self, data: object) -> TScalar_co: raise NotImplementedError # pragma: no cover @abstractmethod - def default_scalar(self) -> TScalar_co: + def default_scalar(self) -> Scalar: """ Get the default scalar value for the wrapped data type. @@ -242,7 +234,7 @@ def default_scalar(self) -> TScalar_co: raise NotImplementedError # pragma: no cover @abstractmethod - def from_json_scalar(self: Self, data: JSON, *, zarr_format: ZarrFormat) -> TScalar_co: + def from_json_scalar(self: Self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: """ Read a JSON-serializable value as a scalar. diff --git a/src/zarr/core/group.py b/src/zarr/core/group.py index 080e90ff0f..d061e1a5c6 100644 --- a/src/zarr/core/group.py +++ b/src/zarr/core/group.py @@ -1,24 +1,21 @@ from __future__ import annotations import asyncio -import itertools -import json import logging import unicodedata import warnings from collections import defaultdict from dataclasses import asdict, dataclass, field, fields, replace from itertools import accumulate -from typing import TYPE_CHECKING, Literal, TypeVar, assert_never, cast, overload +from typing import TYPE_CHECKING, Literal, assert_never, cast, overload import numpy as np -import numpy.typing as npt -from typing_extensions import deprecated import zarr.api.asynchronous as async_api from zarr.abc.metadata import Metadata from zarr.abc.store import Store, set_or_delete from zarr.core._info import GroupInfo +from zarr.core._json import buffer_to_json_object, json_to_buffer from zarr.core.array import ( DEFAULT_FILL_VALUE, Array, @@ -40,22 +37,25 @@ ZATTRS_JSON, ZGROUP_JSON, ZMETADATA_V2_JSON, - DimensionNames, + ChunksLike, + DimensionNamesLike, NodeType, ShapeLike, ZarrFormat, parse_shapelike, ) from zarr.core.config import config +from zarr.core.dtype import parse_data_type +from zarr.core.json_parse import parse_field from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata from zarr.core.metadata.io import save_metadata from zarr.core.sync import SyncMixin, sync from zarr.errors import ( + ArrayNotFoundError, ContainsArrayError, ContainsGroupError, GroupNotFoundError, MetadataValidationError, - ZarrDeprecationWarning, ZarrUserWarning, ) from zarr.storage import StoreLike, StorePath @@ -83,23 +83,18 @@ logger = logging.getLogger("zarr.group") -DefaultT = TypeVar("DefaultT") - def parse_zarr_format(data: Any) -> ZarrFormat: """Parse the zarr_format field from metadata.""" - if data in (2, 3): - return cast("ZarrFormat", data) - msg = f"Invalid zarr_format. Expected one of 2 or 3. Got {data}." - raise ValueError(msg) + return cast("ZarrFormat", parse_field(data, Literal[2, 3], "zarr_format")) def parse_node_type(data: Any) -> NodeType: """Parse the node_type field from metadata.""" - if data in ("array", "group"): - return cast("Literal['array', 'group']", data) - msg = f"Invalid value for 'node_type'. Expected 'array' or 'group'. Got '{data}'." - raise MetadataValidationError(msg) + return cast( + "Literal['array', 'group']", + parse_field(data, Literal["array", "group"], "node_type", error=MetadataValidationError), + ) # todo: convert None to empty dict @@ -108,7 +103,7 @@ def parse_attributes(data: Any) -> dict[str, Any]: if data is None: return {} elif isinstance(data, dict) and all(isinstance(k, str) for k in data): - return data + return dict(data) msg = f"Expected dict with string keys. Got {type(data)} instead." raise TypeError(msg) @@ -238,13 +233,13 @@ def _flat_to_nested( # array metadata of its immediate children. # In the example, the group at `/a/b` will have consolidated metadata # for its children `array-0` and `array-1`. - # - # metadata = dict(metadata) - keys = sorted(metadata, key=lambda k: k.count("/")) - grouped = { - k: list(v) for k, v in itertools.groupby(keys, key=lambda k: k.rsplit("/", 1)[0]) - } + # Group keys by their parent path. This must not rely on same-parent keys + # being adjacent: the persisted key order is arbitrary, so accumulate + # instead of using itertools.groupby, which only groups consecutive runs. + grouped: dict[str, list[str]] = defaultdict(list) + for k in sorted(metadata, key=lambda k: k.count("/")): + grouped[k.rsplit("/", 1)[0]].append(k) # we go top down and directly manipulate metadata. for key, children_keys in grouped.items(): @@ -272,13 +267,17 @@ def _flat_to_nested( # These are already present, either thanks to being an array in the # root, or by being collected as a child in the else clause continue - children_keys = list(children_keys) - # We pop from metadata, since we're *moving* this under group - children = { - child_key.split("/")[-1]: metadata.pop(child_key) - for child_key in children_keys - if child_key != key - } + children: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] = {} + # We pop from metadata, since we're *moving* this under group. + # While doing this, normalize leaf groups to carry empty consolidated metadata. + for child_key in children_keys: + if child_key == key: + continue + child = metadata.pop(child_key) + if isinstance(child, GroupMetadata) and child.consolidated_metadata is None: + child = replace(child, consolidated_metadata=ConsolidatedMetadata(metadata={})) + children[child_key.split("/")[-1]] = child + parent[name] = replace( node, consolidated_metadata=ConsolidatedMetadata(metadata=children) ) @@ -357,21 +356,15 @@ class GroupMetadata(Metadata): node_type: Literal["group"] = field(default="group", init=False) def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: - json_indent = config.get("json_indent") + indent = config.get("json_indent") if self.zarr_format == 3: - return { - ZARR_JSON: prototype.buffer.from_bytes( - json.dumps(self.to_dict(), indent=json_indent, allow_nan=True).encode() - ) - } + return {ZARR_JSON: json_to_buffer(self.to_dict(), prototype=prototype, indent=indent)} else: items = { - ZGROUP_JSON: prototype.buffer.from_bytes( - json.dumps({"zarr_format": self.zarr_format}, indent=json_indent).encode() - ), - ZATTRS_JSON: prototype.buffer.from_bytes( - json.dumps(self.attributes, indent=json_indent, allow_nan=True).encode() + ZGROUP_JSON: json_to_buffer( + {"zarr_format": self.zarr_format}, prototype=prototype, indent=indent ), + ZATTRS_JSON: json_to_buffer(self.attributes, prototype=prototype, indent=indent), } if self.consolidated_metadata: d = { @@ -396,10 +389,9 @@ def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: }, } - items[ZMETADATA_V2_JSON] = prototype.buffer.from_bytes( - json.dumps( - {"metadata": d, "zarr_consolidated_format": 1}, allow_nan=True - ).encode() + # The consolidated metadata blob is written compactly (no indent). + items[ZMETADATA_V2_JSON] = json_to_buffer( + {"metadata": d, "zarr_consolidated_format": 1}, prototype=prototype ) return items @@ -627,13 +619,13 @@ def _from_bytes_v2( consolidated_metadata_bytes: Buffer | None, ) -> AsyncGroup: # V2 groups are comprised of a .zgroup and .zattrs objects - zgroup = json.loads(zgroup_bytes.to_bytes()) - zattrs = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {} - group_metadata = {**zgroup, "attributes": zattrs} + zgroup = buffer_to_json_object(zgroup_bytes) + zattrs = buffer_to_json_object(zattrs_bytes) if zattrs_bytes is not None else {} + group_metadata: dict[str, Any] = {**zgroup, "attributes": zattrs} if consolidated_metadata_bytes is not None: - v2_consolidated_metadata = json.loads(consolidated_metadata_bytes.to_bytes()) - v2_consolidated_metadata = v2_consolidated_metadata["metadata"] + v2_consolidated_doc = buffer_to_json_object(consolidated_metadata_bytes) + v2_consolidated_metadata = cast("dict[str, Any]", v2_consolidated_doc["metadata"]) # We already read zattrs and zgroup. Should we ignore these? v2_consolidated_metadata.pop(".zattrs", None) v2_consolidated_metadata.pop(".zgroup", None) @@ -668,7 +660,7 @@ def _from_bytes_v3( zarr_json_bytes: Buffer, use_consolidated: bool | None, ) -> AsyncGroup: - group_metadata = json.loads(zarr_json_bytes.to_bytes()) + group_metadata = buffer_to_json_object(zarr_json_bytes) if use_consolidated and group_metadata.get("consolidated_metadata") is None: msg = f"Consolidated metadata requested with 'use_consolidated=True' but not found in '{store_path.path}'." raise ValueError(msg) @@ -806,7 +798,7 @@ async def delitem(self, key: str) -> None: self.metadata.consolidated_metadata.metadata.pop(key, None) await self._save_metadata() - async def get( + async def get[DefaultT]( self, key: str, default: DefaultT | None = None ) -> AnyAsyncArray | AsyncGroup | DefaultT | None: """Obtain a group member, returning default if not found. @@ -828,6 +820,70 @@ async def get( except KeyError: return default + async def get_array(self, path: str) -> AnyAsyncArray: + """Obtain an array member of this group, raising if it is absent or not an array. + + Parameters + ---------- + path : str + Path of the array relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subarray`. + + Returns + ------- + AsyncArray + The array at the given path. + + Raises + ------ + ArrayNotFoundError + If no node exists at the given path. + ContainsGroupError + If the node at the given path is a group rather than an array. + """ + store_path = self.store_path / path + try: + node = await self.getitem(path) + except KeyError as e: + msg = f"No array found in store {store_path.store!r} at path {store_path.path!r}" + raise ArrayNotFoundError(msg) from e + if isinstance(node, AsyncGroup): + msg = f"A group exists in store {store_path.store!r} at path {store_path.path!r}." + raise ContainsGroupError(msg) + return node + + async def get_group(self, path: str) -> AsyncGroup: + """Obtain a group member of this group, raising if it is absent or not a group. + + Parameters + ---------- + path : str + Path of the group relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subsubgroup`. + + Returns + ------- + AsyncGroup + The group at the given path. + + Raises + ------ + GroupNotFoundError + If no node exists at the given path. + ContainsArrayError + If the node at the given path is an array rather than a group. + """ + store_path = self.store_path / path + try: + node = await self.getitem(path) + except KeyError as e: + msg = f"No group found in store {store_path.store!r} at path {store_path.path!r}" + raise GroupNotFoundError(msg) from e + if isinstance(node, AsyncArray): + msg = f"An array exists in store {store_path.store!r} at path {store_path.path!r}." + raise ContainsArrayError(msg) + return node + async def _save_metadata(self, ensure_parents: bool = False) -> None: await save_metadata(self.store_path, self.metadata, ensure_parents=ensure_parents) @@ -843,7 +899,7 @@ def name(self) -> str: # follow h5py convention: add leading slash name = self.path if name[0] != "/": - name = "/" + name + name = f"/{name}" return name return "/" @@ -1022,7 +1078,7 @@ async def create_array( shape: ShapeLike | None = None, dtype: ZDTypeLike | None = None, data: np.ndarray[Any, np.dtype[Any]] | None = None, - chunks: tuple[int, ...] | Literal["auto"] = "auto", + chunks: ChunksLike | Literal["auto"] = "auto", shards: ShardsLike | None = None, filters: FiltersLike = "auto", compressors: CompressorsLike = "auto", @@ -1032,7 +1088,7 @@ async def create_array( order: MemoryOrder | None = None, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, overwrite: bool = False, config: ArrayConfigLike | None = None, @@ -1065,9 +1121,9 @@ async def create_array( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of ``"auto"`` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like @@ -1080,7 +1136,7 @@ async def create_array( filters are applied (if any are specified) and the data is serialized into bytes. For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. + returns another bytestream. Multiple compressors may be provided for Zarr format 3. If no ``compressors`` are provided, a default set of compressors will be used. These defaults can be changed by modifying the value of ``array.v3_default_compressors`` in [`zarr.config`][zarr.config]. @@ -1102,7 +1158,7 @@ async def create_array( fill_value : Any, optional Fill value for the array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory @@ -1162,90 +1218,18 @@ async def create_array( write_data=write_data, ) - @deprecated("Use AsyncGroup.create_array instead.", category=ZarrDeprecationWarning) - async def create_dataset(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> AnyAsyncArray: - """Create an array. - - !!! warning "Deprecated" - `AsyncGroup.create_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0. - Use `AsyncGroup.create_array` instead. - - Arrays are known as "datasets" in HDF5 terminology. For compatibility - with h5py, Zarr groups also implement the [zarr.AsyncGroup.require_dataset][] method. - - Parameters - ---------- - name : str - Array name. - **kwargs : dict - Additional arguments passed to [zarr.AsyncGroup.create_array][]. - - Returns - ------- - a : AsyncArray - """ - data = kwargs.pop("data", None) - # create_dataset in zarr 2.x requires shape but not dtype if data is - # provided. Allow this configuration by inferring dtype from data if - # necessary and passing it to create_array - if "dtype" not in kwargs and data is not None: - kwargs["dtype"] = data.dtype - array = await self.create_array(name, shape=shape, **kwargs) - if data is not None: - await array.setitem(slice(None), data) - return array - - @deprecated("Use AsyncGroup.require_array instead.", category=ZarrDeprecationWarning) - async def require_dataset( - self, - name: str, - *, - shape: tuple[int, ...], - dtype: npt.DTypeLike = None, - exact: bool = False, - **kwargs: Any, - ) -> AnyAsyncArray: - """Obtain an array, creating if it doesn't exist. - - !!! warning "Deprecated" - `AsyncGroup.require_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0. - Use `AsyncGroup.require_dataset` instead. - - Arrays are known as "datasets" in HDF5 terminology. For compatibility - with h5py, Zarr groups also implement the [zarr.AsyncGroup.create_dataset][] method. - - Other `kwargs` are as per [zarr.AsyncGroup.create_dataset][]. - - Parameters - ---------- - name : str - Array name. - shape : int or tuple of ints - Array shape. - dtype : str or dtype, optional - NumPy dtype. - exact : bool, optional - If True, require `dtype` to match exactly. If false, require - `dtype` can be cast from array dtype. - - Returns - ------- - a : AsyncArray - """ - return await self.require_array(name, shape=shape, dtype=dtype, exact=exact, **kwargs) - async def require_array( self, name: str, *, shape: ShapeLike, - dtype: npt.DTypeLike = None, + dtype: ZDTypeLike | None = None, exact: bool = False, **kwargs: Any, ) -> AnyAsyncArray: """Obtain an array, creating if it doesn't exist. - Other `kwargs` are as per [zarr.AsyncGroup.create_dataset][]. + Other `kwargs` are as per [zarr.AsyncGroup.create_array][]. Parameters ---------- @@ -1253,8 +1237,9 @@ async def require_array( Array name. shape : int or tuple of ints Array shape. - dtype : str or dtype, optional - NumPy dtype. + dtype : ZDTypeLike, optional + The data type of the array, given as a string, a NumPy dtype, or a + Zarr data type. exact : bool, optional If True, require `dtype` to match exactly. If false, require `dtype` can be cast from array dtype. @@ -1272,7 +1257,11 @@ async def require_array( if shape != ds.shape: raise TypeError(f"Incompatible shape ({ds.shape} vs {shape})") - dtype = np.dtype(dtype) + # `np.dtype(None)` used to resolve to float64 here; keep that default. + dtype = parse_data_type( + "float64" if dtype is None else dtype, + zarr_format=self.metadata.zarr_format, + ).to_native_dtype() if exact: if ds.dtype != dtype: raise TypeError(f"Incompatible dtype ({ds.dtype} vs {dtype})") @@ -1921,7 +1910,9 @@ def __getitem__(self, path: str) -> AnyArray | Group: else: return Group(obj) - def get(self, path: str, default: DefaultT | None = None) -> AnyArray | Group | DefaultT | None: + def get[DefaultT]( + self, path: str, default: DefaultT | None = None + ) -> AnyArray | Group | DefaultT | None: """Obtain a group member, returning default if not found. Parameters @@ -1958,6 +1949,74 @@ def get(self, path: str, default: DefaultT | None = None) -> AnyArray | Group | except KeyError: return default + def get_array(self, path: str) -> AnyArray: + """Obtain an array member of this group, raising if it is absent or not an array. + + Parameters + ---------- + path : str + Path of the array relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subarray`. + + Returns + ------- + Array + The array at the given path. + + Raises + ------ + ArrayNotFoundError + If no node exists at the given path. + ContainsGroupError + If the node at the given path is a group rather than an array. + + Examples + -------- + ```python + import zarr + from zarr.core.group import Group + group = Group.from_store(zarr.storage.MemoryStore()) + group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="float64") + group.get_array("subarray") + # + ``` + """ + return Array(self._sync(self._async_group.get_array(path))) + + def get_group(self, path: str) -> Group: + """Obtain a group member of this group, raising if it is absent or not a group. + + Parameters + ---------- + path : str + Path of the group relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subsubgroup`. + + Returns + ------- + Group + The group at the given path. + + Raises + ------ + GroupNotFoundError + If no node exists at the given path. + ContainsArrayError + If the node at the given path is an array rather than a group. + + Examples + -------- + ```python + import zarr + from zarr.core.group import Group + group = Group.from_store(zarr.storage.MemoryStore()) + group.create_group(name="subgroup") + group.get_group("subgroup") + # + ``` + """ + return Group(self._sync(self._async_group.get_group(path))) + def __delitem__(self, key: str) -> None: """Delete a group member. @@ -1969,12 +2028,13 @@ def __delitem__(self, key: str) -> None: Examples -------- >>> import zarr - >>> group = Group.from_store(zarr.storage.MemoryStore() - >>> group.create_array(name="subarray", shape=(10,), chunks=(10,)) + >>> group = Group.from_store(zarr.storage.MemoryStore()) + >>> a = group.create_array(name="subarray", dtype="i1", shape=(10,), chunks=(10,)) >>> del group["subarray"] >>> "subarray" in group False """ + self._sync(self._async_group.delitem(key)) def __iter__(self) -> Iterator[str]: @@ -1985,14 +2045,10 @@ def __iter__(self) -> Iterator[str]: >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') - >>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,)) - >>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,)) - >>> for name in g1: - ... print(name) - baz - bar - foo - quux + >>> d1 = g1.create_array('baz', dtype="i1", shape=(10,), chunks=(10,)) + >>> d2 = g1.create_array('quux', dtype="i1", shape=(10,), chunks=(10,)) + >>> sorted(g1) + ['bar', 'baz', 'foo', 'quux'] """ yield from self.keys() @@ -2015,11 +2071,12 @@ def __setitem__(self, key: str, value: Any) -> None: Examples -------- + >>> import numpy as np >>> import zarr >>> group = zarr.group() - >>> group["foo"] = zarr.zeros((10,)) + >>> group["foo"] = np.array(zarr.zeros((10,))) >>> group["foo"] - + """ self._sync(self._async_group.setitem(key, value)) @@ -2031,10 +2088,15 @@ async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group Examples -------- - >>> import zarr - >>> group = zarr.group() - >>> await group.update_attributes_async({"foo": "bar"}) - >>> group.attrs.asdict() + >>> async def example(): + ... import zarr + ... + ... group = zarr.group() + ... new_group = await group.update_attributes_async({"foo": "bar"}) + ... return new_group.attrs.asdict() + + >>> import asyncio + >>> asyncio.run(example()) {'foo': 'bar'} """ new_metadata = replace(self.metadata, attributes=new_attributes) @@ -2133,8 +2195,7 @@ def update_attributes(self, new_attributes: dict[str, Any]) -> Group: Examples -------- >>> import zarr - >>> group = zarr.group() - >>> group.update_attributes({"foo": "bar"}) + >>> group = zarr.group().update_attributes({"foo": "bar"}) >>> group.attrs.asdict() {'foo': 'bar'} """ @@ -2240,19 +2301,17 @@ def create_hierarchy( >>> import zarr >>> from zarr.core.group import GroupMetadata >>> root = zarr.create_group(store={}) - >>> for key, val in root.create_hierarchy({'a/b/c': GroupMetadata()}): - ... print(key, val) - ... - - - + >>> sorted(root.create_hierarchy({'a/b/c': GroupMetadata()})) + [('a', ), + ('a/b', ), + ('a/b/c', )] """ for key, node in self._sync_iter( self._async_group.create_hierarchy(nodes, overwrite=overwrite) ): yield (key, _parse_async_node(node)) - def keys(self) -> Generator[str, None]: + def keys(self) -> Generator[str]: """Return an iterator over group member names. Examples @@ -2261,14 +2320,10 @@ def keys(self) -> Generator[str, None]: >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') - >>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,)) - >>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,)) - >>> for name in g1.keys(): - ... print(name) - baz - bar - foo - quux + >>> d1 = g1.create_array('baz', dtype="i1", shape=(10,), chunks=(10,)) + >>> d2 = g1.create_array('quux', dtype="i1", shape=(10,), chunks=(10,)) + >>> sorted(g1.keys()) + ['bar', 'baz', 'foo', 'quux'] """ yield from self._sync_iter(self._async_group.keys()) @@ -2280,14 +2335,13 @@ def __contains__(self, member: str) -> bool: >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') - >>> d1 = g1.create_array('bar', shape=(10,), chunks=(10,)) + >>> d1 = g1.create_array('bar', dtype="i1", shape=(10,), chunks=(10,)) >>> 'foo' in g1 True >>> 'bar' in g1 True >>> 'baz' in g1 False - """ return self._sync(self._async_group.contains(member)) @@ -2298,10 +2352,9 @@ def groups(self) -> Generator[tuple[str, Group], None]: -------- >>> import zarr >>> group = zarr.group() - >>> group.create_group("subgroup") - >>> for name, subgroup in group.groups(): - ... print(name, subgroup) - subgroup + >>> subgroup = group.create_group("subgroup") + >>> list(group.groups()) + [('subgroup', )] """ for name, async_group in self._sync_iter(self._async_group.groups()): yield name, Group(async_group) @@ -2313,10 +2366,9 @@ def group_keys(self) -> Generator[str, None]: -------- >>> import zarr >>> group = zarr.group() - >>> group.create_group("subgroup") - >>> for name in group.group_keys(): - ... print(name) - subgroup + >>> subgroup = group.create_group("subgroup") + >>> list(group.group_keys()) + ['subgroup'] """ for name, _ in self.groups(): yield name @@ -2328,10 +2380,9 @@ def group_values(self) -> Generator[Group, None]: -------- >>> import zarr >>> group = zarr.group() - >>> group.create_group("subgroup") - >>> for subgroup in group.group_values(): - ... print(subgroup) - + >>> subgroup = group.create_group("subgroup") + >>> list(group.group_values()) + [] """ for _, group in self.groups(): yield group @@ -2343,10 +2394,9 @@ def arrays(self) -> Generator[tuple[str, AnyArray], None]: -------- >>> import zarr >>> group = zarr.group() - >>> group.create_array("subarray", shape=(10,), chunks=(10,)) - >>> for name, subarray in group.arrays(): - ... print(name, subarray) - subarray + >>> subarray = group.create_array("subarray", dtype="i1", shape=(10,), chunks=(10,)) + >>> list(group.arrays()) + [('subarray', )] """ for name, async_array in self._sync_iter(self._async_group.arrays()): yield name, Array(async_array) @@ -2358,10 +2408,9 @@ def array_keys(self) -> Generator[str, None]: -------- >>> import zarr >>> group = zarr.group() - >>> group.create_array("subarray", shape=(10,), chunks=(10,)) - >>> for name in group.array_keys(): - ... print(name) - subarray + >>> subarray = group.create_array("subarray", dtype="i1", shape=(10,), chunks=(10,)) + >>> list(group.array_keys()) + ['subarray'] """ for name, _ in self.arrays(): @@ -2374,10 +2423,9 @@ def array_values(self) -> Generator[AnyArray, None]: -------- >>> import zarr >>> group = zarr.group() - >>> group.create_array("subarray", shape=(10,), chunks=(10,)) - >>> for subarray in group.array_values(): - ... print(subarray) - + >>> subarray = group.create_array("subarray", dtype="i1", shape=(10,), chunks=(10,)) + >>> list(group.array_values()) + [] """ for _, array in self.arrays(): yield array @@ -2434,7 +2482,7 @@ def create_group(self, name: str, **kwargs: Any) -> Group: >>> group = zarr.group() >>> subgroup = group.create_group("subgroup") >>> subgroup - + """ return Group(self._sync(self._async_group.create_group(name, **kwargs))) @@ -2473,7 +2521,7 @@ def create( shape: ShapeLike | None = None, dtype: ZDTypeLike | None = None, data: np.ndarray[Any, np.dtype[Any]] | None = None, - chunks: tuple[int, ...] | Literal["auto"] = "auto", + chunks: ChunksLike | Literal["auto"] = "auto", shards: ShardsLike | None = None, filters: FiltersLike = "auto", compressors: CompressorsLike = "auto", @@ -2483,7 +2531,7 @@ def create( order: MemoryOrder | None = None, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, overwrite: bool = False, config: ArrayConfigLike | None = None, @@ -2518,9 +2566,9 @@ def create( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of ``"auto"`` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like @@ -2533,7 +2581,7 @@ def create( filters are applied (if any are specified) and the data is serialized into bytes. For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. + returns another bytestream. Multiple compressors may be provided for Zarr format 3. If no ``compressors`` are provided, a default set of compressors will be used. These defaults can be changed by modifying the value of ``array.v3_default_compressors`` in [`zarr.config`][]. @@ -2555,7 +2603,7 @@ def create( fill_value : Any, optional Fill value for the array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory @@ -2617,7 +2665,7 @@ def create_array( shape: ShapeLike | None = None, dtype: ZDTypeLike | None = None, data: np.ndarray[Any, np.dtype[Any]] | None = None, - chunks: tuple[int, ...] | Literal["auto"] = "auto", + chunks: ChunksLike | Literal["auto"] = "auto", shards: ShardsLike | None = None, filters: FiltersLike = "auto", compressors: CompressorsLike = "auto", @@ -2627,7 +2675,7 @@ def create_array( order: MemoryOrder | None = None, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, storage_options: dict[str, Any] | None = None, overwrite: bool = False, config: ArrayConfigLike | None = None, @@ -2662,9 +2710,9 @@ def create_array( dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. + order of your filters is consistent with the behavior of each filter. - The default value of ``"auto"`` instructs Zarr to use a default used based on the data + The default value of ``"auto"`` instructs Zarr to use a default based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like @@ -2677,7 +2725,7 @@ def create_array( filters are applied (if any are specified) and the data is serialized into bytes. For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. + returns another bytestream. Multiple compressors may be provided for Zarr format 3. If no ``compressors`` are provided, a default set of compressors will be used. These defaults can be changed by modifying the value of ``array.v3_default_compressors`` in [`zarr.config`][zarr.config]. @@ -2699,7 +2747,7 @@ def create_array( fill_value : Any, optional Fill value for the array. order : {"C", "F"}, optional - The memory of the array (default is "C"). + The memory order of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory @@ -2760,57 +2808,6 @@ def create_array( ) ) - @deprecated("Use Group.create_array instead.", category=ZarrDeprecationWarning) - def create_dataset(self, name: str, **kwargs: Any) -> AnyArray: - """Create an array. - - !!! warning "Deprecated" - `Group.create_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0. - Use `Group.create_array` instead. - - - Arrays are known as "datasets" in HDF5 terminology. For compatibility - with h5py, Zarr groups also implement the [zarr.Group.require_dataset][] method. - - Parameters - ---------- - name : str - Array name. - **kwargs : dict - Additional arguments passed to [zarr.Group.create_array][] - - Returns - ------- - a : Array - """ - return Array(self._sync(self._async_group.create_dataset(name, **kwargs))) - - @deprecated("Use Group.require_array instead.", category=ZarrDeprecationWarning) - def require_dataset(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> AnyArray: - """Obtain an array, creating if it doesn't exist. - - !!! warning "Deprecated" - `Group.require_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0. - Use `Group.require_array` instead. - - Arrays are known as "datasets" in HDF5 terminology. For compatibility - with h5py, Zarr groups also implement the [zarr.Group.create_dataset][] method. - - Other `kwargs` are as per [zarr.Group.create_dataset][]. - - Parameters - ---------- - name : str - Array name. - **kwargs : - See [zarr.Group.create_dataset][]. - - Returns - ------- - a : Array - """ - return Array(self._sync(self._async_group.require_array(name, shape=shape, **kwargs))) - def require_array(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> AnyArray: """Obtain an array, creating if it doesn't exist. @@ -3008,152 +3005,6 @@ def move(self, source: str, dest: str) -> None: """ return self._sync(self._async_group.move(source, dest)) - @deprecated("Use Group.create_array instead.", category=ZarrDeprecationWarning) - def array( - self, - name: str, - *, - shape: ShapeLike, - dtype: npt.DTypeLike, - chunks: tuple[int, ...] | Literal["auto"] = "auto", - shards: tuple[int, ...] | Literal["auto"] | None = None, - filters: FiltersLike = "auto", - compressors: CompressorsLike = "auto", - compressor: CompressorLike = None, - serializer: SerializerLike = "auto", - fill_value: Any | None = DEFAULT_FILL_VALUE, - order: MemoryOrder | None = None, - attributes: dict[str, JSON] | None = None, - chunk_key_encoding: ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, - storage_options: dict[str, Any] | None = None, - overwrite: bool = False, - config: ArrayConfigLike | None = None, - data: npt.ArrayLike | None = None, - ) -> AnyArray: - """Create an array within this group. - - !!! warning "Deprecated" - `Group.array()` is deprecated since v3.0.0 and will be removed in a future release. - Use `Group.create_array` instead. - - This method lightly wraps [zarr.core.array.create_array][]. - - Parameters - ---------- - name : str - The name of the array relative to the group. If ``path`` is ``None``, the array will be located - at the root of the store. - shape : tuple[int, ...] - Shape of the array. - dtype : npt.DTypeLike - Data type of the array. - chunks : tuple[int, ...], optional - Chunk shape of the array. - If not specified, default are guessed based on the shape and dtype. - shards : tuple[int, ...], optional - Shard shape of the array. The default value of ``None`` results in no sharding at all. - filters : Iterable[Codec] | Literal["auto"], optional - Iterable of filters to apply to each chunk of the array, in order, before serializing that - chunk to bytes. - - For Zarr format 3, a "filter" is a codec that takes an array and returns an array, - and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a - dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. - - For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the - the order if your filters is consistent with the behavior of each filter. - - The default value of ``"auto"`` instructs Zarr to use a default used based on the data - type of the array and the Zarr format specified. For all data types in Zarr V3, and most - data types in Zarr V2, the default filters are empty. The only cases where default filters - are not empty is when the Zarr format is 2, and the data type is a variable-length data type like - [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, - the default filters contains a single element which is a codec specific to that particular data type. - - To create an array with no filters, provide an empty iterable or the value ``None``. - compressors : Iterable[Codec], optional - List of compressors to apply to the array. Compressors are applied in order, and after any - filters are applied (if any are specified) and the data is serialized into bytes. - - For Zarr format 3, a "compressor" is a codec that takes a bytestream, and - returns another bytestream. Multiple compressors my be provided for Zarr format 3. - If no ``compressors`` are provided, a default set of compressors will be used. - These defaults can be changed by modifying the value of ``array.v3_default_compressors`` - in [`zarr.config`][zarr.config]. - Use ``None`` to omit default compressors. - - For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may - be provided for Zarr format 2. - If no ``compressor`` is provided, a default compressor will be used. - in [`zarr.config`][zarr.config]. - Use ``None`` to omit the default compressor. - compressor : Codec, optional - Deprecated in favor of ``compressors``. - serializer : dict[str, JSON] | ArrayBytesCodec, optional - Array-to-bytes codec to use for encoding the array data. - Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. - If no ``serializer`` is provided, a default serializer will be used. - These defaults can be changed by modifying the value of ``array.v3_default_serializer`` - in [`zarr.config`][zarr.config]. - fill_value : Any, optional - Fill value for the array. - order : {"C", "F"}, optional - The memory of the array (default is "C"). - For Zarr format 2, this parameter sets the memory order of the array. - For Zarr format 3, this parameter is deprecated, because memory order - is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory - order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. - If no ``order`` is provided, a default order will be used. - This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config]. - attributes : dict, optional - Attributes for the array. - chunk_key_encoding : ChunkKeyEncoding, optional - A specification of how the chunk keys are represented in storage. - For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. - For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. - dimension_names : Iterable[str], optional - The names of the dimensions (default is None). - Zarr format 3 only. Zarr format 2 arrays should not use this parameter. - storage_options : dict, optional - If using an fsspec URL to create the store, these will be passed to the backend implementation. - Ignored otherwise. - overwrite : bool, default False - Whether to overwrite an array with the same name in the store, if one exists. - config : ArrayConfig or ArrayConfigLike, optional - Runtime configuration for the array. - data : array_like - The data to fill the array with. - - Returns - ------- - AsyncArray - """ - compressors = _parse_deprecated_compressor(compressor, compressors) - return Array( - self._sync( - self._async_group.create_dataset( - name=name, - shape=shape, - dtype=dtype, - chunks=chunks, - shards=shards, - fill_value=fill_value, - attributes=attributes, - chunk_key_encoding=chunk_key_encoding, - compressors=compressors, - serializer=serializer, - dimension_names=dimension_names, - order=order, - filters=filters, - overwrite=overwrite, - storage_options=storage_options, - config=config, - data=data, - ) - ) - ) - async def create_hierarchy( *, @@ -3197,21 +3048,24 @@ async def create_hierarchy( Yields ------ tuple[str, AsyncGroup | AsyncArray] - This function yields (path, node) pairs, in the order the nodes were created. + Yields (path, node) pairs, in the order the nodes were created. Examples -------- - >>> from zarr.api.asynchronous import create_hierarchy - >>> from zarr.storage import MemoryStore - >>> from zarr.core.group import GroupMetadata + >>> async def example(): + ... from zarr.api.asynchronous import create_hierarchy + ... from zarr.core.group import GroupMetadata + ... from zarr.storage import MemoryStore + ... + ... store = MemoryStore() + ... nodes = {'a': GroupMetadata(attributes={'name': 'leaf'})} + ... return sorted([x async for x in create_hierarchy(store=store, nodes=nodes)]) + >>> import asyncio - >>> store = MemoryStore() - >>> nodes = {'a': GroupMetadata(attributes={'name': 'leaf'})} - >>> async def run(): - ... print(dict([x async for x in create_hierarchy(store=store, nodes=nodes)])) - >>> asyncio.run(run()) - # {'a': , '': } + >>> asyncio.run(example()) + [('', ), ('a', )] """ + # normalize the keys to be valid paths nodes_normed_keys = _normalize_path_keys(nodes) @@ -3348,7 +3202,7 @@ async def create_nodes( """ # Note: the only way to alter this value is via the config. If that's undesirable for some reason, - # then we should consider adding a keyword argument this this function + # then we should consider adding a keyword argument to this function semaphore = asyncio.Semaphore(config.get("async.concurrency")) create_tasks: list[Coroutine[None, None, str]] = [] @@ -3644,9 +3498,7 @@ async def _read_metadata_v3(store: Store, path: str) -> ArrayV3Metadata | GroupM ) if zarr_json_bytes is None: raise FileNotFoundError(path) - else: - zarr_json = json.loads(zarr_json_bytes.to_bytes()) - return _build_metadata_v3(zarr_json) + return _build_metadata_v3(buffer_to_json_object(zarr_json_bytes)) async def _read_metadata_v2(store: Store, path: str) -> ArrayV2Metadata | GroupMetadata: @@ -3663,22 +3515,23 @@ async def _read_metadata_v2(store: Store, path: str) -> ArrayV2Metadata | GroupM store.get(_join_paths([path, ZATTRS_JSON]), prototype=default_buffer_prototype()), ) + zattrs: dict[str, JSON] if zattrs_bytes is None: zattrs = {} else: - zattrs = json.loads(zattrs_bytes.to_bytes()) + zattrs = buffer_to_json_object(zattrs_bytes) # TODO: decide how to handle finding both array and group metadata. The spec does not seem to # consider this situation. A practical approach would be to ignore that combination, and only # return the array metadata. if zarray_bytes is not None: - zmeta = json.loads(zarray_bytes.to_bytes()) + zmeta = buffer_to_json_object(zarray_bytes) else: if zgroup_bytes is None: # neither .zarray or .zgroup were found results in KeyError raise FileNotFoundError(path) else: - zmeta = json.loads(zgroup_bytes.to_bytes()) + zmeta = buffer_to_json_object(zgroup_bytes) return _build_metadata_v2(zmeta, zattrs) diff --git a/src/zarr/core/indexing.py b/src/zarr/core/indexing.py index d226c03675..a1b050cb7b 100644 --- a/src/zarr/core/indexing.py +++ b/src/zarr/core/indexing.py @@ -3,22 +3,18 @@ import itertools import math import numbers -import operator from collections.abc import Iterator, Sequence from dataclasses import dataclass from enum import Enum -from functools import lru_cache, reduce +from functools import lru_cache from types import EllipsisType from typing import ( TYPE_CHECKING, Any, - Generic, Literal, NamedTuple, Protocol, - TypeAlias, TypeGuard, - TypeVar, cast, runtime_checkable, ) @@ -26,8 +22,10 @@ import numpy as np import numpy.typing as npt +from zarr.core.chunk_grids import FixedDimension from zarr.core.common import ceildiv, product -from zarr.core.metadata import T_ArrayMetadata +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.core.metadata.v3 import ArrayV3Metadata from zarr.errors import ( ArrayIndexError, BoundsCheckError, @@ -38,7 +36,7 @@ if TYPE_CHECKING: from zarr.core.array import AsyncArray from zarr.core.buffer import NDArrayLikeOrScalar - from zarr.core.chunk_grids import ChunkGrid + from zarr.core.chunk_grids import ChunkGrid, DimensionGrid from zarr.types import AnyArray @@ -79,7 +77,7 @@ class Indexer(Protocol): def __iter__(self) -> Iterator[ChunkProjection]: ... -_ArrayIndexingOrder: TypeAlias = Literal["lexicographic"] +type _ArrayIndexingOrder = Literal["lexicographic"] def _iter_grid( @@ -332,15 +330,6 @@ def is_pure_orthogonal_indexing(selection: Selection, ndim: int) -> TypeGuard[Or ) -def get_chunk_shape(chunk_grid: ChunkGrid) -> tuple[int, ...]: - from zarr.core.chunk_grids import RegularChunkGrid - - assert isinstance(chunk_grid, RegularChunkGrid), ( - "Only regular chunk grid is supported, currently." - ) - return chunk_grid.chunk_shape - - def normalize_integer_selection(dim_sel: int, dim_len: int) -> int: # normalize type to int dim_sel = int(dim_sel) @@ -380,35 +369,41 @@ class ChunkDimProjection(NamedTuple): class IntDimIndexer: dim_sel: int dim_len: int - dim_chunk_len: int + dim_grid: DimensionGrid nitems: int = 1 - def __init__(self, dim_sel: int, dim_len: int, dim_chunk_len: int) -> None: + def __init__(self, dim_sel: int, dim_len: int, dim_grid: DimensionGrid) -> None: object.__setattr__(self, "dim_sel", normalize_integer_selection(dim_sel, dim_len)) object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) + object.__setattr__(self, "dim_grid", dim_grid) def __iter__(self) -> Iterator[ChunkDimProjection]: - dim_chunk_ix = self.dim_sel // self.dim_chunk_len - dim_offset = dim_chunk_ix * self.dim_chunk_len + g = self.dim_grid + dim_chunk_ix = g.index_to_chunk(self.dim_sel) + dim_offset = g.chunk_offset(dim_chunk_ix) dim_chunk_sel = self.dim_sel - dim_offset dim_out_sel = None - is_complete_chunk = self.dim_chunk_len == 1 + is_complete_chunk = g.data_size(dim_chunk_ix) == 1 yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk) @dataclass(frozen=True) class SliceDimIndexer: dim_len: int - dim_chunk_len: int nitems: int nchunks: int + dim_grid: DimensionGrid start: int stop: int step: int - def __init__(self, dim_sel: slice, dim_len: int, dim_chunk_len: int) -> None: + def __init__( + self, + dim_sel: slice, + dim_len: int, + dim_grid: DimensionGrid, + ) -> None: # normalize start, stop, step = dim_sel.indices(dim_len) if step < 1: @@ -419,23 +414,25 @@ def __init__(self, dim_sel: slice, dim_len: int, dim_chunk_len: int) -> None: object.__setattr__(self, "step", step) object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) + object.__setattr__(self, "dim_grid", dim_grid) object.__setattr__(self, "nitems", max(0, ceildiv((stop - start), step))) - object.__setattr__(self, "nchunks", ceildiv(dim_len, dim_chunk_len)) + object.__setattr__(self, "nchunks", dim_grid.nchunks) def __iter__(self) -> Iterator[ChunkDimProjection]: # figure out the range of chunks we need to visit - dim_chunk_ix_from = 0 if self.start == 0 else self.start // self.dim_chunk_len - dim_chunk_ix_to = ceildiv(self.stop, self.dim_chunk_len) + if self.start >= self.stop: + return # empty slice + g = self.dim_grid + dim_chunk_ix_from = g.index_to_chunk(self.start) if self.start > 0 else 0 + dim_chunk_ix_to = g.index_to_chunk(self.stop - 1) + 1 if self.stop > 0 else 0 # iterate over chunks in range for dim_chunk_ix in range(dim_chunk_ix_from, dim_chunk_ix_to): # compute offsets for chunk within overall array - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_limit = min(self.dim_len, (dim_chunk_ix + 1) * self.dim_chunk_len) - + dim_offset = g.chunk_offset(dim_chunk_ix) # determine chunk length, accounting for trailing chunk - dim_chunk_len = dim_limit - dim_offset + dim_chunk_len = g.data_size(dim_chunk_ix) + dim_limit = dim_offset + dim_chunk_len if self.start < dim_offset: # selection starts before current chunk @@ -445,7 +442,6 @@ def __iter__(self) -> Iterator[ChunkDimProjection]: dim_chunk_sel_start += self.step - remainder # compute number of previous items, provides offset into output array dim_out_offset = ceildiv((dim_offset - self.start), self.step) - else: # selection starts within current chunk dim_chunk_sel_start = self.start - dim_offset @@ -454,7 +450,6 @@ def __iter__(self) -> Iterator[ChunkDimProjection]: if self.stop > dim_limit: # selection ends after current chunk dim_chunk_sel_stop = dim_chunk_len - else: # selection ends within current chunk dim_chunk_sel_stop = self.stop - dim_offset @@ -467,7 +462,6 @@ def __iter__(self) -> Iterator[ChunkDimProjection]: continue dim_out_sel = slice(dim_out_offset, dim_out_offset + dim_chunk_nitems) - is_complete_chunk = ( dim_chunk_sel_start == 0 and (self.stop >= dim_limit) and self.step in [1, None] ) @@ -518,13 +512,11 @@ def replace_ellipsis(selection: Any, shape: tuple[int, ...]) -> SelectionNormali def replace_lists(selection: SelectionNormalized) -> SelectionNormalized: return tuple( - np.asarray(dim_sel) if isinstance(dim_sel, list) else dim_sel for dim_sel in selection + cast("ArrayOfIntOrBool", np.asarray(dim_sel)) if isinstance(dim_sel, list) else dim_sel + for dim_sel in selection ) -T = TypeVar("T") - - def ensure_tuple(v: Any) -> SelectionNormalized: if not isinstance(v, tuple): v = (v,) @@ -588,21 +580,19 @@ def __init__( shape: tuple[int, ...], chunk_grid: ChunkGrid, ) -> None: - chunk_shape = get_chunk_shape(chunk_grid) + dim_grids = chunk_grid._dimensions # handle ellipsis selection_normalized = replace_ellipsis(selection, shape) # setup per-dimension indexers dim_indexers: list[IntDimIndexer | SliceDimIndexer] = [] - for dim_sel, dim_len, dim_chunk_len in zip( - selection_normalized, shape, chunk_shape, strict=True - ): + for dim_sel, dim_len, dim_grid in zip(selection_normalized, shape, dim_grids, strict=True): dim_indexer: IntDimIndexer | SliceDimIndexer if is_integer(dim_sel): - dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len) + dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_grid) elif is_slice(dim_sel): - dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len) + dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_grid) else: raise IndexError( @@ -635,7 +625,7 @@ def __iter__(self) -> Iterator[ChunkProjection]: class BoolArrayDimIndexer: dim_sel: npt.NDArray[np.bool_] dim_len: int - dim_chunk_len: int + dim_grid: DimensionGrid nchunks: int chunk_nitems: npt.NDArray[Any] @@ -643,7 +633,12 @@ class BoolArrayDimIndexer: nitems: int dim_chunk_ixs: npt.NDArray[np.intp] - def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: int) -> None: + def __init__( + self, + dim_sel: npt.NDArray[np.bool_], + dim_len: int, + dim_grid: DimensionGrid, + ) -> None: # check number of dimensions if not is_bool_array(dim_sel, 1): raise IndexError("Boolean arrays in an orthogonal selection must be 1-dimensional only") @@ -654,13 +649,16 @@ def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: f"Boolean array has the wrong length for dimension; expected {dim_len}, got {dim_sel.shape[0]}" ) + g = dim_grid + nchunks = g.nchunks + # precompute number of selected items for each chunk - nchunks = ceildiv(dim_len, dim_chunk_len) chunk_nitems = np.zeros(nchunks, dtype="i8") for dim_chunk_ix in range(nchunks): - dim_offset = dim_chunk_ix * dim_chunk_len + dim_offset = g.chunk_offset(dim_chunk_ix) + chunk_len = g.data_size(dim_chunk_ix) chunk_nitems[dim_chunk_ix] = np.count_nonzero( - dim_sel[dim_offset : dim_offset + dim_chunk_len] + dim_sel[dim_offset : dim_offset + chunk_len] ) chunk_nitems_cumsum = np.cumsum(chunk_nitems) nitems = chunk_nitems_cumsum[-1] @@ -669,7 +667,7 @@ def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: # store attributes object.__setattr__(self, "dim_sel", dim_sel) object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) + object.__setattr__(self, "dim_grid", dim_grid) object.__setattr__(self, "nchunks", nchunks) object.__setattr__(self, "chunk_nitems", chunk_nitems) object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) @@ -677,15 +675,19 @@ def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs) def __iter__(self) -> Iterator[ChunkDimProjection]: + g = self.dim_grid + # iterate over chunks with at least one item for dim_chunk_ix in self.dim_chunk_ixs: # find region in chunk - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_chunk_sel = self.dim_sel[dim_offset : dim_offset + self.dim_chunk_len] - - # pad out if final chunk - if dim_chunk_sel.shape[0] < self.dim_chunk_len: - tmp = np.zeros(self.dim_chunk_len, dtype=bool) + dim_offset = g.chunk_offset(dim_chunk_ix) + chunk_len = g.data_size(dim_chunk_ix) + dim_chunk_sel = self.dim_sel[dim_offset : dim_offset + chunk_len] + + # pad out if boundary chunk (codec buffer may be larger than valid data region) + codec_size = g.chunk_size(dim_chunk_ix) + if dim_chunk_sel.shape[0] < codec_size: + tmp = np.zeros(codec_size, dtype=bool) tmp[: dim_chunk_sel.shape[0]] = dim_chunk_sel dim_chunk_sel = tmp @@ -744,7 +746,7 @@ class IntArrayDimIndexer: """Integer array selection against a single dimension.""" dim_len: int - dim_chunk_len: int + dim_grid: DimensionGrid nchunks: int nitems: int order: Order @@ -758,7 +760,7 @@ def __init__( self, dim_sel: npt.NDArray[np.intp], dim_len: int, - dim_chunk_len: int, + dim_grid: DimensionGrid, wraparound: bool = True, boundscheck: bool = True, order: Order = Order.UNKNOWN, @@ -769,7 +771,8 @@ def __init__( raise IndexError("integer arrays in an orthogonal selection must be 1-dimensional only") nitems = len(dim_sel) - nchunks = ceildiv(dim_len, dim_chunk_len) + g = dim_grid + nchunks = g.nchunks # handle wraparound if wraparound: @@ -782,7 +785,7 @@ def __init__( # determine which chunk is needed for each selection item # note: for dense integer selections, the division operation here is the # bottleneck - dim_sel_chunk = dim_sel // dim_chunk_len + dim_sel_chunk = g.indices_to_chunks(dim_sel) # determine order of indices if order == Order.UNKNOWN: @@ -811,7 +814,7 @@ def __init__( # store attributes object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) + object.__setattr__(self, "dim_grid", dim_grid) object.__setattr__(self, "nchunks", nchunks) object.__setattr__(self, "nitems", nitems) object.__setattr__(self, "order", order) @@ -822,6 +825,8 @@ def __init__( object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) def __iter__(self) -> Iterator[ChunkDimProjection]: + g = self.dim_grid + for dim_chunk_ix in self.dim_chunk_ixs: dim_out_sel: slice | npt.NDArray[np.intp] # find region in output @@ -836,7 +841,7 @@ def __iter__(self) -> Iterator[ChunkDimProjection]: dim_out_sel = self.dim_out_sel[start:stop] # find region in chunk - dim_offset = dim_chunk_ix * self.dim_chunk_len + dim_offset = g.chunk_offset(dim_chunk_ix) dim_chunk_sel = self.dim_sel[start:stop] - dim_offset is_complete_chunk = False # TODO yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk) @@ -896,13 +901,13 @@ def oindex_set(a: npt.NDArray[Any], selection: Selection, value: Any) -> None: @dataclass(frozen=True) class OrthogonalIndexer(Indexer): dim_indexers: list[IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer] + dim_grids: tuple[DimensionGrid, ...] shape: tuple[int, ...] - chunk_shape: tuple[int, ...] is_advanced: bool drop_axes: tuple[int, ...] def __init__(self, selection: Selection, shape: tuple[int, ...], chunk_grid: ChunkGrid) -> None: - chunk_shape = get_chunk_shape(chunk_grid) + dim_grids = chunk_grid._dimensions # handle ellipsis selection = replace_ellipsis(selection, shape) @@ -914,19 +919,19 @@ def __init__(self, selection: Selection, shape: tuple[int, ...], chunk_grid: Chu dim_indexers: list[ IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer ] = [] - for dim_sel, dim_len, dim_chunk_len in zip(selection, shape, chunk_shape, strict=True): + for dim_sel, dim_len, dim_grid in zip(selection, shape, dim_grids, strict=True): dim_indexer: IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer if is_integer(dim_sel): - dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len) + dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_grid) elif isinstance(dim_sel, slice): - dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len) + dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_grid) elif is_integer_array(dim_sel): - dim_indexer = IntArrayDimIndexer(dim_sel, dim_len, dim_chunk_len) + dim_indexer = IntArrayDimIndexer(dim_sel, dim_len, dim_grid) elif is_bool_array(dim_sel): - dim_indexer = BoolArrayDimIndexer(dim_sel, dim_len, dim_chunk_len) + dim_indexer = BoolArrayDimIndexer(dim_sel, dim_len, dim_grid) else: raise IndexError( @@ -949,8 +954,8 @@ def __init__(self, selection: Selection, shape: tuple[int, ...], chunk_grid: Chu drop_axes = () object.__setattr__(self, "dim_indexers", dim_indexers) + object.__setattr__(self, "dim_grids", dim_grids) object.__setattr__(self, "shape", shape) - object.__setattr__(self, "chunk_shape", chunk_shape) object.__setattr__(self, "is_advanced", is_advanced) object.__setattr__(self, "drop_axes", drop_axes) @@ -966,15 +971,26 @@ def __iter__(self) -> Iterator[ChunkProjection]: # handle advanced indexing arrays orthogonally if self.is_advanced: - # N.B., numpy doesn't support orthogonal indexing directly as yet, - # so need to work around via np.ix_. Also np.ix_ does not support a - # mixture of arrays and slices or integers, so need to convert slices - # and integers into ranges. - chunk_selection = ix_(chunk_selection, self.chunk_shape) + # NumPy can handle a single array-indexed dimension directly, + # which preserves full slices and avoids an + # unnecessary advanced-indexing copy. Integer-indexed + # dimensions still need the ix_ path for downstream squeezing. + # Example: we skip `ix_` for array[:, :, [1, 2, 3]] + n_array_dims = sum(isinstance(sel, np.ndarray) for sel in chunk_selection) + + if n_array_dims > 1 or self.drop_axes: + # N.B., numpy doesn't support orthogonal indexing directly + # for multiple array-indexed dimensions, so we need to + # convert the orthogonal selection into coordinate arrays. + chunk_shape = tuple( + g.chunk_size(p.dim_chunk_ix) + for g, p in zip(self.dim_grids, dim_projections, strict=True) + ) + chunk_selection = ix_(chunk_selection, chunk_shape) - # special case for non-monotonic indices - if not is_basic_selection(out_selection): - out_selection = ix_(out_selection, self.shape) + # special case for non-monotonic indices + if not is_basic_selection(out_selection): + out_selection = ix_(out_selection, self.shape) is_complete_chunk = all(p.is_complete_chunk for p in dim_projections) yield ChunkProjection(chunk_coords, chunk_selection, out_selection, is_complete_chunk) @@ -1009,7 +1025,7 @@ def __setitem__(self, selection: OrthogonalSelection, value: npt.ArrayLike) -> N @dataclass(frozen=True) -class AsyncOIndex(Generic[T_ArrayMetadata]): +class AsyncOIndex[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: array: AsyncArray[T_ArrayMetadata] async def getitem(self, selection: OrthogonalSelection | AnyArray) -> NDArrayLikeOrScalar: @@ -1036,7 +1052,7 @@ class BlockIndexer(Indexer): def __init__( self, selection: BasicSelection, shape: tuple[int, ...], chunk_grid: ChunkGrid ) -> None: - chunk_shape = get_chunk_shape(chunk_grid) + dim_grids = chunk_grid._dimensions # handle ellipsis selection_normalized = replace_ellipsis(selection, shape) @@ -1046,17 +1062,20 @@ def __init__( # setup per-dimension indexers dim_indexers = [] - for dim_sel, dim_len, dim_chunk_size in zip( - selection_normalized, shape, chunk_shape, strict=True - ): - dim_numchunks = int(np.ceil(dim_len / dim_chunk_size)) + for dim_sel, dim_len, dim_grid in zip(selection_normalized, shape, dim_grids, strict=True): + dim_numchunks = dim_grid.nchunks if is_integer(dim_sel): if dim_sel < 0: dim_sel = dim_numchunks + dim_sel - start = dim_sel * dim_chunk_size - stop = start + dim_chunk_size + if dim_sel < 0 or dim_sel >= dim_numchunks: + raise BoundsCheckError( + f"block index out of bounds for dimension with {dim_numchunks} chunk(s)" + ) + + start = dim_grid.chunk_offset(dim_sel) + stop = start + dim_grid.chunk_size(dim_sel) slice_ = slice(start, stop) elif is_slice(dim_sel): @@ -1076,8 +1095,8 @@ def __init__( if stop < 0: stop = dim_numchunks + stop - start *= dim_chunk_size - stop *= dim_chunk_size + start = dim_grid.chunk_offset(start) if start < dim_numchunks else dim_len + stop = dim_grid.chunk_offset(stop) if stop < dim_numchunks else dim_len slice_ = slice(start, stop) else: @@ -1086,10 +1105,10 @@ def __init__( f"expected integer or slice, got {type(dim_sel)!r}" ) - dim_indexer = SliceDimIndexer(slice_, dim_len, dim_chunk_size) + dim_indexer = SliceDimIndexer(slice_, dim_len, dim_grid) dim_indexers.append(dim_indexer) - if start >= dim_len or start < 0: + if slice_.start >= dim_len or slice_.start < 0: msg = f"index out of bounds for dimension with length {dim_len}" raise BoundsCheckError(msg) @@ -1157,25 +1176,25 @@ class CoordinateIndexer(Indexer): chunk_rixs: npt.NDArray[np.intp] chunk_mixs: tuple[npt.NDArray[np.intp], ...] shape: tuple[int, ...] - chunk_shape: tuple[int, ...] + dim_grids: tuple[DimensionGrid, ...] drop_axes: tuple[int, ...] def __init__( self, selection: CoordinateSelection, shape: tuple[int, ...], chunk_grid: ChunkGrid ) -> None: - chunk_shape = get_chunk_shape(chunk_grid) + dim_grids = chunk_grid._dimensions cdata_shape: tuple[int, ...] if shape == (): cdata_shape = (1,) else: - cdata_shape = tuple(math.ceil(s / c) for s, c in zip(shape, chunk_shape, strict=True)) - nchunks = reduce(operator.mul, cdata_shape, 1) + cdata_shape = tuple(g.nchunks for g in dim_grids) + nchunks = math.prod(cdata_shape) # some initial normalization selection_normalized = cast("CoordinateSelectionNormalized", ensure_tuple(selection)) selection_normalized = tuple( - np.asarray([i]) if is_integer(i) else i for i in selection_normalized + np.asarray([i], dtype=np.intp) if is_integer(i) else i for i in selection_normalized ) selection_normalized = cast( "CoordinateSelectionNormalized", replace_lists(selection_normalized) @@ -1189,6 +1208,59 @@ def __init__( f"got {selection!r}" ) + # Optimization for a single sorted, in-bounds, 1-D integer coordinate array over a + # regular (fixed-size) chunk grid. The general path below makes several full passes over + # the flat selection. For sufficiently dense selections, locating the internal chunk + # boundaries with searchsorted is cheaper. + if len(selection_normalized) == 1: + (coords,) = selection_normalized + g0 = dim_grids[0] + # coords is an integer ndarray here: is_coordinate_selection() validated above, and + # the normalization turned ints/lists into arrays. Only the sorted-1D-over-regular-grid + # shape is special-cased; everything else falls through to the general path below. + if ( + isinstance(g0, FixedDimension) + and g0.size > 0 # guard the divide below + and coords.ndim == 1 + and coords.size > 0 + and coords[0] >= 0 + and coords[-1] < shape[0] + and coords[0] <= coords[-1] + ): + size = g0.size + first = int(coords[0]) // size + last = int(coords[-1]) // size + chunk_span = last - first + 1 + # searchsorted does O(log n) work per chunk in the spanned range. Fall through + # when directly processing the coordinates is expected to be cheaper. + if ( + chunk_span * coords.size.bit_length() < coords.size + and bool((coords[:-1] <= coords[1:]).all()) # sorted -> grouped by chunk + ): + # Search only internal boundaries. Derive the first and last counts from the + # selection bounds so that the boundary after the last chunk cannot overflow. + if first == last: + counts = np.array([coords.size], dtype=np.intp) + else: + edges = np.arange(first + 1, last + 1, dtype=coords.dtype) * size + cuts = np.searchsorted(coords, edges) + counts = np.diff(cuts, prepend=0, append=coords.size) + chunk_rixs = (first + np.nonzero(counts)[0]).astype(np.intp) + chunk_nitems = np.zeros(nchunks, dtype=np.intp) + chunk_nitems[first : last + 1] = counts + chunk_nitems_cumsum = np.cumsum(chunk_nitems) + + object.__setattr__(self, "sel_shape", coords.shape) + object.__setattr__(self, "selection", (coords,)) + object.__setattr__(self, "sel_sort", None) + object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) + object.__setattr__(self, "chunk_rixs", chunk_rixs) + object.__setattr__(self, "chunk_mixs", (chunk_rixs,)) + object.__setattr__(self, "dim_grids", dim_grids) + object.__setattr__(self, "shape", coords.shape) + object.__setattr__(self, "drop_axes", ()) + return + # handle wraparound, boundscheck for dim_sel, dim_len in zip(selection_normalized, shape, strict=True): # handle wraparound @@ -1199,8 +1271,8 @@ def __init__( # compute chunk index for each point in the selection chunks_multi_index = tuple( - dim_sel // dim_chunk_len - for (dim_sel, dim_chunk_len) in zip(selection_normalized, chunk_shape, strict=True) + g.indices_to_chunks(dim_sel) + for (dim_sel, g) in zip(selection_normalized, dim_grids, strict=True) ) # broadcast selection - this will raise error if array dimensions don't match @@ -1246,7 +1318,7 @@ def __init__( object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) object.__setattr__(self, "chunk_rixs", chunk_rixs) object.__setattr__(self, "chunk_mixs", chunk_mixs) - object.__setattr__(self, "chunk_shape", chunk_shape) + object.__setattr__(self, "dim_grids", dim_grids) object.__setattr__(self, "shape", shape) object.__setattr__(self, "drop_axes", ()) @@ -1266,8 +1338,8 @@ def __iter__(self) -> Iterator[ChunkProjection]: out_selection = self.sel_sort[start:stop] chunk_offsets = tuple( - dim_chunk_ix * dim_chunk_len - for dim_chunk_ix, dim_chunk_len in zip(chunk_coords, self.chunk_shape, strict=True) + g.chunk_offset(dim_chunk_ix) + for dim_chunk_ix, g in zip(chunk_coords, self.dim_grids, strict=True) ) chunk_selection = tuple( dim_sel[start:stop] - dim_chunk_offset @@ -1349,7 +1421,7 @@ def __setitem__( @dataclass(frozen=True) -class AsyncVIndex(Generic[T_ArrayMetadata]): +class AsyncVIndex[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: array: AsyncArray[T_ArrayMetadata] # TODO: develop Array generic and move zarr.Array[np.intp] | zarr.Array[np.bool_] to ArrayOfIntOrBool @@ -1504,19 +1576,19 @@ def decode_morton_vectorized( @lru_cache(maxsize=16) -def _morton_order(chunk_shape: tuple[int, ...]) -> npt.NDArray[np.intp]: - n_total = product(chunk_shape) - n_dims = len(chunk_shape) +def _morton_order(shape: tuple[int, ...]) -> npt.NDArray[np.intp]: + n_total = product(shape) + n_dims = len(shape) if n_total == 0: out = np.empty((0, n_dims), dtype=np.intp) out.flags.writeable = False return out # Ceiling hypercube: smallest power-of-2 hypercube whose Morton codes span - # all valid coordinates in chunk_shape. (c-1).bit_length() gives the number + # all valid coordinates in shape. (c-1).bit_length() gives the number # of bits needed to index c values (0 for singleton dims). n_z = 2**total_bits # is the size of this hypercube. - total_bits = sum((c - 1).bit_length() for c in chunk_shape) + total_bits = sum((c - 1).bit_length() for c in shape) n_z = 1 << total_bits if total_bits > 0 else 1 # Decode all Morton codes in the ceiling hypercube, then filter to valid coords. @@ -1527,8 +1599,8 @@ def _morton_order(chunk_shape: tuple[int, ...]) -> npt.NDArray[np.intp]: # Ceiling strategy: decode all n_z codes vectorized, filter in-bounds. # Works well when the overgeneration ratio n_z/n_total is small (≤4). z_values = np.arange(n_z, dtype=np.intp) - all_coords = decode_morton_vectorized(z_values, chunk_shape) - shape_arr = np.array(chunk_shape, dtype=np.intp) + all_coords = decode_morton_vectorized(z_values, shape) + shape_arr = np.array(shape, dtype=np.intp) valid_mask = np.all(all_coords < shape_arr, axis=1) order = all_coords[valid_mask] else: @@ -1537,11 +1609,11 @@ def _morton_order(chunk_shape: tuple[int, ...]) -> npt.NDArray[np.intp]: # larger overgeneration penalty for near-miss shapes like (33,33,33). # Cost: O(n_total * bits) encode + O(n_total log n_total) sort, # vs O(n_z * bits) = O(8 * n_total * bits) for ceiling. - grids = np.meshgrid(*[np.arange(c, dtype=np.intp) for c in chunk_shape], indexing="ij") + grids = np.meshgrid(*[np.arange(c, dtype=np.intp) for c in shape], indexing="ij") all_coords = np.stack([g.ravel() for g in grids], axis=1) # Encode all coordinates to Morton codes (vectorized). - bits_per_dim = tuple((c - 1).bit_length() for c in chunk_shape) + bits_per_dim = tuple((c - 1).bit_length() for c in shape) max_coord_bits = max(bits_per_dim) z_codes = np.zeros(n_total, dtype=np.intp) output_bit = 0 @@ -1559,16 +1631,56 @@ def _morton_order(chunk_shape: tuple[int, ...]) -> npt.NDArray[np.intp]: @lru_cache(maxsize=16) -def _morton_order_keys(chunk_shape: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: - return tuple(tuple(int(x) for x in row) for row in _morton_order(chunk_shape)) +def morton_order_coords(shape: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: + # The grid coordinates in Morton (Z) order, as a cached sequence. The + # coordinate set of a finite grid has a known length and is reused in full on + # every shard write, so it is built once (vectorized, via `_morton_order`) and + # cached per shape rather than recomputed. Indexable and `len`-able; iterate it + # directly where an iterator is needed. + # + # `.tolist()` converts the whole array to native Python ints in one C-level + # call; building the tuples row-by-row with `int(x)` is ~9x slower. + return tuple(map(tuple, _morton_order(shape).tolist())) -def morton_order_iter(chunk_shape: tuple[int, ...]) -> Iterator[tuple[int, ...]]: - return iter(_morton_order_keys(tuple(chunk_shape))) +@lru_cache(maxsize=16) +def _lexicographic_order(shape: tuple[int, ...]) -> npt.NDArray[np.intp]: + # Lexicographic (C-order) coordinates, computed vectorized and cached so that + # the sharding codec's per-shard chunk grid is not rebuilt on every call. + # Equivalent to `np.array(list(np.ndindex(shape)))` but without the + # Python-level iteration over every coordinate. + n_dims = len(shape) + if n_dims == 0: + # A 0-d shard holds a single chunk addressed by the empty coordinate, so + # the coordinate array has one row and zero columns. np.indices(()) cannot + # express this, so build it directly. Matches list(np.ndindex(())) == [()]. + order = np.empty((1, 0), dtype=np.intp) + else: + order = np.indices(shape, dtype=np.intp).reshape(n_dims, -1).T + order.flags.writeable = False + return order -def c_order_iter(chunks_per_shard: tuple[int, ...]) -> Iterator[tuple[int, ...]]: - return itertools.product(*(range(x) for x in chunks_per_shard)) +@lru_cache(maxsize=16) +def lexicographic_order_coords(shape: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: + # The grid coordinates in lexicographic (row-major / C) order, as a cached + # sequence. The coordinate set of a finite grid has a known length and is + # reused in full on every shard write, so it is built once (vectorized, via + # `_lexicographic_order`) and cached per shape. Indexable and `len`-able; + # iterate it directly where an iterator is needed. + # + # `.tolist()` converts the whole array to native Python ints in one C-level + # call; building the tuples row-by-row with `int(x)` is ~9x slower. + return tuple(map(tuple, _lexicographic_order(shape).tolist())) + + +@lru_cache(maxsize=16) +def colexicographic_order_coords(shape: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: + # The grid coordinates in colexicographic (column-major / F) order, as a cached + # sequence: the first axis varies fastest. Equivalent to reversing each axis, + # taking lexicographic order, and reversing the coordinates back. Cached per + # shape like its siblings so shard writes don't rebuild it. + return tuple(c[::-1] for c in lexicographic_order_coords(shape[::-1])) def get_indexer( diff --git a/src/zarr/core/json_parse.py b/src/zarr/core/json_parse.py new file mode 100644 index 0000000000..09c5ca074e --- /dev/null +++ b/src/zarr/core/json_parse.py @@ -0,0 +1,103 @@ +"""Helpers for validating JSON-decoded metadata. + +Most JSON metadata validation is delegated to +[`msgspec.convert`][msgspec.convert], which handles the type coercions Zarr +needs (``Literal`` membership, ``int``/``bool`` strictness, list-to-tuple, +``TypedDict`` with ``NotRequired``). ``convert`` is a thin wrapper that +translates [`msgspec.ValidationError`][msgspec.ValidationError] into the +``TypeError`` the rest of the codebase already raises. + +msgspec cannot handle two things in Zarr's metadata types: + +* the recursive ``JSON`` / ``JSONValue`` aliases, which it rejects at + schema-build time, and +* PEP 728 ``extra_items=`` extension fields, which it silently drops. + +``validate_json_value`` is the small hand-written fallback for the first of +those. See https://github.com/zarr-developers/zarr-python/issues/3285. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, Final, cast, get_origin + +import msgspec + +if TYPE_CHECKING: + from zarr.core.common import JSON + +__all__ = ["MAX_JSON_DEPTH", "convert", "parse_field", "validate_json_value"] + +MAX_JSON_DEPTH: Final = 64 +"""Maximum nesting depth accepted by ``validate_json_value``.""" + + +def _type_name(type_: Any) -> str: + """Render ``type_`` for an error message. + + Parameterized types keep their arguments, so a ``Literal`` reports its + members (``Literal[2, 3]``) rather than the bare origin name. ``__name__`` + would drop them, which loses the most useful part of the message. + """ + if get_origin(type_) is not None: + return str(type_).replace("typing.", "") + return getattr(type_, "__name__", None) or str(type_).replace("typing.", "") + + +def convert(value: object, type_: Any, *, strict: bool = True) -> Any: + """Validate and coerce ``value`` against ``type_`` via [`msgspec.convert`][msgspec.convert]. + + On a mismatch msgspec raises + [`msgspec.ValidationError`][msgspec.ValidationError]; this re-raises + a plain, field-agnostic ``ValueError`` naming the expected type, so callers + can add their own field context (see ``parse_field``). + """ + try: + return msgspec.convert(value, type_, strict=strict) + except msgspec.ValidationError as exc: + raise ValueError(f"Expected instance of {_type_name(type_)}, got {value!r}.") from exc + + +def parse_field( + data: object, type_: Any, field: str, *, error: type[Exception] = ValueError +) -> Any: + """Validate ``data`` for metadata field ``field`` against ``type_``. + + Wraps ``convert`` and, on failure, re-raises ``error`` with field + context, chaining the underlying type error. This keeps the + ``convert``-then-re-raise pattern in one place rather than repeating it in + every per-field parser. + """ + try: + return convert(data, type_) + except ValueError as exc: + raise error( + f"Failed to parse input for {field!r}: expected {_type_name(type_)}, got {data!r}." + ) from exc + + +def validate_json_value(value: object, *, max_depth: int = MAX_JSON_DEPTH, _depth: int = 0) -> JSON: + """Check that ``value`` is a JSON value and return it unchanged. + + msgspec cannot build a schema for Zarr's recursive ``JSON`` / ``JSONValue`` + aliases, so this covers the fields typed that way (``attributes``, + ``fill_value``, extension-field values). Unlike the previous per-field + parsers it also enforces ``max_depth``: a pathologically nested document + could otherwise exhaust the interpreter stack. + """ + if _depth > max_depth: + raise ValueError(f"JSON value nesting exceeds the maximum depth of {max_depth}.") + if value is None or isinstance(value, (bool, int, float, str)): + return cast("JSON", value) + if isinstance(value, (list, tuple)): + for item in value: + validate_json_value(item, max_depth=max_depth, _depth=_depth + 1) + return cast("JSON", value) + if isinstance(value, Mapping): + for key, item in value.items(): + if not isinstance(key, str): + raise TypeError(f"JSON object keys must be str, got {type(key).__name__}.") + validate_json_value(item, max_depth=max_depth, _depth=_depth + 1) + return cast("JSON", value) + raise TypeError(f"Value {value!r} is not a valid JSON value.") diff --git a/src/zarr/core/metadata/__init__.py b/src/zarr/core/metadata/__init__.py index 57385386b6..cacfc933b5 100644 --- a/src/zarr/core/metadata/__init__.py +++ b/src/zarr/core/metadata/__init__.py @@ -1,11 +1,8 @@ -from typing import TypeAlias, TypeVar - from .v2 import ArrayV2Metadata, ArrayV2MetadataDict from .v3 import ArrayMetadataJSON_V3, ArrayV3Metadata -ArrayMetadata: TypeAlias = ArrayV2Metadata | ArrayV3Metadata -ArrayMetadataDict: TypeAlias = ArrayV2MetadataDict | ArrayMetadataJSON_V3 -T_ArrayMetadata = TypeVar("T_ArrayMetadata", ArrayV2Metadata, ArrayV3Metadata, covariant=True) +ArrayMetadata = ArrayV2Metadata | ArrayV3Metadata +type ArrayMetadataDict = ArrayV2MetadataDict | ArrayMetadataJSON_V3 __all__ = [ "ArrayMetadata", diff --git a/src/zarr/core/metadata/common.py b/src/zarr/core/metadata/common.py index 44d3eb292b..6367bdb28a 100644 --- a/src/zarr/core/metadata/common.py +++ b/src/zarr/core/metadata/common.py @@ -10,4 +10,4 @@ def parse_attributes(data: dict[str, JSON] | None) -> dict[str, JSON]: if data is None: return {} - return data + return dict(data) diff --git a/src/zarr/core/metadata/v2.py b/src/zarr/core/metadata/v2.py index 3204543426..70d4e1e59c 100644 --- a/src/zarr/core/metadata/v2.py +++ b/src/zarr/core/metadata/v2.py @@ -1,13 +1,13 @@ from __future__ import annotations +import json import warnings from collections.abc import Iterable, Sequence from functools import cached_property -from typing import TYPE_CHECKING, Any, TypeAlias, TypedDict, cast +from typing import TYPE_CHECKING, Any, TypedDict, cast from zarr.abc.metadata import Metadata from zarr.abc.numcodec import Numcodec, _is_numcodec -from zarr.core.chunk_grids import RegularChunkGrid from zarr.core.dtype import get_data_type_from_json from zarr.core.dtype.common import OBJECT_CODEC_IDS, DTypeSpec_V2 from zarr.errors import ZarrUserWarning @@ -19,19 +19,18 @@ import numpy.typing as npt from zarr.core.buffer import Buffer, BufferPrototype + from zarr.core.chunk_grids import ChunkGrid from zarr.core.dtype.wrapper import ( TBaseDType, TBaseScalar, - TDType_co, - TScalar_co, ZDType, ) -import json from dataclasses import dataclass, field, fields, replace import numpy as np +from zarr.core._json import json_to_buffer from zarr.core.array_spec import ArrayConfig, ArraySpec from zarr.core.chunk_key_encodings import parse_separator from zarr.core.common import ( @@ -42,6 +41,7 @@ parse_shapelike, ) from zarr.core.config import config, parse_indexing_order +from zarr.core.json_parse import parse_field from zarr.core.metadata.common import parse_attributes @@ -55,7 +55,7 @@ class ArrayV2MetadataDict(TypedDict): # Union of acceptable types for v2 compressors -CompressorLikev2: TypeAlias = dict[str, JSON] | Numcodec | None +type CompressorLikev2 = dict[str, JSON] | Numcodec | None @dataclass(frozen=True, kw_only=True) @@ -75,7 +75,7 @@ def __init__( self, *, shape: tuple[int, ...], - dtype: ZDType[TDType_co, TScalar_co], + dtype: ZDType[TBaseDType, TBaseScalar], chunks: tuple[int, ...], fill_value: Any, order: MemoryOrder, @@ -118,8 +118,22 @@ def ndim(self) -> int: return len(self.shape) @cached_property - def chunk_grid(self) -> RegularChunkGrid: - return RegularChunkGrid(chunk_shape=self.chunks) + def chunk_grid(self) -> ChunkGrid: + """Backwards-compatible chunk grid property. + + !!! warning "Deprecated" + Access the chunk grid via the array layer instead. + This property will be removed in a future release. + """ + from zarr.core.chunk_grids import ChunkGrid + + warnings.warn( + "ArrayV2Metadata.chunk_grid is deprecated. " + "Use ChunkGrid.from_metadata(metadata) instead.", + DeprecationWarning, + stacklevel=2, + ) + return ChunkGrid.from_sizes(self.shape, tuple(self.chunks)) @property def shards(self) -> tuple[int, ...] | None: @@ -128,14 +142,10 @@ def shards(self) -> tuple[int, ...] | None: def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: zarray_dict = self.to_dict() zattrs_dict = zarray_dict.pop("attributes", {}) - json_indent = config.get("json_indent") + indent = config.get("json_indent") return { - ZARRAY_JSON: prototype.buffer.from_bytes( - json.dumps(zarray_dict, indent=json_indent, allow_nan=True).encode() - ), - ZATTRS_JSON: prototype.buffer.from_bytes( - json.dumps(zattrs_dict, indent=json_indent, allow_nan=True).encode() - ), + ZARRAY_JSON: json_to_buffer(zarray_dict, prototype=prototype, indent=indent), + ZATTRS_JSON: json_to_buffer(zattrs_dict, prototype=prototype, indent=indent), } @classmethod @@ -227,6 +237,19 @@ def to_dict(self) -> dict[str, JSON]: return zarray_dict + def __eq__(self, other: object) -> bool: + # The default dataclass __eq__ compares fields directly, which is wrong for a NaN + # fill_value: NaN != NaN under IEEE 754. Comparing the JSON-serialized form instead + # treats matching NaN (and inf) fill values as equal. See issue #2929. + if not isinstance(other, ArrayV2Metadata): + return NotImplemented + return self.to_dict() == other.to_dict() + + def __hash__(self) -> int: + # Hash the JSON-serialized form to stay consistent with __eq__: equal metadata + # must hash equally, which a field-based hash violates for a NaN fill_value. + return hash(json.dumps(self.to_dict(), sort_keys=True)) + def get_chunk_spec( self, _chunk_coords: tuple[int, ...], array_config: ArrayConfig, prototype: BufferPrototype ) -> ArraySpec: @@ -256,9 +279,9 @@ def parse_dtype(data: npt.DTypeLike) -> np.dtype[Any]: def parse_zarr_format(data: object) -> Literal[2]: - if data == 2: - return 2 - raise ValueError(f"Invalid value. Expected 2. Got {data}.") + from typing import Literal + + return cast("Literal[2]", parse_field(data, Literal[2], "zarr_format")) def parse_filters(data: object) -> tuple[Numcodec, ...] | None: diff --git a/src/zarr/core/metadata/v3.py b/src/zarr/core/metadata/v3.py index 5ce155bd9a..fc47f8fc95 100644 --- a/src/zarr/core/metadata/v3.py +++ b/src/zarr/core/metadata/v3.py @@ -1,30 +1,18 @@ from __future__ import annotations -from collections.abc import Mapping -from typing import TYPE_CHECKING, NotRequired, TypedDict, TypeGuard, cast - -from zarr.abc.metadata import Metadata -from zarr.core.buffer.core import default_buffer_prototype -from zarr.core.dtype import VariableLengthUTF8, ZDType, get_data_type_from_json -from zarr.core.dtype.common import check_dtype_spec_v3 - -if TYPE_CHECKING: - from typing import Self - - from zarr.core.buffer import Buffer, BufferPrototype - from zarr.core.chunk_grids import ChunkGrid - from zarr.core.common import JSON - from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar - - import json -from collections.abc import Iterable +from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace -from typing import Any, Literal +from typing import TYPE_CHECKING, Any, Final, Literal, NotRequired, TypeGuard, cast + +from typing_extensions import TypedDict from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec +from zarr.abc.metadata import Metadata +from zarr.core._json import json_to_buffer from zarr.core.array_spec import ArrayConfig, ArraySpec -from zarr.core.chunk_grids import ChunkGrid, RegularChunkGrid +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.chunk_grids import is_regular_nd from zarr.core.chunk_key_encodings import ( ChunkKeyEncoding, ChunkKeyEncodingLike, @@ -33,29 +21,43 @@ from zarr.core.common import ( JSON, ZARR_JSON, - DimensionNames, + DimensionNamesLike, NamedConfig, + NamedRequiredConfig, + compress_rle, + expand_rle, parse_named_configuration, parse_shapelike, + validate_rectilinear_edges, + validate_rectilinear_kind, ) from zarr.core.config import config +from zarr.core.dtype import VariableLengthUTF8, ZDType, get_data_type_from_json +from zarr.core.dtype.common import check_dtype_spec_v3 +from zarr.core.json_parse import parse_field, validate_json_value from zarr.core.metadata.common import parse_attributes from zarr.errors import MetadataValidationError, NodeTypeValidationError, UnknownCodecError from zarr.registry import get_codec_class +if TYPE_CHECKING: + from typing import Self + + from zarr.core.buffer import Buffer, BufferPrototype + from zarr.core.chunk_grids import ChunksTuple + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar + def parse_zarr_format(data: object) -> Literal[3]: - if data == 3: - return 3 - msg = f"Invalid value for 'zarr_format'. Expected '3'. Got '{data}'." - raise MetadataValidationError(msg) + return cast( + "Literal[3]", parse_field(data, Literal[3], "zarr_format", error=MetadataValidationError) + ) def parse_node_type_array(data: object) -> Literal["array"]: - if data == "array": - return "array" - msg = f"Invalid value for 'node_type'. Expected 'array'. Got '{data}'." - raise NodeTypeValidationError(msg) + return cast( + 'Literal["array"]', + parse_field(data, Literal["array"], "node_type", error=NodeTypeValidationError), + ) def parse_codecs(data: object) -> tuple[Codec, ...]: @@ -128,20 +130,22 @@ def parse_storage_transformers(data: object) -> tuple[dict[str, JSON], ...]: """ if data is None: return () - if isinstance(data, Iterable): - if len(tuple(data)) >= 1: - return data # type: ignore[return-value] - else: - return () + if isinstance(data, Iterable) and not isinstance(data, (str, bytes)): + # Materialise once. The previous implementation called ``len(tuple(data))`` + # and then returned ``data`` itself, which exhausted (and discarded) a + # one-shot iterable and could return a value typed as a tuple that was not + # actually a tuple. + return tuple(data) raise TypeError( f"Invalid storage_transformers. Expected an iterable of dicts. Got {type(data)} instead." ) -class AllowedExtraField(TypedDict): +class AllowedExtraField(TypedDict, extra_items=JSON): # type: ignore[call-arg] """ This class models allowed extra fields in array metadata. - They are ignored by Zarr Python. + They must have ``must_understand`` set to ``False``, and may contain + arbitrary additional JSON data. """ must_understand: Literal[False] @@ -174,32 +178,293 @@ def parse_extra_fields( return dict(data) -class ArrayMetadataJSON_V3(TypedDict): +# JSON type for a single dimension's rectilinear spec: +# bare int (uniform shorthand), or list of ints / [value, count] RLE pairs. +RectilinearDimSpecJSON = int | list[int | list[int]] + + +class RegularChunkGridMetadataConfig(TypedDict): + chunk_shape: Sequence[int] + + +class RectilinearChunkGridMetadataConfig(TypedDict): + kind: Literal["inline"] + chunk_shapes: Sequence[RectilinearDimSpecJSON] + + +RegularChunkGridMetadataJSON = NamedRequiredConfig[ + Literal["regular"], RegularChunkGridMetadataConfig +] +RectilinearChunkGridMetadataJSON = NamedRequiredConfig[ + Literal["rectilinear"], RectilinearChunkGridMetadataConfig +] + + +def _parse_chunk_shape(chunk_shape: Iterable[int]) -> tuple[int, ...]: + """Validate and normalize a regular chunk shape. + + Delegates to ``_validate_chunk_shapes`` — a regular chunk shape is just + a sequence of bare ints (one per dimension), each of which must be >= 1. + """ + result = _validate_chunk_shapes(tuple(chunk_shape)) + # Regular grids only have bare ints — cast is safe after validation + return cast(tuple[int, ...], result) + + +def _validate_chunk_shapes( + chunk_shapes: Sequence[int | Sequence[int]], +) -> tuple[int | tuple[int, ...], ...]: + """Validate per-dimension chunk specifications. + + Each element is either a bare ``int`` (regular step size, must be >= 1) + or a sequence of explicit edge lengths (all must be >= 1, non-empty). """ - A typed dictionary model for zarr v3 metadata. + result: list[int | tuple[int, ...]] = [] + for dim_idx, dim_spec in enumerate(chunk_shapes): + if isinstance(dim_spec, int): + if dim_spec < 1: + raise ValueError( + f"Dimension {dim_idx}: integer chunk edge length must be >= 1, got {dim_spec}" + ) + result.append(dim_spec) + else: + edges = tuple(dim_spec) + if not edges: + raise ValueError(f"Dimension {dim_idx} has no chunk edges.") + bad = [i for i, e in enumerate(edges) if e < 1] + if bad: + raise ValueError( + f"Dimension {dim_idx} has invalid edge lengths at indices {bad}: " + f"{[edges[i] for i in bad]}" + ) + result.append(edges) + return tuple(result) + + +@dataclass(frozen=True, kw_only=True) +class RegularChunkGridMetadata(Metadata): + """Metadata-only description of a regular chunk grid. + + Stores just the chunk shape — no array extent, no runtime logic. + This is what lives on ``ArrayV3Metadata.chunk_grid``. + """ + + chunk_shape: tuple[int, ...] + + def __post_init__(self) -> None: + chunk_shape_parsed = _parse_chunk_shape(self.chunk_shape) + object.__setattr__(self, "chunk_shape", chunk_shape_parsed) + + @property + def ndim(self) -> int: + return len(self.chunk_shape) + + def to_dict(self) -> RegularChunkGridMetadataJSON: # type: ignore[override] + return { + "name": "regular", + "configuration": {"chunk_shape": self.chunk_shape}, + } + + @classmethod + def from_dict(cls, data: RegularChunkGridMetadataJSON) -> Self: # type: ignore[override] + parse_named_configuration(data, "regular") # validate name + configuration = data["configuration"] + return cls(chunk_shape=_parse_chunk_shape(configuration["chunk_shape"])) + + +@dataclass(frozen=True, kw_only=True) +class RectilinearChunkGridMetadata(Metadata): + """Metadata-only description of a rectilinear chunk grid. + + Each element of ``chunk_shapes`` is either: + + - A bare ``int`` — a regular step size that repeats to cover the axis + (the spec's single-integer shorthand). + - A ``tuple[int, ...]`` — explicit per-chunk edge lengths (already + expanded from any RLE encoding). + + This distinction matters for faithful round-tripping: a bare int + serializes back as a bare int, while a single-element tuple serializes + as a list. + """ + + chunk_shapes: tuple[int | tuple[int, ...], ...] + + def __post_init__(self) -> None: + if not config.get("array.rectilinear_chunks"): + raise ValueError( + "Rectilinear chunk grids are experimental and disabled by default. " + "Enable them with: zarr.config.set({'array.rectilinear_chunks': True}) " + "or set the environment variable ZARR_ARRAY__RECTILINEAR_CHUNKS=True" + ) + object.__setattr__(self, "chunk_shapes", _validate_chunk_shapes(self.chunk_shapes)) + + @property + def ndim(self) -> int: + return len(self.chunk_shapes) + + def to_dict(self) -> RectilinearChunkGridMetadataJSON: # type: ignore[override] + serialized_dims: list[RectilinearDimSpecJSON] = [] + for dim_spec in self.chunk_shapes: + if isinstance(dim_spec, int): + # Bare int shorthand — serialize as-is + serialized_dims.append(dim_spec) + else: + rle = compress_rle(dim_spec) + # Use RLE only if it's actually shorter + if len(rle) < len(dim_spec): + serialized_dims.append(rle) + else: + serialized_dims.append(list(dim_spec)) + return { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": tuple(serialized_dims), + }, + } + + def update_shape( + self, old_shape: tuple[int, ...], new_shape: tuple[int, ...] + ) -> RectilinearChunkGridMetadata: + """Return a new RectilinearChunkGridMetadata with edges adjusted for *new_shape*. + + - Bare-int dimensions stay as bare ints (they cover any extent). + - Explicit-edge dimensions: if the new extent exceeds the sum of + edges, a new chunk is appended to cover the additional extent. + Otherwise edges are kept as-is (the spec allows trailing edges + beyond the array extent). + """ + new_chunk_shapes: list[int | tuple[int, ...]] = [] + for dim_spec, new_ext in zip(self.chunk_shapes, new_shape, strict=True): + if isinstance(dim_spec, int): + # Bare int covers any extent — no change needed + new_chunk_shapes.append(dim_spec) + else: + edge_sum = sum(dim_spec) + if new_ext > edge_sum: + new_chunk_shapes.append((*dim_spec, new_ext - edge_sum)) + else: + new_chunk_shapes.append(dim_spec) + return RectilinearChunkGridMetadata(chunk_shapes=tuple(new_chunk_shapes)) + + @classmethod + def from_dict(cls, data: RectilinearChunkGridMetadataJSON) -> Self: # type: ignore[override] + parse_named_configuration(data, "rectilinear") # validate name + configuration = data["configuration"] + validate_rectilinear_kind(configuration.get("kind")) + raw_shapes = configuration["chunk_shapes"] + parsed: list[int | tuple[int, ...]] = [] + for dim_spec in raw_shapes: + if isinstance(dim_spec, int): + if dim_spec < 1: + raise ValueError(f"Integer chunk edge length must be >= 1, got {dim_spec}") + parsed.append(dim_spec) + elif isinstance(dim_spec, list): + parsed.append(tuple(expand_rle(dim_spec))) + else: + raise TypeError( + f"Invalid chunk_shapes entry: expected int or list, got {type(dim_spec)}" + ) + return cls(chunk_shapes=tuple(parsed)) + + +ChunkGridMetadata = RegularChunkGridMetadata | RectilinearChunkGridMetadata + + +def create_chunk_grid_metadata( + chunks: ChunksTuple, +) -> ChunkGridMetadata: + """Construct a chunk grid metadata object from a normalized `ChunksTuple`. + + Regular chunks produce a `RegularChunkGridMetadata`. + Rectilinear chunks produce a `RectilinearChunkGridMetadata`. + + Parameters + ---------- + chunks : ChunksTuple + Normalized chunk specification, as returned by + `normalize_chunks_nd` or `guess_chunks`. + + See Also + -------- + parse_chunk_grid : Deserialize a chunk grid from stored JSON metadata. + """ + if is_regular_nd(chunks): + # If we know the chunks specification is regular, then we can take the first + # chunk size for each dimension as the chunk shape. + chunk_shape = tuple(int(dim_chunks[0]) for dim_chunks in chunks) + return RegularChunkGridMetadata(chunk_shape=chunk_shape) + else: + return RectilinearChunkGridMetadata( + chunk_shapes=tuple(tuple(int(x) for x in d) for d in chunks) + ) + + +def parse_chunk_grid( + data: dict[str, JSON] | ChunkGridMetadata | NamedConfig[str, Any], +) -> ChunkGridMetadata: + """Deserialize a chunk grid from stored JSON metadata or pass through an existing instance. + + See Also + -------- + create_chunk_grid_metadata : Construct a chunk grid from user-facing input. + """ + if isinstance(data, (RegularChunkGridMetadata, RectilinearChunkGridMetadata)): + return data + + name, _ = parse_named_configuration(data) + if name == "regular": + return RegularChunkGridMetadata.from_dict(data) # type: ignore[arg-type] + if name == "rectilinear": + return RectilinearChunkGridMetadata.from_dict(data) # type: ignore[arg-type] + raise ValueError(f"Unknown chunk grid name: {name!r}") + + +class ArrayMetadataJSON_V3(TypedDict, extra_items=AllowedExtraField): # type: ignore[call-arg] + """ + A typed dictionary model for zarr v3 array metadata. + + Extra keys are permitted if they conform to ``AllowedExtraField`` + (i.e. they are mappings with ``must_understand: false``). """ zarr_format: Literal[3] node_type: Literal["array"] - data_type: str | NamedConfig[str, Mapping[str, object]] + data_type: str | NamedConfig[str, Mapping[str, JSON]] shape: tuple[int, ...] - chunk_grid: NamedConfig[str, Mapping[str, object]] - chunk_key_encoding: NamedConfig[str, Mapping[str, object]] - fill_value: object - codecs: tuple[str | NamedConfig[str, Mapping[str, object]], ...] + chunk_grid: str | NamedConfig[str, Mapping[str, JSON]] + chunk_key_encoding: str | NamedConfig[str, Mapping[str, JSON]] + fill_value: JSON + codecs: tuple[str | NamedConfig[str, Mapping[str, JSON]], ...] attributes: NotRequired[Mapping[str, JSON]] - storage_transformers: NotRequired[tuple[NamedConfig[str, Mapping[str, object]], ...]] - dimension_names: NotRequired[tuple[str | None]] - - -ARRAY_METADATA_KEYS = set(ArrayMetadataJSON_V3.__annotations__.keys()) + storage_transformers: NotRequired[tuple[str | NamedConfig[str, Mapping[str, JSON]], ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +""" +The names of the fields of the array metadata document defined in the zarr V3 spec. +""" +ARRAY_METADATA_KEYS: Final[set[str]] = { + "zarr_format", + "node_type", + "data_type", + "shape", + "chunk_grid", + "chunk_key_encoding", + "fill_value", + "codecs", + "attributes", + "storage_transformers", + "dimension_names", +} @dataclass(frozen=True, kw_only=True) class ArrayV3Metadata(Metadata): shape: tuple[int, ...] data_type: ZDType[TBaseDType, TBaseScalar] - chunk_grid: ChunkGrid + chunk_grid: ChunkGridMetadata chunk_key_encoding: ChunkKeyEncoding fill_value: Any codecs: tuple[Codec, ...] @@ -215,12 +480,12 @@ def __init__( *, shape: Iterable[int], data_type: ZDType[TBaseDType, TBaseScalar], - chunk_grid: dict[str, JSON] | ChunkGrid | NamedConfig[str, Any], + chunk_grid: dict[str, JSON] | ChunkGridMetadata | NamedConfig[str, Any], chunk_key_encoding: ChunkKeyEncodingLike, fill_value: object, codecs: Iterable[Codec | dict[str, JSON] | NamedConfig[str, Any] | str], attributes: dict[str, JSON] | None, - dimension_names: DimensionNames, + dimension_names: DimensionNamesLike, storage_transformers: Iterable[dict[str, JSON]] | None = None, extra_fields: Mapping[str, AllowedExtraField] | None = None, ) -> None: @@ -229,7 +494,7 @@ def __init__( """ shape_parsed = parse_shapelike(shape) - chunk_grid_parsed = ChunkGrid.from_dict(chunk_grid) + chunk_grid_parsed = parse_chunk_grid(chunk_grid) chunk_key_encoding_parsed = parse_chunk_key_encoding(chunk_key_encoding) dimension_names_parsed = parse_dimension_names(dimension_names) # Note: relying on a type method is numpy-specific @@ -245,7 +510,21 @@ def __init__( config=ArrayConfig.from_dict({}), # TODO: config is not needed here. prototype=default_buffer_prototype(), # TODO: prototype is not needed here. ) - codecs_parsed = tuple(c.evolve_from_array_spec(array_spec) for c in codecs_parsed_partial) + # Thread the spec through evolution: each codec must be evolved against + # the spec it will actually see at run-time, not the original array spec. + # Earlier array->array codecs may transform the dtype (e.g. cast_value), + # so the spec passed to later codecs must reflect those transformations. + # Per-codec validate() must run before resolve_metadata(), since the + # latter may rely on invariants the former checks (e.g. cast_value + # rejects complex source dtypes that would otherwise crash _do_cast). + evolved: list[Codec] = [] + spec = array_spec + for c in codecs_parsed_partial: + evolved_codec = c.evolve_from_array_spec(spec) + evolved_codec.validate(shape=spec.shape, dtype=spec.dtype, chunk_grid=chunk_grid_parsed) + evolved.append(evolved_codec) + spec = evolved_codec.resolve_metadata(spec) + codecs_parsed = tuple(evolved) validate_codecs(codecs_parsed_partial, data_type) object.__setattr__(self, "shape", shape_parsed) @@ -262,12 +541,10 @@ def __init__( self._validate_metadata() def _validate_metadata(self) -> None: - if isinstance(self.chunk_grid, RegularChunkGrid) and len(self.shape) != len( - self.chunk_grid.chunk_shape - ): - raise ValueError( - "`chunk_shape` and `shape` need to have the same number of dimensions." - ) + if len(self.shape) != self.chunk_grid.ndim: + raise ValueError("`chunk_grid` and `shape` need to have the same number of dimensions.") + if isinstance(self.chunk_grid, RectilinearChunkGridMetadata): + validate_rectilinear_edges(self.chunk_grid.chunk_shapes, self.shape) if self.dimension_names is not None and len(self.shape) != len(self.dimension_names): raise ValueError( "`dimension_names` and `shape` need to have the same number of dimensions." @@ -285,74 +562,52 @@ def ndim(self) -> int: def dtype(self) -> ZDType[TBaseDType, TBaseScalar]: return self.data_type + # TODO: move these properties to the Array class. + # They require knowledge of codecs (ShardingCodec) and don't belong on a metadata DTO. + @property def chunks(self) -> tuple[int, ...]: - if isinstance(self.chunk_grid, RegularChunkGrid): - from zarr.codecs.sharding import ShardingCodec + if not isinstance(self.chunk_grid, RegularChunkGridMetadata): + msg = ( + "The `chunks` attribute is only defined for arrays using regular chunk grids. " + "This array has a rectilinear chunk grid. Use `read_chunk_sizes` for general access." + ) + raise NotImplementedError(msg) - if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): - sharding_codec = self.codecs[0] - assert isinstance(sharding_codec, ShardingCodec) # for mypy - return sharding_codec.chunk_shape - else: - return self.chunk_grid.chunk_shape + from zarr.codecs.sharding import ShardingCodec - msg = ( - f"The `chunks` attribute is only defined for arrays using `RegularChunkGrid`." - f"This array has a {self.chunk_grid} instead." - ) - raise NotImplementedError(msg) + if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): + return self.codecs[0].chunk_shape + return self.chunk_grid.chunk_shape @property def shards(self) -> tuple[int, ...] | None: - if isinstance(self.chunk_grid, RegularChunkGrid): - from zarr.codecs.sharding import ShardingCodec - - if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): - return self.chunk_grid.chunk_shape - else: - return None - - msg = ( - f"The `shards` attribute is only defined for arrays using `RegularChunkGrid`." - f"This array has a {self.chunk_grid} instead." - ) - raise NotImplementedError(msg) + from zarr.codecs.sharding import ShardingCodec + + if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): + if not isinstance(self.chunk_grid, RegularChunkGridMetadata): + msg = ( + "The `shards` attribute is only defined for arrays using regular chunk grids. " + "This array has a rectilinear chunk grid. Use `write_chunk_sizes` for general access." + ) + raise NotImplementedError(msg) + return self.chunk_grid.chunk_shape + return None @property def inner_codecs(self) -> tuple[Codec, ...]: - if isinstance(self.chunk_grid, RegularChunkGrid): - from zarr.codecs.sharding import ShardingCodec + from zarr.codecs.sharding import ShardingCodec - if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): - return self.codecs[0].codecs + if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): + return self.codecs[0].codecs return self.codecs - def get_chunk_spec( - self, _chunk_coords: tuple[int, ...], array_config: ArrayConfig, prototype: BufferPrototype - ) -> ArraySpec: - assert isinstance(self.chunk_grid, RegularChunkGrid), ( - "Currently, only regular chunk grid is supported" - ) - return ArraySpec( - shape=self.chunk_grid.chunk_shape, - dtype=self.dtype, - fill_value=self.fill_value, - config=array_config, - prototype=prototype, - ) - def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: return self.chunk_key_encoding.encode_chunk_key(chunk_coords) def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: - json_indent = config.get("json_indent") - d = self.to_dict() - return { - ZARR_JSON: prototype.buffer.from_bytes( - json.dumps(d, allow_nan=True, indent=json_indent).encode() - ) - } + indent = config.get("json_indent") + return {ZARR_JSON: json_to_buffer(self.to_dict(), prototype=prototype, indent=indent)} @classmethod def from_dict(cls, data: dict[str, JSON]) -> Self: @@ -399,10 +654,10 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: return cls( shape=_data_typed["shape"], - chunk_grid=_data_typed["chunk_grid"], - chunk_key_encoding=_data_typed["chunk_key_encoding"], + chunk_grid=_data_typed["chunk_grid"], # type: ignore[arg-type] + chunk_key_encoding=_data_typed["chunk_key_encoding"], # type: ignore[arg-type] codecs=_data_typed["codecs"], - attributes=_data_typed.get("attributes", {}), # type: ignore[arg-type] + attributes=validate_json_value(_data_typed.get("attributes", {})), # type: ignore[arg-type] dimension_names=_data_typed.get("dimension_names", None), fill_value=fill_value_parsed, data_type=data_type, @@ -415,6 +670,8 @@ def to_dict(self) -> dict[str, JSON]: extra_fields = out_dict.pop("extra_fields") out_dict = out_dict | extra_fields # type: ignore[operator] + out_dict["chunk_grid"] = self.chunk_grid.to_dict() + out_dict["fill_value"] = self.data_type.to_json_scalar( self.fill_value, zarr_format=self.zarr_format ) @@ -435,8 +692,24 @@ def to_dict(self) -> dict[str, JSON]: out_dict["data_type"] = dtype_meta.to_json(zarr_format=3) # type: ignore[unreachable] return out_dict + def __eq__(self, other: object) -> bool: + # The default dataclass __eq__ compares fields directly, which is wrong for a NaN + # fill_value: NaN != NaN under IEEE 754. Comparing the JSON-serialized form instead + # treats matching NaN (and inf) fill values as equal. See issue #2929. + if not isinstance(other, ArrayV3Metadata): + return NotImplemented + return self.to_dict() == other.to_dict() + + def __hash__(self) -> int: + # Hash the JSON-serialized form to stay consistent with __eq__: equal metadata + # must hash equally, which a field-based hash violates for a NaN fill_value. + return hash(json.dumps(self.to_dict(), sort_keys=True)) + def update_shape(self, shape: tuple[int, ...]) -> Self: - return replace(self, shape=shape) + chunk_grid = self.chunk_grid + if isinstance(chunk_grid, RectilinearChunkGridMetadata): + chunk_grid = chunk_grid.update_shape(self.shape, shape) + return replace(self, shape=shape, chunk_grid=chunk_grid) def update_attributes(self, attributes: dict[str, JSON]) -> Self: return replace(self, attributes=attributes) diff --git a/src/zarr/core/sync.py b/src/zarr/core/sync.py index fe435cc2b8..724b31a464 100644 --- a/src/zarr/core/sync.py +++ b/src/zarr/core/sync.py @@ -6,9 +6,7 @@ import os import threading from concurrent.futures import ThreadPoolExecutor, wait -from typing import TYPE_CHECKING, TypeVar - -from typing_extensions import ParamSpec +from typing import TYPE_CHECKING from zarr.core.config import config @@ -19,9 +17,6 @@ logger = logging.getLogger(__name__) -P = ParamSpec("P") -T = TypeVar("T") - # From https://github.com/fsspec/filesystem_spec/blob/master/fsspec/asyn.py iothread: list[threading.Thread | None] = [None] # dedicated IO thread @@ -95,7 +90,9 @@ def reset_resources_after_fork() -> None: Ensure that global resources are reset after a fork. Without this function, forked processes will retain invalid references to the parent process's resources. """ - global loop, iothread, _executor + # `loop` and `iothread` are mutated in place rather than rebound, so only + # `_executor` needs the global declaration. + global _executor # These lines are excluded from coverage because this function only runs in a child process, # which is not observed by the test coverage instrumentation. Despite the apparent lack of # test coverage, this function should be adequately tested by any test that uses Zarr IO with @@ -110,18 +107,18 @@ def reset_resources_after_fork() -> None: os.register_at_fork(after_in_child=reset_resources_after_fork) -async def _runner(coro: Coroutine[Any, Any, T]) -> T | BaseException: +async def _runner[T](coro: Coroutine[Any, Any, T]) -> T | BaseException: """ Await a coroutine and return the result of running it. If awaiting the coroutine raises an exception, the exception will be returned. """ try: return await coro - except Exception as ex: + except Exception as ex: # noqa: BLE001 -- the caller re-raises the returned exception return ex -def sync( +def sync[T]( coro: Coroutine[Any, Any, T], loop: asyncio.AbstractEventLoop | None = None, timeout: float | None = None, @@ -182,7 +179,7 @@ def _get_loop() -> asyncio.AbstractEventLoop: return loop[0] -async def _collect_aiterator(data: AsyncIterator[T]) -> tuple[T, ...]: +async def _collect_aiterator[T](data: AsyncIterator[T]) -> tuple[T, ...]: """ Collect an entire async iterator into a tuple """ @@ -190,7 +187,7 @@ async def _collect_aiterator(data: AsyncIterator[T]) -> tuple[T, ...]: return tuple(result) -def collect_aiterator(data: AsyncIterator[T]) -> tuple[T, ...]: +def collect_aiterator[T](data: AsyncIterator[T]) -> tuple[T, ...]: """ Synchronously collect an entire async iterator into a tuple. """ @@ -198,22 +195,22 @@ def collect_aiterator(data: AsyncIterator[T]) -> tuple[T, ...]: class SyncMixin: - def _sync(self, coroutine: Coroutine[Any, Any, T]) -> T: - # TODO: refactor this to to take *args and **kwargs and pass those to the method + def _sync[T](self, coroutine: Coroutine[Any, Any, T]) -> T: + # TODO: refactor this to take *args and **kwargs and pass those to the method # this should allow us to better type the sync wrapper return sync( coroutine, timeout=config.get("async.timeout"), ) - def _sync_iter(self, async_iterator: AsyncIterator[T]) -> list[T]: + def _sync_iter[T](self, async_iterator: AsyncIterator[T]) -> list[T]: async def iter_to_list() -> list[T]: return [item async for item in async_iterator] return self._sync(iter_to_list()) -async def _with_semaphore( +async def _with_semaphore[T]( func: Callable[[], Awaitable[T]], semaphore: asyncio.Semaphore | None = None ) -> T: """ diff --git a/src/zarr/creation.py b/src/zarr/creation.py deleted file mode 100644 index 605b5af5de..0000000000 --- a/src/zarr/creation.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -Helpers for creating arrays. - -!!! warning "Deprecated" - This sub-module is deprecated. All functions here are defined in the top level zarr namespace instead. - -""" - -import warnings - -from zarr.api.synchronous import ( - array, - create, - empty, - empty_like, - full, - full_like, - ones, - ones_like, - open_array, - open_like, - zeros, - zeros_like, -) -from zarr.errors import ZarrDeprecationWarning - -__all__ = [ - "array", - "create", - "empty", - "empty_like", - "full", - "full_like", - "ones", - "ones_like", - "open_array", - "open_like", - "zeros", - "zeros_like", -] - -warnings.warn( - "zarr.creation is deprecated. " - "Import these functions from the top level zarr. namespace instead.", - ZarrDeprecationWarning, - stacklevel=2, -) diff --git a/src/zarr/dtype.py b/src/zarr/dtype.py index 2c7eb651b0..0c271b6c90 100644 --- a/src/zarr/dtype.py +++ b/src/zarr/dtype.py @@ -2,7 +2,6 @@ Bool, Complex64, Complex128, - DataTypeValidationError, DateTime64, DateTime64JSON_V2, DateTime64JSON_V3, @@ -22,6 +21,8 @@ RawBytes, RawBytesJSON_V2, RawBytesJSON_V3, + Struct, + StructJSON_V3, Structured, StructuredJSON_V2, StructuredJSON_V3, @@ -43,12 +44,13 @@ parse_data_type, # noqa: F401 parse_dtype, ) +from zarr.core.dtype.common import DTypeSpec_V2, check_dtype_spec_v2 __all__ = [ "Bool", "Complex64", "Complex128", - "DataTypeValidationError", + "DTypeSpec_V2", "DateTime64", "DateTime64JSON_V2", "DateTime64JSON_V3", @@ -68,6 +70,8 @@ "RawBytes", "RawBytesJSON_V2", "RawBytesJSON_V3", + "Struct", + "StructJSON_V3", "Structured", "StructuredJSON_V2", "StructuredJSON_V3", @@ -83,6 +87,23 @@ "VariableLengthUTF8", "VariableLengthUTF8JSON_V2", "ZDType", + "check_dtype_spec_v2", "data_type_registry", "parse_dtype", ] + + +def __getattr__(name: str) -> object: + if name == "DataTypeValidationError": + import warnings + + from zarr.errors import DataTypeValidationError, ZarrDeprecationWarning + + warnings.warn( + "Importing DataTypeValidationError from zarr.dtype is deprecated. " + "Use zarr.errors.DataTypeValidationError instead.", + ZarrDeprecationWarning, + stacklevel=2, + ) + return DataTypeValidationError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/zarr/errors.py b/src/zarr/errors.py index bcd6a08deb..781bebe534 100644 --- a/src/zarr/errors.py +++ b/src/zarr/errors.py @@ -3,9 +3,11 @@ "ArrayNotFoundError", "BaseZarrError", "BoundsCheckError", + "ChunkNotFoundError", "ContainsArrayAndGroupError", "ContainsArrayError", "ContainsGroupError", + "DataTypeValidationError", "GroupNotFoundError", "MetadataValidationError", "NegativeStepError", @@ -83,6 +85,9 @@ class ContainsArrayAndGroupError(BaseZarrError): ) +class DataTypeValidationError(ValueError): ... + + class MetadataValidationError(BaseZarrError): """Raised when the Zarr metadata is invalid in some way""" @@ -144,3 +149,9 @@ class BoundsCheckError(IndexError): ... class ArrayIndexError(IndexError): ... + + +class ChunkNotFoundError(BaseZarrError): + """ + Raised when a chunk that was expected to exist in storage was not retrieved successfully. + """ diff --git a/src/zarr/experimental/__init__.py b/src/zarr/experimental/__init__.py index 3863510c65..f7caaf96a1 100644 --- a/src/zarr/experimental/__init__.py +++ b/src/zarr/experimental/__init__.py @@ -1 +1,5 @@ """The experimental module is a site for exporting new or experimental Zarr features.""" + +from zarr.core.chunk_grids import ChunkGrid, ChunkSpec + +__all__ = ["ChunkGrid", "ChunkSpec"] diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 1535b42f67..20cb4d4c0f 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -52,10 +52,11 @@ class CacheStore(WrapperStore[Store]): store : Store The underlying store to wrap with caching cache_store : Store - The store to use for caching (can be any Store implementation) - max_age_seconds : int | None, optional - Maximum age of cached entries in seconds. None means no expiration. - Default is None. + The store to use for caching (can be any Store implementation that + supports deletes) + max_age_seconds : int or "infinity", optional + Maximum age of cached entries in seconds. The string "infinity" means + entries never expire. Default is "infinity". max_size : int | None, optional Maximum size of the cache in bytes. When exceeded, least recently used items are evicted. None means unlimited size. Default is None. @@ -328,6 +329,16 @@ async def _get_no_cache( await self._cache_miss(key, byte_range, result) return result + @property + def _supports_sync_io(self) -> bool: + # The caching logic lives only in the async get/set/delete overrides; + # the sync methods inherited from `WrapperStore` delegate straight to + # the source store, so a sync-capable consumer (the fused codec + # pipeline) would write and delete around the cache, leaving stale + # entries that later async reads serve as current data. Opt out of + # sync IO until the sync surface is cache-aware. + return False + async def get( self, key: str, diff --git a/src/zarr/metadata/migrate_v3.py b/src/zarr/metadata/migrate_v3.py index a72939100d..370af75a6d 100644 --- a/src/zarr/metadata/migrate_v3.py +++ b/src/zarr/metadata/migrate_v3.py @@ -27,7 +27,7 @@ from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType from zarr.core.group import GroupMetadata from zarr.core.metadata.v2 import ArrayV2Metadata -from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGridMetadata from zarr.core.sync import sync from zarr.registry import get_codec_class from zarr.storage import StorePath @@ -211,7 +211,7 @@ def _convert_array_metadata(metadata_v2: ArrayV2Metadata) -> ArrayV3Metadata: return ArrayV3Metadata( shape=metadata_v2.shape, data_type=metadata_v2.dtype, - chunk_grid=metadata_v2.chunk_grid, + chunk_grid=RegularChunkGridMetadata(chunk_shape=metadata_v2.chunks), chunk_key_encoding=chunk_key_encoding, fill_value=metadata_v2.fill_value, codecs=codecs, diff --git a/src/zarr/registry.py b/src/zarr/registry.py index d0850a1387..c2c0eb2921 100644 --- a/src/zarr/registry.py +++ b/src/zarr/registry.py @@ -3,7 +3,7 @@ import warnings from collections import defaultdict from importlib.metadata import entry_points as get_entry_points -from typing import TYPE_CHECKING, Any, Generic, TypeVar +from typing import TYPE_CHECKING, Any from zarr.core.config import BadConfigError, config from zarr.core.dtype import data_type_registry @@ -39,10 +39,8 @@ "register_pipeline", ] -T = TypeVar("T") - -class Registry(dict[str, type[T]], Generic[T]): +class Registry[T](dict[str, type[T]]): def __init__(self) -> None: super().__init__() self.lazy_load_list: list[EntryPoint] = [] @@ -59,11 +57,11 @@ def register(self, cls: type[T], qualname: str | None = None) -> None: self[qualname] = cls -__codec_registries: dict[str, Registry[Codec]] = defaultdict(Registry) -__pipeline_registry: Registry[CodecPipeline] = Registry() -__buffer_registry: Registry[Buffer] = Registry() -__ndbuffer_registry: Registry[NDBuffer] = Registry() -__chunk_key_encoding_registry: Registry[ChunkKeyEncoding] = Registry() +_codec_registries: dict[str, Registry[Codec]] = defaultdict(Registry) +_pipeline_registry: Registry[CodecPipeline] = Registry() +_buffer_registry: Registry[Buffer] = Registry() +_ndbuffer_registry: Registry[NDBuffer] = Registry() +_chunk_key_encoding_registry: Registry[ChunkKeyEncoding] = Registry() """ The registry module is responsible for managing implementations of codecs, @@ -95,37 +93,37 @@ def _collect_entrypoints() -> list[Registry[Any]]: """ entry_points = get_entry_points() - __buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.buffer")) - __buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="buffer")) - __ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.ndbuffer")) - __ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="ndbuffer")) + _buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.buffer")) + _buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="buffer")) + _ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.ndbuffer")) + _ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="ndbuffer")) data_type_registry._lazy_load_list.extend(entry_points.select(group="zarr.data_type")) data_type_registry._lazy_load_list.extend(entry_points.select(group="zarr", name="data_type")) - __chunk_key_encoding_registry.lazy_load_list.extend( + _chunk_key_encoding_registry.lazy_load_list.extend( entry_points.select(group="zarr.chunk_key_encoding") ) - __chunk_key_encoding_registry.lazy_load_list.extend( + _chunk_key_encoding_registry.lazy_load_list.extend( entry_points.select(group="zarr", name="chunk_key_encoding") ) - __pipeline_registry.lazy_load_list.extend(entry_points.select(group="zarr.codec_pipeline")) - __pipeline_registry.lazy_load_list.extend( + _pipeline_registry.lazy_load_list.extend(entry_points.select(group="zarr.codec_pipeline")) + _pipeline_registry.lazy_load_list.extend( entry_points.select(group="zarr", name="codec_pipeline") ) for e in entry_points.select(group="zarr.codecs"): - __codec_registries[e.name].lazy_load_list.append(e) + _codec_registries[e.name].lazy_load_list.append(e) for group in entry_points.groups: if group.startswith("zarr.codecs."): codec_name = group.split(".")[2] - __codec_registries[codec_name].lazy_load_list.extend(entry_points.select(group=group)) + _codec_registries[codec_name].lazy_load_list.extend(entry_points.select(group=group)) return [ - *__codec_registries.values(), - __pipeline_registry, - __buffer_registry, - __ndbuffer_registry, - __chunk_key_encoding_registry, + *_codec_registries.values(), + _pipeline_registry, + _buffer_registry, + _ndbuffer_registry, + _chunk_key_encoding_registry, ] @@ -135,40 +133,40 @@ def _reload_config() -> None: def fully_qualified_name(cls: type) -> str: module = cls.__module__ - return module + "." + cls.__qualname__ + return f"{module}.{cls.__qualname__}" def register_codec(key: str, codec_cls: type[Codec], *, qualname: str | None = None) -> None: - if key not in __codec_registries: - __codec_registries[key] = Registry() - __codec_registries[key].register(codec_cls, qualname=qualname) + if key not in _codec_registries: + _codec_registries[key] = Registry() + _codec_registries[key].register(codec_cls, qualname=qualname) def register_pipeline(pipe_cls: type[CodecPipeline]) -> None: - __pipeline_registry.register(pipe_cls) + _pipeline_registry.register(pipe_cls) def register_ndbuffer(cls: type[NDBuffer], qualname: str | None = None) -> None: - __ndbuffer_registry.register(cls, qualname) + _ndbuffer_registry.register(cls, qualname) def register_buffer(cls: type[Buffer], qualname: str | None = None) -> None: - __buffer_registry.register(cls, qualname) + _buffer_registry.register(cls, qualname) def register_chunk_key_encoding(key: str, cls: type) -> None: - __chunk_key_encoding_registry.register(cls, key) + _chunk_key_encoding_registry.register(cls, key) def get_codec_class(key: str, reload_config: bool = False) -> type[Codec]: if reload_config: _reload_config() - if key in __codec_registries: + if key in _codec_registries: # logger.debug("Auto loading codec '%s' from entrypoint", codec_id) - __codec_registries[key].lazy_load() + _codec_registries[key].lazy_load() - codec_classes = __codec_registries[key] + codec_classes = _codec_registries[key] if not codec_classes: raise KeyError(key) config_entry = config.get("codecs", {}).get(key) @@ -198,9 +196,9 @@ def _resolve_codec(data: dict[str, JSON]) -> Codec: def _parse_bytes_bytes_codec(data: dict[str, JSON] | Codec) -> BytesBytesCodec: """ - Normalize the input to a ``BytesBytesCodec`` instance. - If the input is already a ``BytesBytesCodec``, it is returned as is. If the input is a dict, it - is converted to a ``BytesBytesCodec`` instance via the ``_resolve_codec`` function. + Normalize the input to a `BytesBytesCodec` instance. + If the input is already a `BytesBytesCodec`, it is returned as is. If the input is a dict, it + is converted to a `BytesBytesCodec` instance via the `_resolve_codec` function. """ from zarr.abc.codec import BytesBytesCodec @@ -218,9 +216,9 @@ def _parse_bytes_bytes_codec(data: dict[str, JSON] | Codec) -> BytesBytesCodec: def _parse_array_bytes_codec(data: dict[str, JSON] | Codec) -> ArrayBytesCodec: """ - Normalize the input to a ``ArrayBytesCodec`` instance. - If the input is already a ``ArrayBytesCodec``, it is returned as is. If the input is a dict, it - is converted to a ``ArrayBytesCodec`` instance via the ``_resolve_codec`` function. + Normalize the input to a `ArrayBytesCodec` instance. + If the input is already a `ArrayBytesCodec`, it is returned as is. If the input is a dict, it + is converted to a `ArrayBytesCodec` instance via the `_resolve_codec` function. """ from zarr.abc.codec import ArrayBytesCodec @@ -238,9 +236,9 @@ def _parse_array_bytes_codec(data: dict[str, JSON] | Codec) -> ArrayBytesCodec: def _parse_array_array_codec(data: dict[str, JSON] | Codec) -> ArrayArrayCodec: """ - Normalize the input to a ``ArrayArrayCodec`` instance. - If the input is already a ``ArrayArrayCodec``, it is returned as is. If the input is a dict, it - is converted to a ``ArrayArrayCodec`` instance via the ``_resolve_codec`` function. + Normalize the input to a `ArrayArrayCodec` instance. + If the input is already a `ArrayArrayCodec`, it is returned as is. If the input is a dict, it + is converted to a `ArrayArrayCodec` instance via the `_resolve_codec` function. """ from zarr.abc.codec import ArrayArrayCodec @@ -259,50 +257,50 @@ def _parse_array_array_codec(data: dict[str, JSON] | Codec) -> ArrayArrayCodec: def get_pipeline_class(reload_config: bool = False) -> type[CodecPipeline]: if reload_config: _reload_config() - __pipeline_registry.lazy_load() + _pipeline_registry.lazy_load() path = config.get("codec_pipeline.path") - pipeline_class = __pipeline_registry.get(path) + pipeline_class = _pipeline_registry.get(path) if pipeline_class: return pipeline_class raise BadConfigError( - f"Pipeline class '{path}' not found in registered pipelines: {list(__pipeline_registry)}." + f"Pipeline class '{path}' not found in registered pipelines: {list(_pipeline_registry)}." ) def get_buffer_class(reload_config: bool = False) -> type[Buffer]: if reload_config: _reload_config() - __buffer_registry.lazy_load() + _buffer_registry.lazy_load() path = config.get("buffer") - buffer_class = __buffer_registry.get(path) + buffer_class = _buffer_registry.get(path) if buffer_class: return buffer_class raise BadConfigError( - f"Buffer class '{path}' not found in registered buffers: {list(__buffer_registry)}." + f"Buffer class '{path}' not found in registered buffers: {list(_buffer_registry)}." ) def get_ndbuffer_class(reload_config: bool = False) -> type[NDBuffer]: if reload_config: _reload_config() - __ndbuffer_registry.lazy_load() + _ndbuffer_registry.lazy_load() path = config.get("ndbuffer") - ndbuffer_class = __ndbuffer_registry.get(path) + ndbuffer_class = _ndbuffer_registry.get(path) if ndbuffer_class: return ndbuffer_class raise BadConfigError( - f"NDBuffer class '{path}' not found in registered buffers: {list(__ndbuffer_registry)}." + f"NDBuffer class '{path}' not found in registered buffers: {list(_ndbuffer_registry)}." ) def get_chunk_key_encoding_class(key: str) -> type[ChunkKeyEncoding]: - __chunk_key_encoding_registry.lazy_load(use_entrypoint_name=True) - if key not in __chunk_key_encoding_registry: + _chunk_key_encoding_registry.lazy_load(use_entrypoint_name=True) + if key not in _chunk_key_encoding_registry: raise KeyError( - f"Chunk key encoding '{key}' not found in registered chunk key encodings: {list(__chunk_key_encoding_registry)}." + f"Chunk key encoding '{key}' not found in registered chunk key encodings: {list(_chunk_key_encoding_registry)}." ) - return __chunk_key_encoding_registry[key] + return _chunk_key_encoding_registry[key] _collect_entrypoints() diff --git a/src/zarr/storage/__init__.py b/src/zarr/storage/__init__.py index 00df50214f..f1bd1724af 100644 --- a/src/zarr/storage/__init__.py +++ b/src/zarr/storage/__init__.py @@ -8,7 +8,7 @@ from zarr.storage._fsspec import FsspecStore from zarr.storage._local import LocalStore from zarr.storage._logging import LoggingStore -from zarr.storage._memory import GpuMemoryStore, MemoryStore +from zarr.storage._memory import GpuMemoryStore, ManagedMemoryStore, MemoryStore from zarr.storage._obstore import ObjectStore from zarr.storage._wrapper import WrapperStore from zarr.storage._zip import ZipStore @@ -18,6 +18,7 @@ "GpuMemoryStore", "LocalStore", "LoggingStore", + "ManagedMemoryStore", "MemoryStore", "ObjectStore", "StoreLike", diff --git a/src/zarr/storage/_common.py b/src/zarr/storage/_common.py index 08c05864aa..72b5fc8a40 100644 --- a/src/zarr/storage/_common.py +++ b/src/zarr/storage/_common.py @@ -1,9 +1,8 @@ from __future__ import annotations import importlib.util -import json from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal, Self, TypeAlias +from typing import TYPE_CHECKING, Any, Literal, Self from zarr.abc.store import ( ByteRequest, @@ -12,6 +11,7 @@ SupportsGetSync, SupportsSetSync, ) +from zarr.core._json import buffer_to_json_object, get_json from zarr.core.buffer import Buffer, default_buffer_prototype from zarr.core.common import ( ANY_ACCESS_MODE, @@ -23,8 +23,8 @@ ) from zarr.errors import ContainsArrayAndGroupError, ContainsArrayError, ContainsGroupError from zarr.storage._local import LocalStore -from zarr.storage._memory import MemoryStore -from zarr.storage._utils import normalize_path +from zarr.storage._memory import ManagedMemoryStore, MemoryStore +from zarr.storage._utils import UPath, _join_paths, normalize_path, parse_store_url _has_fsspec = importlib.util.find_spec("fsspec") if _has_fsspec: @@ -34,18 +34,7 @@ if TYPE_CHECKING: from zarr.core.buffer import BufferPrototype - - -def _dereference_path(root: str, path: str) -> str: - if not isinstance(root, str): - msg = f"{root=} is not a string ({type(root)=})" # type: ignore[unreachable] - raise TypeError(msg) - if not isinstance(path, str): - msg = f"{path=} is not a string ({type(path)=})" # type: ignore[unreachable] - raise TypeError(msg) - root = root.rstrip("/") - path = f"{root}/{path}" if root else path - return path.rstrip("/") + from zarr.core.common import JSON class StorePath: @@ -95,11 +84,11 @@ async def open(cls, store: Store, path: str, mode: AccessModeLiteral | None = No The accepted values are: - - ``'r'``: read only (must exist) - - ``'r+'``: read/write (must exist) - - ``'a'``: read/write (create if doesn't exist) - - ``'w'``: read/write (overwrite if exists) - - ``'w-'``: read/write (create if doesn't exist). + - `'r'`: read only (must exist) + - `'r+'`: read/write (must exist) + - `'a'`: read/write (create if doesn't exist) + - `'w'`: read/write (overwrite if exists) + - `'w-'`: read/write (create if doesn't exist). Raises ------ @@ -173,6 +162,23 @@ async def get( prototype = default_buffer_prototype() return await self.store.get(self.path, prototype=prototype, byte_range=byte_range) + async def get_json(self, *, byte_range: ByteRequest | None = None) -> JSON | None: + """ + Read and parse the JSON document at this path, or None if it is absent. + + Parameters + ---------- + byte_range : ByteRequest, optional + If given, read only this portion of the value. Note that a partial + read of a JSON document may not be valid JSON. + + Returns + ------- + JSON or None + The parsed JSON value, or None if this path does not exist. + """ + return await get_json(self.store, self.path, byte_range=byte_range) + async def set(self, value: Buffer) -> None: """ Write bytes to the store. @@ -203,7 +209,7 @@ async def delete_dir(self) -> None: async def set_if_not_exists(self, default: Buffer) -> None: """ - Store a key to ``value`` if the key is not already present. + Store a key to `value` if the key is not already present. Parameters ---------- @@ -244,7 +250,7 @@ def get_sync( prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None, ) -> Buffer | None: - """Synchronous read — delegates to ``self.store.get_sync(self.path, ...)``.""" + """Synchronous read — delegates to `self.store.get_sync(self.path, ...)`.""" if not isinstance(self.store, SupportsGetSync): raise TypeError(f"Store {type(self.store).__name__} does not support synchronous get.") if prototype is None: @@ -252,13 +258,13 @@ def get_sync( return self.store.get_sync(self.path, prototype=prototype, byte_range=byte_range) def set_sync(self, value: Buffer) -> None: - """Synchronous write — delegates to ``self.store.set_sync(self.path, value)``.""" + """Synchronous write — delegates to `self.store.set_sync(self.path, value)`.""" if not isinstance(self.store, SupportsSetSync): raise TypeError(f"Store {type(self.store).__name__} does not support synchronous set.") self.store.set_sync(self.path, value) def delete_sync(self) -> None: - """Synchronous delete — delegates to ``self.store.delete_sync(self.path)``.""" + """Synchronous delete — delegates to `self.store.delete_sync(self.path)`.""" if not isinstance(self.store, SupportsDeleteSync): raise TypeError( f"Store {type(self.store).__name__} does not support synchronous delete." @@ -267,10 +273,10 @@ def delete_sync(self) -> None: def __truediv__(self, other: str) -> StorePath: """Combine this store path with another path""" - return self.__class__(self.store, _dereference_path(self.path, other)) + return self.__class__(self.store, _join_paths([self.path, other])) def __str__(self) -> str: - return _dereference_path(str(self.store), self.path) + return _join_paths([str(self.store), self.path]) def __repr__(self) -> str: return f"StorePath({self.store.__class__.__name__}, '{self}')" @@ -291,12 +297,11 @@ def __eq__(self, other: object) -> bool: """ try: return self.store == other.store and self.path == other.path # type: ignore[attr-defined, no-any-return] - except Exception: - pass - return False + except AttributeError: + return False -StoreLike: TypeAlias = Store | StorePath | FSMap | Path | str | dict[str, Buffer] +type StoreLike = Store | StorePath | FSMap | Path | UPath | str | dict[str, Buffer] async def make_store( @@ -316,6 +321,7 @@ async def make_store( - `dict[str, Buffer]` = `MemoryStore` object. - `None` = `MemoryStore` object. - `FSMap` = `FsspecStore` object. + - `UPath` = `FsspecStore` object, or `LocalStore` for a local `UPath`. Parameters ---------- @@ -342,14 +348,17 @@ async def make_store( """ from zarr.storage._fsspec import FsspecStore # circular import - if ( - not (isinstance(store_like, str) and _is_fsspec_uri(store_like)) - and storage_options is not None - ): - raise TypeError( - "'storage_options' was provided but unused. " - "'storage_options' is only used when the store is passed as an FSSpec URI string.", - ) + # Parse URL early so we can reuse the result for both validation and routing + parsed = parse_store_url(store_like) if isinstance(store_like, str) else None + + # Check if storage_options is valid for this store_like + if storage_options is not None: + is_fsspec_uri = parsed is not None and parsed.scheme not in ("", "memory", "file") + if not is_fsspec_uri: + raise TypeError( + "'storage_options' was provided but unused. " + "'storage_options' is only used when the store is passed as an FSSpec URI string.", + ) assert mode in (None, "r", "r+", "a", "w", "w-") _read_only = mode == "r" @@ -373,19 +382,33 @@ async def make_store( # Create a new in-memory store return await make_store({}, mode=mode, storage_options=storage_options) + elif isinstance(store_like, UPath): + # This must be checked before Path: in universal-pathlib < 0.3 every UPath, including + # remote ones like S3Path, subclasses pathlib.Path, and would otherwise be misrouted to a + # LocalStore. Local UPaths get a LocalStore so that UPath("/data") and Path("/data") agree, + # mirroring how the equivalent strings are routed below. + if store_like.protocol in ("", "file"): + return await make_store( + Path(store_like.path), mode=mode, storage_options=storage_options + ) + return FsspecStore.from_upath(store_like, read_only=_read_only) + elif isinstance(store_like, Path): # Create a new LocalStore return await LocalStore.open(root=store_like, mode=mode, read_only=_read_only) - elif isinstance(store_like, str): - # Either an FSSpec URI or a local filesystem path - if _is_fsspec_uri(store_like): + elif isinstance(store_like, str) and parsed is not None: + if parsed.scheme == "memory" and not _has_fsspec: + # Create or get a ManagedMemoryStore + return ManagedMemoryStore(name=parsed.name, path=parsed.path, read_only=_read_only) + elif parsed.scheme == "file" or not parsed.scheme: + # Local filesystem path — use parsed.path to strip the file:// scheme + return await make_store(Path(parsed.path), mode=mode, storage_options=storage_options) + else: + # Assume fsspec can handle it (s3://, gs://, http://, etc.) return FsspecStore.from_url( store_like, storage_options=storage_options, read_only=_read_only ) - else: - # Assume a filesystem path - return await make_store(Path(store_like), mode=mode, storage_options=storage_options) elif _has_fsspec and isinstance(store_like, FSMap): return FsspecStore.from_mapper(store_like, read_only=_read_only) @@ -460,25 +483,6 @@ async def make_store_path( return await StorePath.open(store, path=path_normalized, mode=mode) -def _is_fsspec_uri(uri: str) -> bool: - """ - Check if a URI looks like a non-local fsspec URI. - - Examples - -------- - ```python - from zarr.storage._common import _is_fsspec_uri - _is_fsspec_uri("s3://bucket") - # True - _is_fsspec_uri("my-directory") - # False - _is_fsspec_uri("local://my-directory") - # False - ``` - """ - return "://" in uri or ("::" in uri and "local://" not in uri) - - async def ensure_no_existing_node( store_path: StorePath, zarr_format: ZarrFormat, @@ -546,14 +550,16 @@ async def _contains_node_v3(store_path: StorePath) -> Literal["array", "group", # if no metadata document could be loaded, then we just return "nothing" if extant_meta_bytes is not None: try: - extant_meta_json = json.loads(extant_meta_bytes.to_bytes()) + extant_meta_json = buffer_to_json_object(extant_meta_bytes) # avoid constructing a full metadata document here in the name of speed. if extant_meta_json["node_type"] == "array": result = "array" elif extant_meta_json["node_type"] == "group": result = "group" - except (KeyError, json.JSONDecodeError): - # either of these errors is consistent with no array or group present. + except (KeyError, TypeError, ValueError): + # any of these errors is consistent with no array or group present. `ValueError` + # covers both malformed JSON (`json.JSONDecodeError`) and non-UTF-8 bytes + # (`UnicodeDecodeError`), each a `ValueError` subclass. pass return result @@ -617,11 +623,11 @@ async def contains_array(store_path: StorePath, zarr_format: ZarrFormat) -> bool return False else: try: - extant_meta_json = json.loads(extant_meta_bytes.to_bytes()) + extant_meta_json = buffer_to_json_object(extant_meta_bytes) # we avoid constructing a full metadata document here in the name of speed. if extant_meta_json["node_type"] == "array": return True - except (ValueError, KeyError): + except (ValueError, KeyError, TypeError): return False elif zarr_format == 2: return await (store_path / ZARRAY_JSON).exists() @@ -649,18 +655,7 @@ async def contains_group(store_path: StorePath, zarr_format: ZarrFormat) -> bool """ if zarr_format == 3: - extant_meta_bytes = await (store_path / ZARR_JSON).get() - if extant_meta_bytes is None: - return False - else: - try: - extant_meta_json = json.loads(extant_meta_bytes.to_bytes()) - # we avoid constructing a full metadata document here in the name of speed. - result: bool = extant_meta_json["node_type"] == "group" - except (ValueError, KeyError): - return False - else: - return result + return (await _contains_node_v3(store_path)) == "group" elif zarr_format == 2: return await (store_path / ZGROUP_JSON).exists() msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3" # type: ignore[unreachable] diff --git a/src/zarr/storage/_fsspec.py b/src/zarr/storage/_fsspec.py index f9e4ed375d..a212e95f2f 100644 --- a/src/zarr/storage/_fsspec.py +++ b/src/zarr/storage/_fsspec.py @@ -1,6 +1,5 @@ from __future__ import annotations -import json import warnings from contextlib import suppress from typing import TYPE_CHECKING, Any @@ -16,7 +15,7 @@ ) from zarr.core.buffer import Buffer from zarr.errors import ZarrUserWarning -from zarr.storage._common import _dereference_path +from zarr.storage._utils import _dereference_path if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterable @@ -51,10 +50,10 @@ def _make_async(fs: AbstractFileSystem) -> AsyncFileSystem: # Already an async instance of an async filesystem, nothing to do return fs if fs.async_impl: - # Convert sync instance of an async fs to an async instance - fs_dict = json.loads(fs.to_json()) - fs_dict["asynchronous"] = True - return fsspec.AbstractFileSystem.from_json(json.dumps(fs_dict)) + # Convert sync instance of an async fs to an async instance. Reuse the original + # constructor arguments rather than round-tripping through JSON, since storage + # options may hold objects that are not JSON-serializable (e.g. credentials). + return type(fs)(*fs.storage_args, **{**fs.storage_options, "asynchronous": True}) if fsspec_version < parse_version("2024.12.0"): raise ImportError( @@ -103,6 +102,15 @@ class FsspecStore(Store): ZarrUserWarning If the file system (fs) was not created with `asynchronous=True`. + Notes + ----- + Closing the store does not close the underlying filesystem or its network + session. fsspec caches and shares filesystem instances across callers, so + the store cannot know whether it is the only user, and closing a shared + session would break other stores. The filesystem's lifecycle belongs to + whoever created it; use fsspec's own tools (e.g. `clear_instance_cache`) + to release it. + See Also -------- FsspecStore.from_upath @@ -163,8 +171,12 @@ def from_upath( ------- FsspecStore """ + # A UPath hands back a filesystem in whatever mode it was constructed with, which is + # synchronous unless the caller passed asynchronous=True. Route it through _make_async so + # that sync-mode instances of async filesystems are re-created in async mode, and + # genuinely synchronous filesystems are wrapped. return cls( - fs=upath.fs, + fs=_make_async(upath.fs), path=upath.path.rstrip("/"), read_only=read_only, allowed_exceptions=allowed_exceptions, @@ -371,30 +383,31 @@ async def get_partial_values( key_ranges: Iterable[tuple[str, ByteRequest | None]], ) -> list[Buffer | None]: # docstring inherited - if key_ranges: - # _cat_ranges expects a list of paths, start, and end ranges, so we need to reformat each ByteRequest. - key_ranges = list(key_ranges) - paths: list[str] = [] - starts: list[int | None] = [] - stops: list[int | None] = [] - for key, byte_range in key_ranges: - paths.append(_dereference_path(self.path, key)) - if byte_range is None: - starts.append(None) - stops.append(None) - elif isinstance(byte_range, RangeByteRequest): - starts.append(byte_range.start) - stops.append(byte_range.end) - elif isinstance(byte_range, OffsetByteRequest): - starts.append(byte_range.offset) - stops.append(None) - elif isinstance(byte_range, SuffixByteRequest): - starts.append(-byte_range.suffix) - stops.append(None) - else: - raise ValueError(f"Unexpected byte_range, got {byte_range}.") - else: + # Materialise first: key_ranges may be a one-shot iterable, so a bare + # truthiness check (e.g. `if key_ranges`) would be unreliable for an + # empty generator. _cat_ranges also expects lists of paths/starts/stops. + key_ranges = list(key_ranges) + if not key_ranges: return [] + paths: list[str] = [] + starts: list[int | None] = [] + stops: list[int | None] = [] + for key, byte_range in key_ranges: + paths.append(_dereference_path(self.path, key)) + if byte_range is None: + starts.append(None) + stops.append(None) + elif isinstance(byte_range, RangeByteRequest): + starts.append(byte_range.start) + stops.append(byte_range.end) + elif isinstance(byte_range, OffsetByteRequest): + starts.append(byte_range.offset) + stops.append(None) + elif isinstance(byte_range, SuffixByteRequest): + starts.append(-byte_range.suffix) + stops.append(None) + else: + raise ValueError(f"Unexpected byte_range, got {byte_range}.") # TODO: expectations for exceptions or missing keys? res = await self.fs._cat_ranges(paths, starts, stops, on_error="return") # the following is an s3-specific condition we probably don't want to leak @@ -408,7 +421,7 @@ async def get_partial_values( async def list(self) -> AsyncIterator[str]: # docstring inherited allfiles = await self.fs._find(self.path, detail=False, withdirs=False) - for onefile in (a.removeprefix(self.path + "/") for a in allfiles): + for onefile in (a.removeprefix(f"{self.path}/") for a in allfiles): yield onefile async def list_dir(self, prefix: str) -> AsyncIterator[str]: @@ -418,7 +431,7 @@ async def list_dir(self, prefix: str) -> AsyncIterator[str]: allfiles = await self.fs._ls(prefix, detail=False) except FileNotFoundError: return - for onefile in (a.replace(prefix + "/", "") for a in allfiles): + for onefile in (a.replace(f"{prefix}/", "") for a in allfiles): yield onefile.removeprefix(self.path).removeprefix("/") async def list_prefix(self, prefix: str) -> AsyncIterator[str]: diff --git a/src/zarr/storage/_local.py b/src/zarr/storage/_local.py index 96f1e61746..1627c1a6b5 100644 --- a/src/zarr/storage/_local.py +++ b/src/zarr/storage/_local.py @@ -8,7 +8,7 @@ import sys import uuid from pathlib import Path -from typing import TYPE_CHECKING, Any, BinaryIO, Literal, Self +from typing import TYPE_CHECKING, BinaryIO, Literal, Self from zarr.abc.store import ( ByteRequest, @@ -356,236 +356,6 @@ async def list_dir(self, prefix: str) -> AsyncIterator[str]: except (FileNotFoundError, NotADirectoryError): pass - async def _get_bytes( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> bytes: - """ - Retrieve raw bytes from the local store asynchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_bytes`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - - Returns - ------- - bytes - The raw bytes stored at the given key. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - - See Also - -------- - Store.get_bytes : Base implementation with full documentation. - get_bytes_sync : Synchronous version of this method. - - Examples - -------- - >>> store = await LocalStore.open("data") - >>> await store.set("data", Buffer.from_bytes(b"hello")) - >>> # No need to specify prototype for LocalStore - >>> data = await store.get_bytes("data") - >>> print(data) - b'hello' - """ - if prototype is None: - prototype = default_buffer_prototype() - return await super()._get_bytes(key, prototype=prototype, byte_range=byte_range) - - def _get_bytes_sync( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> bytes: - """ - Retrieve raw bytes from the local store synchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_bytes`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - - Returns - ------- - bytes - The raw bytes stored at the given key. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - - Warnings - -------- - Do not call this method from async functions. Use ``get_bytes()`` instead. - - See Also - -------- - Store.get_bytes_sync : Base implementation with full documentation. - get_bytes : Asynchronous version of this method. - - Examples - -------- - >>> store = LocalStore("data") - >>> store.set("data", Buffer.from_bytes(b"hello")) - >>> # No need to specify prototype for LocalStore - >>> data = store.get_bytes("data") - >>> print(data) - b'hello' - """ - if prototype is None: - prototype = default_buffer_prototype() - return super()._get_bytes_sync(key, prototype=prototype, byte_range=byte_range) - - async def _get_json( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> Any: - """ - Retrieve and parse JSON data from the local store asynchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_json`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the JSON data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Note: Using byte ranges with JSON may result in invalid JSON. - - Returns - ------- - Any - The parsed JSON data. This follows the behavior of ``json.loads()`` and - can be any JSON-serializable type: dict, list, str, int, float, bool, or None. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - json.JSONDecodeError - If the stored data is not valid JSON. - - See Also - -------- - Store.get_json : Base implementation with full documentation. - get_json_sync : Synchronous version of this method. - get_bytes : Method for retrieving raw bytes without parsing. - - Examples - -------- - >>> store = await LocalStore.open("data") - >>> import json - >>> metadata = {"zarr_format": 3, "node_type": "array"} - >>> await store.set("zarr.json", Buffer.from_bytes(json.dumps(metadata).encode())) - >>> # No need to specify prototype for LocalStore - >>> data = await store.get_json("zarr.json") - >>> print(data) - {'zarr_format': 3, 'node_type': 'array'} - """ - if prototype is None: - prototype = default_buffer_prototype() - return await super()._get_json(key, prototype=prototype, byte_range=byte_range) - - def _get_json_sync( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> Any: - """ - Retrieve and parse JSON data from the local store synchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_json`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the JSON data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Note: Using byte ranges with JSON may result in invalid JSON. - - Returns - ------- - Any - The parsed JSON data. This follows the behavior of ``json.loads()`` and - can be any JSON-serializable type: dict, list, str, int, float, bool, or None. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - json.JSONDecodeError - If the stored data is not valid JSON. - - Warnings - -------- - Do not call this method from async functions. Use ``get_json()`` instead. - - See Also - -------- - Store.get_json_sync : Base implementation with full documentation. - get_json : Asynchronous version of this method. - get_bytes_sync : Method for retrieving raw bytes without parsing. - - Examples - -------- - >>> store = LocalStore("data") - >>> import json - >>> metadata = {"zarr_format": 3, "node_type": "array"} - >>> store.set("zarr.json", Buffer.from_bytes(json.dumps(metadata).encode())) - >>> # No need to specify prototype for LocalStore - >>> data = store.get_json("zarr.json") - >>> print(data) - {'zarr_format': 3, 'node_type': 'array'} - """ - if prototype is None: - prototype = default_buffer_prototype() - return super()._get_json_sync(key, prototype=prototype, byte_range=byte_range) - async def move(self, dest_root: Path | str) -> None: """ Move the store to another path. The old root directory is deleted. @@ -593,10 +363,10 @@ async def move(self, dest_root: Path | str) -> None: if isinstance(dest_root, str): dest_root = Path(dest_root) os.makedirs(dest_root.parent, exist_ok=True) - if os.path.exists(dest_root): + if dest_root.exists(): raise FileExistsError(f"Destination root {dest_root} already exists.") shutil.move(self.root, dest_root) self.root = dest_root async def getsize(self, key: str) -> int: - return os.path.getsize(self.root / key) + return (self.root / key).stat().st_size diff --git a/src/zarr/storage/_logging.py b/src/zarr/storage/_logging.py index 98dca6b23d..cdf0731430 100644 --- a/src/zarr/storage/_logging.py +++ b/src/zarr/storage/_logging.py @@ -6,7 +6,7 @@ import time from collections import defaultdict from contextlib import contextmanager -from typing import TYPE_CHECKING, Any, Self, TypeVar +from typing import TYPE_CHECKING, Any, Self from zarr.abc.store import Store from zarr.storage._wrapper import WrapperStore @@ -19,10 +19,8 @@ counter: defaultdict[str, int] -T_Store = TypeVar("T_Store", bound=Store) - -class LoggingStore(WrapperStore[T_Store]): +class LoggingStore[T_Store: Store](WrapperStore[T_Store]): """ Store that logs all calls to another wrapped store. @@ -163,7 +161,7 @@ def __repr__(self) -> str: def __eq__(self, other: object) -> bool: with self.log(other): - return type(self) is type(other) and self._store.__eq__(other._store) # type: ignore[attr-defined] + return type(self) is type(other) and self._store.__eq__(other._store) async def get( self, @@ -181,6 +179,7 @@ async def get_partial_values( key_ranges: Iterable[tuple[str, ByteRequest | None]], ) -> list[Buffer | None]: # docstring inherited + key_ranges = list(key_ranges) keys = ",".join([k[0] for k in key_ranges]) with self.log(keys): return await self._store.get_partial_values(prototype=prototype, key_ranges=key_ranges) @@ -205,6 +204,27 @@ async def delete(self, key: str) -> None: with self.log(key): return await self._store.delete(key=key) + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + with self.log(key): + return super().get_sync(key, prototype=prototype, byte_range=byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + # docstring inherited + with self.log(key): + return super().set_sync(key, value) + + def delete_sync(self, key: str) -> None: + # docstring inherited + with self.log(key): + return super().delete_sync(key) + async def list(self) -> AsyncGenerator[str, None]: # docstring inherited with self.log(): diff --git a/src/zarr/storage/_memory.py b/src/zarr/storage/_memory.py index 1194894b9d..f42c38df69 100644 --- a/src/zarr/storage/_memory.py +++ b/src/zarr/storage/_memory.py @@ -1,5 +1,8 @@ from __future__ import annotations +import os +import threading +import weakref from logging import getLogger from typing import TYPE_CHECKING, Any, Self @@ -7,7 +10,12 @@ from zarr.core.buffer import Buffer, gpu from zarr.core.buffer.core import default_buffer_prototype from zarr.core.common import concurrent_map -from zarr.storage._utils import _normalize_byte_range_index +from zarr.storage._utils import ( + _join_paths, + _normalize_byte_range_index, + normalize_path, + parse_store_url, +) if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterable, MutableMapping @@ -18,6 +26,18 @@ logger = getLogger(__name__) +def _copy_buffer(value: Buffer) -> Buffer: + """Copy `value` so the store does not retain the caller's memory. + + Encoding a chunk can hand the store a zero-copy view of the user's array + (an uncompressed write is the common case), and unlike stores that + serialize on write, this one keeps whatever it is given alive in a dict. + Without this copy a later mutation of the user's array would rewrite + chunks already committed to the store. + """ + return type(value).from_array_like(value.as_array_like().copy()) + + class MemoryStore(Store): """ Store for local memory. @@ -34,6 +54,12 @@ class MemoryStore(Store): supports_writes supports_deletes supports_listing + + Notes + ----- + Writes copy the buffer they are given, so the store never aliases the + caller's memory. Buffers passed via `store_dict` are the caller's + responsibility and are stored as-is. """ supports_writes: bool = True @@ -109,7 +135,7 @@ def set_sync(self, key: str, value: Buffer) -> None: raise TypeError( f"MemoryStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." ) - self._store_dict[key] = value + self._store_dict[key] = _copy_buffer(value) def delete_sync(self, key: str) -> None: self._check_writable() @@ -170,13 +196,13 @@ async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None buf[byte_range[0] : byte_range[1]] = value self._store_dict[key] = buf else: - self._store_dict[key] = value + self._store_dict[key] = _copy_buffer(value) async def set_if_not_exists(self, key: str, value: Buffer) -> None: # docstring inherited self._check_writable() await self._ensure_open() - self._store_dict.setdefault(key, value) + self._store_dict.setdefault(key, _copy_buffer(value)) async def delete(self, key: str) -> None: # docstring inherited @@ -209,244 +235,14 @@ async def list_dir(self, prefix: str) -> AsyncIterator[str]: # a pseudo directory when there's a nested item and we're listing an # intermediate level. keys_unique = { - key.removeprefix(prefix + "/").split("/")[0] + key.removeprefix(f"{prefix}/").split("/")[0] for key in self._store_dict - if key.startswith(prefix + "/") and key != prefix + if key.startswith(f"{prefix}/") and key not in {prefix, f"{prefix}/"} } for key in keys_unique: yield key - async def _get_bytes( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> bytes: - """ - Retrieve raw bytes from the memory store asynchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_bytes`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - - Returns - ------- - bytes - The raw bytes stored at the given key. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - - See Also - -------- - Store.get_bytes : Base implementation with full documentation. - get_bytes_sync : Synchronous version of this method. - - Examples - -------- - >>> store = await MemoryStore.open() - >>> await store.set("data", Buffer.from_bytes(b"hello")) - >>> # No need to specify prototype for MemoryStore - >>> data = await store.get_bytes("data") - >>> print(data) - b'hello' - """ - if prototype is None: - prototype = default_buffer_prototype() - return await super()._get_bytes(key, prototype=prototype, byte_range=byte_range) - - def _get_bytes_sync( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> bytes: - """ - Retrieve raw bytes from the memory store synchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_bytes`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - - Returns - ------- - bytes - The raw bytes stored at the given key. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - - Warnings - -------- - Do not call this method from async functions. Use ``get_bytes()`` instead. - - See Also - -------- - Store.get_bytes_sync : Base implementation with full documentation. - get_bytes : Asynchronous version of this method. - - Examples - -------- - >>> store = MemoryStore() - >>> store.set("data", Buffer.from_bytes(b"hello")) - >>> # No need to specify prototype for MemoryStore - >>> data = store.get_bytes("data") - >>> print(data) - b'hello' - """ - if prototype is None: - prototype = default_buffer_prototype() - return super()._get_bytes_sync(key, prototype=prototype, byte_range=byte_range) - - async def _get_json( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> Any: - """ - Retrieve and parse JSON data from the memory store asynchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_json`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the JSON data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Note: Using byte ranges with JSON may result in invalid JSON. - - Returns - ------- - Any - The parsed JSON data. This follows the behavior of ``json.loads()`` and - can be any JSON-serializable type: dict, list, str, int, float, bool, or None. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - json.JSONDecodeError - If the stored data is not valid JSON. - - See Also - -------- - Store.get_json : Base implementation with full documentation. - get_json_sync : Synchronous version of this method. - get_bytes : Method for retrieving raw bytes without parsing. - - Examples - -------- - >>> store = await MemoryStore.open() - >>> import json - >>> metadata = {"zarr_format": 3, "node_type": "array"} - >>> await store.set("zarr.json", Buffer.from_bytes(json.dumps(metadata).encode())) - >>> # No need to specify prototype for MemoryStore - >>> data = await store.get_json("zarr.json") - >>> print(data) - {'zarr_format': 3, 'node_type': 'array'} - """ - if prototype is None: - prototype = default_buffer_prototype() - return await super()._get_json(key, prototype=prototype, byte_range=byte_range) - - def _get_json_sync( - self, - key: str = "", - *, - prototype: BufferPrototype | None = None, - byte_range: ByteRequest | None = None, - ) -> Any: - """ - Retrieve and parse JSON data from the memory store synchronously. - - This is a convenience override that makes the ``prototype`` parameter optional - by defaulting to the standard buffer prototype. See the base ``Store.get_json`` - for full documentation. - - Parameters - ---------- - key : str, optional - The key identifying the JSON data to retrieve. Defaults to an empty string. - prototype : BufferPrototype, optional - The buffer prototype to use for reading the data. If None, uses - ``default_buffer_prototype()``. - byte_range : ByteRequest, optional - If specified, only retrieve a portion of the stored data. - Note: Using byte ranges with JSON may result in invalid JSON. - - Returns - ------- - Any - The parsed JSON data. This follows the behavior of ``json.loads()`` and - can be any JSON-serializable type: dict, list, str, int, float, bool, or None. - - Raises - ------ - FileNotFoundError - If the key does not exist in the store. - json.JSONDecodeError - If the stored data is not valid JSON. - - Warnings - -------- - Do not call this method from async functions. Use ``get_json()`` instead. - - See Also - -------- - Store.get_json_sync : Base implementation with full documentation. - get_json : Asynchronous version of this method. - get_bytes_sync : Method for retrieving raw bytes without parsing. - - Examples - -------- - >>> store = MemoryStore() - >>> import json - >>> metadata = {"zarr_format": 3, "node_type": "array"} - >>> store.set("zarr.json", Buffer.from_bytes(json.dumps(metadata).encode())) - >>> # No need to specify prototype for MemoryStore - >>> data = store.get_json("zarr.json") - >>> print(data) - {'zarr_format': 3, 'node_type': 'array'} - """ - if prototype is None: - prototype = default_buffer_prototype() - return super()._get_json_sync(key, prototype=prototype, byte_range=byte_range) - class GpuMemoryStore(MemoryStore): """ @@ -517,3 +313,397 @@ async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None # Convert to gpu.Buffer gpu_value = value if isinstance(value, gpu.Buffer) else gpu.Buffer.from_buffer(value) await super().set(key, gpu_value, byte_range=byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + # docstring inherited + self._check_writable() + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"GpuMemoryStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + # Convert to gpu.Buffer, mirroring `set` above: every value in this store's + # backing dict must be a gpu.Buffer, regardless of which API wrote it. + gpu_value = value if isinstance(value, gpu.Buffer) else gpu.Buffer.from_buffer(value) + super().set_sync(key, gpu_value) + + +# ----------------------------------------------------------------------------- +# ManagedMemoryStore and its registry +# ----------------------------------------------------------------------------- +# ManagedMemoryStore owns the lifecycle of its backing dict, enabling proper +# weakref-based tracking. This allows memory:// URLs to be resolved back to +# the store's dict within the same process. + + +class _ManagedStoreDict(dict[str, Buffer]): + """ + A dict subclass that supports weak references. + + Regular dicts don't support weakrefs, but we need to track managed store dicts + in a WeakValueDictionary so they can be garbage collected when no longer + referenced. This subclass adds the necessary __weakref__ slot. + """ + + __slots__ = ("__weakref__",) + + +class _ManagedStoreDictRegistry: + """ + Registry for managed store dicts. + + This registry is the source of truth for managed store dicts. It creates + new dicts, tracks them via weak references, and looks them up by name. + """ + + def __init__(self) -> None: + self._registry: weakref.WeakValueDictionary[str, _ManagedStoreDict] = ( + weakref.WeakValueDictionary() + ) + self._counter = 0 + self._lock = threading.Lock() + + def _generate_name(self) -> str: + """Generate a unique name for a store. + + Must be called while holding `self._lock`. + """ + name = str(self._counter) + self._counter += 1 + return name + + def get_or_create(self, name: str | None = None) -> tuple[_ManagedStoreDict, str]: + """ + Get an existing managed dict by name, or create a new one. + + Thread-safe: uses a lock to prevent TOCTOU races between + checking for an existing entry and inserting a new one. + + Parameters + ---------- + name : str | None + The name for the store. If None, a unique name is auto-generated. + If a store with this name already exists, returns the existing store. + Names cannot contain '/' characters. + + Returns + ------- + tuple[_ManagedStoreDict, str] + The store dict and its name. + + Raises + ------ + ValueError + If the name contains '/' characters. + """ + with self._lock: + if name is None: + name = self._generate_name() + elif "/" in name: + raise ValueError( + f"Store name cannot contain '/': {name!r}. " + "Use the 'path' parameter to specify a path within the store." + ) + + existing = self._registry.get(name) + if existing is not None: + return existing, name + + store_dict = _ManagedStoreDict() + self._registry[name] = store_dict + return store_dict, name + + def get(self, name: str) -> _ManagedStoreDict | None: + """ + Look up a managed store dict by name. + + Parameters + ---------- + name : str + The name of the store. + + Returns + ------- + _ManagedStoreDict | None + The store dict if found, None otherwise. + """ + return self._registry.get(name) + + +_managed_store_dict_registry = _ManagedStoreDictRegistry() + + +class ManagedMemoryStore(MemoryStore): + """ + A memory store that owns and manages the lifecycle of its backing dict. + + Unlike ``MemoryStore`` which accepts any ``MutableMapping``, this store + creates and owns its backing dict internally. This enables proper lifecycle + management and allows the store to be looked up by its ``memory://`` URL + within the same process. + + Parameters + ---------- + name : str | None + The name for this store, used in the ``memory://`` URL. If None, a unique + name is auto-generated. If a store with this name already exists, the + new store will share the same backing dict. + path : str + The root path for this store. All keys will be prefixed with this path. + read_only : bool + Whether the store is read-only. + + Attributes + ---------- + name : str + The name of this store. + path : str + The root path of this store. + + Notes + ----- + The backing dict is tracked via weak references and will be garbage collected + when no ``ManagedMemoryStore`` instances reference it. URLs pointing to a + garbage-collected store will fail to resolve. + + See Also + -------- + MemoryStore : A memory store that accepts any MutableMapping. + + Examples + -------- + >>> store = ManagedMemoryStore(name="my-data") + >>> str(store) + 'memory://my-data' + >>> # Later, resolve the URL back to the store's dict + >>> store2 = ManagedMemoryStore.from_url("memory://my-data") + >>> store2._store_dict is store._store_dict + True + >>> # Create a store with a path prefix + >>> store3 = ManagedMemoryStore.from_url("memory://my-data/subdir") + >>> store3.path + 'subdir' + """ + + _store_dict: _ManagedStoreDict + _name: str + path: str + + def __init__(self, name: str | None = None, *, path: str = "", read_only: bool = False) -> None: + # Skip MemoryStore.__init__ and call Store.__init__ directly + # because we manage _store_dict via the registry, not via a user-supplied + # MutableMapping. If MemoryStore.__init__ ever adds logic beyond setting + # _store_dict, that logic must be replicated here. + Store.__init__(self, read_only=read_only) + + # Get or create a managed dict from the registry + self._store_dict, self._name = _managed_store_dict_registry.get_or_create(name) + self.path = normalize_path(path) + + def __str__(self) -> str: + return _join_paths([f"memory://{self._name}", self.path]) + + def __repr__(self) -> str: + return f"ManagedMemoryStore('{self}')" + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and self._store_dict is other._store_dict + and self.path == other.path + and self.read_only == other.read_only + ) + + @property + def name(self) -> str: + """The name of this store, used in the memory:// URL.""" + return self._name + + @classmethod + def _from_managed_dict( + cls, + managed_dict: _ManagedStoreDict, + name: str, + *, + path: str = "", + read_only: bool = False, + ) -> ManagedMemoryStore: + """Internal: create a store from an existing managed dict.""" + store = object.__new__(cls) + Store.__init__(store, read_only=read_only) + store._store_dict = managed_dict + store._name = name + store.path = normalize_path(path) + return store + + def with_read_only(self, read_only: bool = False) -> ManagedMemoryStore: + # docstring inherited + return type(self)._from_managed_dict( + self._store_dict, self._name, path=self.path, read_only=read_only + ) + + @classmethod + def from_url(cls, url: str, *, read_only: bool = False) -> ManagedMemoryStore: + """ + Create a ManagedMemoryStore from a memory:// URL. + + This looks up the backing dict in the process-wide registry and creates + a new store instance that shares the same dict. + + Parameters + ---------- + url : str + A URL like "memory://my-store" or "memory://my-store/path/to/data" + identifying the store and optional path prefix. + read_only : bool + Whether the new store should be read-only. + + Returns + ------- + ManagedMemoryStore + A store sharing the same backing dict as the original. + + Raises + ------ + ValueError + If the URL is not a valid memory:// URL or the store has been + garbage collected. + """ + parsed = parse_store_url(url) + if parsed.scheme != "memory": + raise ValueError( + f"Expected a 'memory://' URL, got scheme {parsed.scheme!r} in '{url}'." + ) + name = parsed.name or "" + managed_dict = _managed_store_dict_registry.get(name) + if managed_dict is None: + raise ValueError( + f"Memory store not found for URL '{url}'. " + "The store may have been garbage collected." + ) + return cls._from_managed_dict(managed_dict, name, path=parsed.path, read_only=read_only) + + # Override MemoryStore methods to use path prefix and check process + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + return super().get_sync( + _join_paths([self.path, key]), prototype=prototype, byte_range=byte_range + ) + + def set_sync(self, key: str, value: Buffer) -> None: + # docstring inherited + super().set_sync(_join_paths([self.path, key]), value) + + def delete_sync(self, key: str) -> None: + # docstring inherited + super().delete_sync(_join_paths([self.path, key])) + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + return await super().get( + _join_paths([self.path, key]), prototype=prototype, byte_range=byte_range + ) + + # get_partial_values is intentionally NOT overridden here: MemoryStore.get_partial_values + # dispatches per-key through `self.get`, which already resolves to the override above. + # Re-prefixing the keys here as well would apply `self.path` twice. + + async def exists(self, key: str) -> bool: + # docstring inherited + return await super().exists(_join_paths([self.path, key])) + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + # docstring inherited + return await super().set(_join_paths([self.path, key]), value, byte_range=byte_range) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + # docstring inherited + return await super().set_if_not_exists(_join_paths([self.path, key]), value) + + async def delete(self, key: str) -> None: + # docstring inherited + return await super().delete(_join_paths([self.path, key])) + + async def list(self) -> AsyncIterator[str]: + # docstring inherited + prefix = f"{self.path}/" if self.path else "" + async for key in super().list(): + if key.startswith(prefix): + yield key.removeprefix(prefix) + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + # Manual concatenation instead of _join_paths because we need "path/" + # as the prefix when prefix is empty (to list all keys under self.path) + full_prefix = f"{self.path}/{prefix}" if self.path else prefix + path_prefix = f"{self.path}/" if self.path else "" + async for key in super().list_prefix(full_prefix): + yield key.removeprefix(path_prefix) + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + full_prefix = _join_paths([self.path, prefix]) + async for key in super().list_dir(full_prefix): + yield key + + def __reduce__( + self, + ) -> tuple[type[ManagedMemoryStore], tuple[str | None], dict[str, Any]]: + """ + Support pickling of ManagedMemoryStore. + + On unpickle, the store will reconnect to an existing store with the same + name if one exists in the registry, or create a new empty store otherwise. + + Note that the backing dict data is NOT serialized - only the store's + identity (name, path, read_only) is preserved. If the original store has + been garbage collected, the unpickled store will have an empty dict. + + The current process ID is preserved so that cross-process unpickling can be + detected and will raise an error at unpickle time. + """ + return ( + self.__class__, + (self._name,), + { + "path": self.path, + "read_only": self.read_only, + "created_pid": os.getpid(), + }, + ) + + def __setstate__(self, state: dict[str, Any]) -> None: + """Restore state after unpickling. + + The pickle protocol calls ``cls(name)`` (via ``__reduce__``'s args) + then ``__setstate__(state)``. ``__init__`` already set up + ``_store_dict`` and ``_name`` from the registry — we just restore + path and read_only here. + """ + # Check for cross-process usage first, before mutating state + created_pid = state.get("created_pid") + if created_pid is not None and created_pid != os.getpid(): + raise RuntimeError( + f"ManagedMemoryStore '{self._name}' was created in process {created_pid} " + f"but is being unpickled in process {os.getpid()}. " + "ManagedMemoryStore instances cannot be shared across processes because " + "their backing dict is not serialized. Use a persistent store (e.g., " + "LocalStore, ZipStore) for cross-process data sharing." + ) + + self.path = normalize_path(state.get("path", "")) + # Use the Store-level _read_only attribute directly because + # Store.__init__ was already called by __init__ during unpickling + self._read_only = state.get("read_only", False) diff --git a/src/zarr/storage/_obstore.py b/src/zarr/storage/_obstore.py index 6e4011da59..b34a5f624d 100644 --- a/src/zarr/storage/_obstore.py +++ b/src/zarr/storage/_obstore.py @@ -6,7 +6,7 @@ from collections import defaultdict from itertools import chain from operator import itemgetter -from typing import TYPE_CHECKING, Generic, Self, TypedDict, TypeVar +from typing import TYPE_CHECKING, Self, TypedDict from zarr.abc.store import ( ByteRequest, @@ -37,10 +37,7 @@ ) -T_Store = TypeVar("T_Store", bound="_UpstreamObjectStore") - - -class ObjectStore(Store, Generic[T_Store]): +class ObjectStore[T_Store: "_UpstreamObjectStore"](Store): """ Store that uses obstore for fast read/write from AWS, GCP, Azure. @@ -270,7 +267,11 @@ async def _transform_list_dir( for path in chain( list_result["common_prefixes"], map(itemgetter("path"), list_result["objects"]) ): - yield _relativize_path(path=path, prefix=prefix) + if prefix != "" and path == prefix: + continue + relpath = _relativize_path(path=path, prefix=prefix) + if relpath: + yield relpath class _BoundedRequest(TypedDict): diff --git a/src/zarr/storage/_utils.py b/src/zarr/storage/_utils.py index 10ac395b36..ca10b0679e 100644 --- a/src/zarr/storage/_utils.py +++ b/src/zarr/storage/_utils.py @@ -1,8 +1,22 @@ from __future__ import annotations +import importlib import re -from pathlib import Path -from typing import TYPE_CHECKING, TypeVar +from pathlib import Path, PureWindowsPath +from urllib.parse import urlparse + +if importlib.util.find_spec("upath"): + # Re-exported for zarr.storage._common, which needs it to recognize UPath store_like values. + # The redundant-looking alias is the explicit re-export mypy requires under strict mode. + from upath.core import UPath as UPath # noqa: PLC0414 +else: + + class UPath: # type: ignore[no-redef] + pass + + +import sys +from typing import TYPE_CHECKING, NamedTuple from zarr.abc.store import OffsetByteRequest, RangeByteRequest, SuffixByteRequest @@ -13,6 +27,83 @@ from zarr.core.buffer import Buffer +class ParsedStoreUrl(NamedTuple): + """ + Parsed components of a store URL. + + Attributes + ---------- + scheme : str + The URL scheme (e.g., "memory", "file", "s3"). Empty string for local paths. + name : str | None + The store name/host component. For memory:// URLs this is the store name. + None if empty. + path : str + The path component within the store. + raw : str + The original URL string. + """ + + scheme: str + name: str | None + path: str + raw: str + + +def parse_store_url(url: str) -> ParsedStoreUrl: + """ + Parse a store URL into its components. + + Parameters + ---------- + url : str + A URL like "memory://store-name/path" or "s3://bucket/key" or a local path. + + Returns + ------- + ParsedStoreUrl + Named tuple with scheme, name, path, and raw URL. + + Examples + -------- + >>> parse_store_url("memory://mystore") + ParsedStoreUrl(scheme='memory', name='mystore', path='', raw='memory://mystore') + + >>> parse_store_url("memory://mystore/path/to/data") + ParsedStoreUrl(scheme='memory', name='mystore', path='path/to/data', raw='memory://mystore/path/to/data') + + >>> parse_store_url("s3://bucket/key") + ParsedStoreUrl(scheme='s3', name='bucket', path='key', raw='s3://bucket/key') + + >>> parse_store_url("/local/path") + ParsedStoreUrl(scheme='', name=None, path='/local/path', raw='/local/path') + + Note that ``memory://name/path`` and ``memory:///path`` are different: + the first has ``name="name"`` and ``path="path"``, while the second has + ``name=None`` and ``path="/path"`` (no host component between ``//`` and ``/``). + """ + # On Windows, bare paths like "C:\foo" or "C:/foo" cause urlparse to + # misinterpret the drive letter as a URL scheme. Detect this early and + # return a local-path result without going through urlparse. + if sys.platform == "win32" and PureWindowsPath(url).drive: + return ParsedStoreUrl(scheme="", name=None, path=url, raw=url) + + parsed = urlparse(url) + + # netloc is the "host" part (store name for memory://, bucket for s3://, etc.) + name = parsed.netloc or None + + # For URLs with a scheme and netloc (like memory://store/path or s3://bucket/key), + # strip the leading slash from the path component. + # For local paths (no scheme), preserve the path as-is. + if parsed.scheme and parsed.netloc: + path = parsed.path.lstrip("/") + else: + path = parsed.path + + return ParsedStoreUrl(scheme=parsed.scheme, name=name, path=path, raw=url) + + def normalize_path(path: str | bytes | Path | None) -> str: if path is None: result = "" @@ -20,7 +111,8 @@ def normalize_path(path: str | bytes | Path | None) -> str: result = str(path, "ascii") # handle pathlib.Path - elif isinstance(path, Path): + + elif isinstance(path, Path | UPath): result = str(path) elif isinstance(path, str): @@ -63,7 +155,7 @@ def _normalize_byte_range_index(data: Buffer, byte_range: ByteRequest | None) -> start = byte_range.offset stop = len(data) + 1 elif isinstance(byte_range, SuffixByteRequest): - start = len(data) - byte_range.suffix + start = max(0, len(data) - byte_range.suffix) stop = len(data) + 1 else: raise ValueError(f"Unexpected byte_range, got {byte_range}.") @@ -95,6 +187,53 @@ def _join_paths(paths: Iterable[str]) -> str: return "/".join(filter(lambda v: v != "", paths)) +def _dereference_path(root: str, path: str) -> str: + """ + Combine a store-side root with a key into a single fully-qualified path. + + Unlike `_join_paths`, this is purpose-built for the case where `root` is + an opaque backend-side prefix that may use `"/"` as a sentinel for "root + of the filesystem" (notably for fsspec's `ReferenceFileSystem`). A + trailing `"/"` is stripped from `root` before joining; if `root` is then + empty, the bare `path` is returned so that joining `"/"` with `"key"` + yields `"key"` rather than `"//key"`. A trailing `"/"` on the result is + also stripped. + + Leading slashes on `root` are preserved -- a backend-side path like + `"/home/foo/data.zarr"` is an absolute filesystem path for + `LocalFileSystem` and must not lose its leading separator. + + Parameters + ---------- + root : str + The backend-side root of a store. May be `""`, `"/"`, an absolute + filesystem path, or a backend-specific prefix. + path : str + The key within the store, typically a zarr key like `"zarr.json"` + or `"a/b/c/zarr.json"`. + + Returns + ------- + str + `root` and `path` joined by a single `"/"`, with the `"/"` sentinel + collapsed and trailing slashes removed. + + Examples + -------- + ```python + from zarr.storage._utils import _dereference_path + _dereference_path("/", "zarr.json") # 'zarr.json' + _dereference_path("", "zarr.json") # 'zarr.json' + _dereference_path("/home/foo", "zarr.json") # '/home/foo/zarr.json' + _dereference_path("/home/foo/", "zarr.json") # '/home/foo/zarr.json' + _dereference_path("bucket/p", "zarr.json") # 'bucket/p/zarr.json' + ``` + """ + root = root.rstrip("/") + path = f"{root}/{path}" if root else path + return path.rstrip("/") + + def _relativize_path(*, path: str, prefix: str) -> str: """ Make a "/"-delimited path relative to some prefix. If the prefix is '', then the path is @@ -130,10 +269,10 @@ def _relativize_path(*, path: str, prefix: str) -> str: if prefix == "": return path else: - _prefix = prefix + "/" + _prefix = f"{prefix}/" if not path.startswith(_prefix): raise ValueError(f"The first component of {path} does not start with {prefix}.") - return path.removeprefix(f"{prefix}/") + return path.removeprefix(_prefix) def _normalize_paths(paths: Iterable[str]) -> tuple[str, ...]: @@ -155,10 +294,7 @@ def _normalize_paths(paths: Iterable[str]) -> tuple[str, ...]: return tuple(path_map.keys()) -T = TypeVar("T") - - -def _normalize_path_keys(data: Mapping[str, T]) -> dict[str, T]: +def _normalize_path_keys[T](data: Mapping[str, T]) -> dict[str, T]: """ Normalize the keys of the input dict according to the normalization scheme used for zarr node paths. If any two keys in the input normalize to the same value, raise a ValueError. diff --git a/src/zarr/storage/_wrapper.py b/src/zarr/storage/_wrapper.py index e8a2859abc..6f498a655d 100644 --- a/src/zarr/storage/_wrapper.py +++ b/src/zarr/storage/_wrapper.py @@ -1,9 +1,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Generic, TypeVar, cast +from typing import TYPE_CHECKING, cast if TYPE_CHECKING: - from collections.abc import AsyncGenerator, AsyncIterator, Iterable + from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Sequence from types import TracebackType from typing import Any, Self @@ -11,12 +11,16 @@ from zarr.abc.store import ByteRequest from zarr.core.buffer import BufferPrototype -from zarr.abc.store import Store +from zarr.abc.store import ( + Store, + SupportsDeleteSync, + SupportsGetSync, + SupportsSetSync, + _store_supports_sync_io, +) -T_Store = TypeVar("T_Store", bound=Store) - -class WrapperStore(Store, Generic[T_Store]): +class WrapperStore[T_Store: Store](Store): """ Store that wraps an existing Store. @@ -85,7 +89,7 @@ def _check_writable(self) -> None: return self._store._check_writable() def __eq__(self, value: object) -> bool: - return type(self) is type(value) and self._store.__eq__(value._store) # type: ignore[attr-defined] + return type(self) is type(value) and self._store.__eq__(value._store) def __str__(self) -> str: return f"wrapping-{self._store}" @@ -105,6 +109,32 @@ async def get_partial_values( ) -> list[Buffer | None]: return await self._store.get_partial_values(prototype, key_ranges) + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int | None = None, + max_gap_bytes: int | None = None, + max_coalesced_bytes: int | None = None, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + """Forward `get_ranges` to the wrapped store. + + Default values for the coalescing kwargs are not declared here; the + wrapped store decides them. `None` means "don't override the wrapped + store's default". + """ + kwargs: dict[str, int] = {} + if max_concurrency is not None: + kwargs["max_concurrency"] = max_concurrency + if max_gap_bytes is not None: + kwargs["max_gap_bytes"] = max_gap_bytes + if max_coalesced_bytes is not None: + kwargs["max_coalesced_bytes"] = max_coalesced_bytes + async for group in self._store.get_ranges(key, byte_ranges, prototype=prototype, **kwargs): + yield group + async def exists(self, key: str) -> bool: return await self._store.exists(key) @@ -125,6 +155,40 @@ def supports_writes(self) -> bool: def supports_deletes(self) -> bool: return self._store.supports_deletes + @property + def _supports_sync_io(self) -> bool: + # The delegating `*_sync` methods below make every wrapper structurally + # satisfy `SupportsSyncStore`; whether they can actually run depends on + # the wrapped store, so forward its capability (see + # `zarr.abc.store._store_supports_sync_io`). + return _store_supports_sync_io(self._store) + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + """Forward `get_sync` to the wrapped store.""" + if not isinstance(self._store, SupportsGetSync): + raise TypeError(f"Store {type(self._store).__name__} does not support synchronous get.") + return self._store.get_sync(key, prototype=prototype, byte_range=byte_range) # type: ignore[unreachable] + + def set_sync(self, key: str, value: Buffer) -> None: + """Forward `set_sync` to the wrapped store.""" + if not isinstance(self._store, SupportsSetSync): + raise TypeError(f"Store {type(self._store).__name__} does not support synchronous set.") + self._store.set_sync(key, value) # type: ignore[unreachable] + + def delete_sync(self, key: str) -> None: + """Forward `delete_sync` to the wrapped store.""" + if not isinstance(self._store, SupportsDeleteSync): + raise TypeError( + f"Store {type(self._store).__name__} does not support synchronous delete." + ) + self._store.delete_sync(key) # type: ignore[unreachable] + async def delete(self, key: str) -> None: await self._store.delete(key) diff --git a/src/zarr/storage/_zip.py b/src/zarr/storage/_zip.py index 72bf9e335a..69ae18bc2c 100644 --- a/src/zarr/storage/_zip.py +++ b/src/zarr/storage/_zip.py @@ -1,12 +1,13 @@ from __future__ import annotations +import io import os import shutil import threading import time import zipfile from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal +from typing import IO, TYPE_CHECKING, Any, Literal from zarr.abc.store import ( ByteRequest, @@ -23,14 +24,67 @@ ZipStoreAccessModeLiteral = Literal["r", "w", "a"] +class _RawReaderAdapter(io.RawIOBase): + """ + Adapt a minimal seekable reader to the `io` interface `zipfile` needs. + + Some file-like objects (e.g. `obstore.ReadableFile`) implement + `read`/`seek`/`tell` but are not `io.IOBase` instances, and their + `read` may return a buffer-protocol object rather than `bytes`. + Wrapping in this adapter plus `io.BufferedReader` yields real `bytes`. + + Reads are clamped to the bytes remaining before EOF: some readers + (obstore < 0.6) raise on short reads rather than returning fewer bytes. + The size is cached, which is safe because the adapter is only used for + read-only access. + """ + + def __init__(self, fileobj: IO[bytes]) -> None: + self._fileobj = fileobj + self._size: int | None = None + + def _get_size(self) -> int: + if self._size is None: + pos = self._fileobj.tell() + self._size = self._fileobj.seek(0, os.SEEK_END) + self._fileobj.seek(pos) + return self._size + + def readable(self) -> bool: + return True + + def seekable(self) -> bool: + return True + + def seek(self, pos: int, whence: int = 0) -> int: + return self._fileobj.seek(pos, whence) + + def tell(self) -> int: + return self._fileobj.tell() + + def readinto(self, b: Any) -> int: + n_requested = min(len(b), self._get_size() - self._fileobj.tell()) + if n_requested <= 0: + return 0 + data = self._fileobj.read(n_requested) + n = len(data) + b[:n] = memoryview(data) + return n + + class ZipStore(Store): """ Store using a ZIP file. Parameters ---------- - path : str - Location of file. + path : str, Path, or IO[bytes] + Location of file, or an open binary file object. A file object must + support `read`, `seek`, and `tell`; objects that are not `io.IOBase` + instances (e.g. an `obstore` reader) are adapted automatically but + can only be used for reading (`mode="r"`). The file object must stay + open for the lifetime of the store, and operations that require a + filesystem location (`clear`, `move`, pickling) are not supported. mode : str, optional One of 'r' to read an existing file, 'w' to truncate and write a new file, 'a' to append to an existing file, or 'x' to exclusively create @@ -58,16 +112,17 @@ class ZipStore(Store): supports_deletes: bool = False supports_listing: bool = True - path: Path + path: Path | None compression: int allowZip64: bool _zf: zipfile.ZipFile _lock: threading.RLock + _fileobj: IO[bytes] | None def __init__( self, - path: Path | str, + path: Path | str | IO[bytes], *, mode: ZipStoreAccessModeLiteral = "r", read_only: bool | None = None, @@ -81,8 +136,28 @@ def __init__( if isinstance(path, str): path = Path(path) - assert isinstance(path, Path) - self.path = path # root? + if isinstance(path, Path): + self.path = path # root? + self._fileobj = None + else: + self.path = None + if not isinstance(path, io.IOBase): + if not all( + callable(getattr(path, attr, None)) for attr in ("read", "seek", "tell") + ): + raise TypeError( + f"expected a path or an open binary file object supporting " + f"read/seek/tell, got {type(path).__name__}" + ) + if mode != "r": + raise TypeError( + f"a file object that is not an io.IOBase instance can only be " + f"opened for reading (mode='r', got mode={mode!r})" + ) + # e.g. an obstore ReadableFile: readable and seekable, but + # not an io object and reads may not return bytes + path = io.BufferedReader(_RawReaderAdapter(path)) + self._fileobj = path self._zmode = mode self.compression = compression @@ -95,7 +170,7 @@ def _sync_open(self) -> None: self._lock = threading.RLock() self._zf = zipfile.ZipFile( - self.path, + self.path if self.path is not None else self._fileobj, # type: ignore[arg-type] mode=self._zmode, compression=self.compression, allowZip64=self.allowZip64, @@ -107,6 +182,13 @@ async def _open(self) -> None: self._sync_open() def __getstate__(self) -> dict[str, Any]: + if self.path is None: + # A path-backed store pickles its path and reopens the file on + # unpickling; an open file object cannot be serialized that way. + raise TypeError( + "cannot pickle a ZipStore backed by a file-like object; " + "construct the store from a path instead" + ) # We need a copy to not modify the state of the original store state = self.__dict__.copy() for attr in ["_zf", "_lock"]: @@ -120,6 +202,8 @@ def __setstate__(self, state: dict[str, Any]) -> None: def close(self) -> None: # docstring inherited + if not self._is_open: + return super().close() with self._lock: self._zf.close() @@ -128,6 +212,10 @@ async def clear(self) -> None: # docstring inherited with self._lock: self._check_writable() + if self.path is None: + raise NotImplementedError( + "clear() is not supported for a ZipStore backed by a file-like object" + ) self._zf.close() os.remove(self.path) self._zf = zipfile.ZipFile( @@ -135,13 +223,19 @@ async def clear(self) -> None: ) def __str__(self) -> str: + if self.path is None: + return f"zip://{self._fileobj!r}" return f"zip://{self.path}" def __repr__(self) -> str: return f"ZipStore('{self}')" def __eq__(self, other: object) -> bool: - return isinstance(other, type(self)) and self.path == other.path + return ( + isinstance(other, type(self)) + and self.path == other.path + and self._fileobj is other._fileobj + ) def _get( self, @@ -245,6 +339,8 @@ async def delete(self, key: str) -> None: async def exists(self, key: str) -> bool: # docstring inherited + if not self._is_open: + self._sync_open() with self._lock: try: self._zf.getinfo(key) @@ -255,6 +351,8 @@ async def exists(self, key: str) -> bool: async def list(self) -> AsyncIterator[str]: # docstring inherited + if not self._is_open: + self._sync_open() with self._lock: for key in self._zf.namelist(): yield key @@ -267,6 +365,8 @@ async def list_prefix(self, prefix: str) -> AsyncIterator[str]: async def list_dir(self, prefix: str) -> AsyncIterator[str]: # docstring inherited + if not self._is_open: + self._sync_open() prefix = prefix.rstrip("/") keys = self._zf.namelist() @@ -279,8 +379,8 @@ async def list_dir(self, prefix: str) -> AsyncIterator[str]: yield key else: for key in keys: - if key.startswith(prefix + "/") and key.strip("/") != prefix: - k = key.removeprefix(prefix + "/").split("/")[0] + if key.startswith(f"{prefix}/") and key.strip("/") != prefix: + k = key.removeprefix(f"{prefix}/").split("/")[0] if k not in seen: seen.add(k) yield k @@ -289,6 +389,10 @@ async def move(self, path: Path | str) -> None: """ Move the store to another path. """ + if self.path is None: + raise NotImplementedError( + "move() is not supported for a ZipStore backed by a file-like object" + ) if isinstance(path, str): path = Path(path) self.close() diff --git a/src/zarr/testing/__init__.py b/src/zarr/testing/__init__.py index 21a3572846..823c508052 100644 --- a/src/zarr/testing/__init__.py +++ b/src/zarr/testing/__init__.py @@ -1,16 +1,28 @@ import importlib.util import warnings +from typing import TYPE_CHECKING from zarr.errors import ZarrUserWarning if importlib.util.find_spec("pytest") is not None: from zarr.testing.store import StoreTests + from zarr.testing.utils import assert_bytes_equal else: warnings.warn( "pytest not installed, skipping test suite", category=ZarrUserWarning, stacklevel=2 ) -from zarr.testing.utils import assert_bytes_equal +if TYPE_CHECKING: + import pytest + + +def pytest_configure(config: "pytest.Config") -> None: + # The tests in zarr.testing are intended to be run by downstream projects. + # To allow those downstream projects to run with `--strict-markers`, we need + # to register an entry point with pytest11 and register our "plugin" with it, + # which just registers the markers used in zarr.testing + config.addinivalue_line("markers", "gpu: mark a test as requiring CuPy and GPU") + # TODO: import public buffer tests? diff --git a/src/zarr/testing/buffer.py b/src/zarr/testing/buffer.py index 6096ece2f8..f666801694 100644 --- a/src/zarr/testing/buffer.py +++ b/src/zarr/testing/buffer.py @@ -13,6 +13,8 @@ from collections.abc import Iterable from typing import Self + from zarr.abc.store import ByteRequest + __all__ = [ "NDBufferUsingTestNDArrayLike", @@ -72,6 +74,13 @@ async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None assert isinstance(value, TestBuffer) await super().set(key, value, byte_range) + def set_sync(self, key: str, value: Buffer) -> None: + # Synchronous counterpart of `set`, used by FusedCodecPipeline. Mirror the + # same buffer-type guard so the invariant holds whichever pipeline writes. + if "json" not in key: + assert isinstance(value, TestBuffer) + super().set_sync(key, value) + async def get( self, key: str, @@ -84,3 +93,18 @@ async def get( if ret is not None: assert isinstance(ret, prototype.buffer) return ret + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # Synchronous counterpart of `get`, used by FusedCodecPipeline. + if "json" not in key and prototype is not None: + assert prototype.buffer is TestBuffer + ret = super().get_sync(key=key, prototype=prototype, byte_range=byte_range) + if ret is not None and prototype is not None: + assert isinstance(ret, prototype.buffer) + return ret diff --git a/src/zarr/testing/conftest.py b/src/zarr/testing/conftest.py deleted file mode 100644 index 59c148e0ec..0000000000 --- a/src/zarr/testing/conftest.py +++ /dev/null @@ -1,9 +0,0 @@ -import pytest - - -def pytest_configure(config: pytest.Config) -> None: - # The tests in zarr.testing are intended to be run by downstream projects. - # To allow those downstream projects to run with `--strict-markers`, we need - # to register an entry point with pytest11 and register our "plugin" with it, - # which just registers the markers used in zarr.testing - config.addinivalue_line("markers", "gpu: mark a test as requiring CuPy and GPU") diff --git a/src/zarr/testing/stateful.py b/src/zarr/testing/stateful.py index 382f1467da..9105b8234e 100644 --- a/src/zarr/testing/stateful.py +++ b/src/zarr/testing/stateful.py @@ -1,7 +1,7 @@ import builtins import functools -from collections.abc import Callable -from typing import Any, TypeVar, cast +from collections.abc import Callable, Iterable +from typing import Any, cast import hypothesis.extra.numpy as npst import hypothesis.strategies as st @@ -18,28 +18,32 @@ import zarr from zarr import Array -from zarr.abc.store import Store +from zarr.abc.store import ( + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) from zarr.codecs.bytes import BytesCodec from zarr.core.buffer import Buffer, BufferPrototype, cpu, default_buffer_prototype from zarr.core.sync import SyncMixin from zarr.storage import LocalStore, MemoryStore +from zarr.testing.strategies import ( + arrays as zarr_arrays, +) from zarr.testing.strategies import ( basic_indices, chunk_paths, - dimension_names, key_ranges, node_names, - np_array_and_chunks, orthogonal_indices, ) from zarr.testing.strategies import keys as zarr_keys MAX_BINARY_SIZE = 100 -F = TypeVar("F", bound=Callable[..., Any]) - -def with_frequency(frequency: float) -> Callable[[F], F]: +def with_frequency[F: Callable[..., Any]](frequency: float) -> Callable[[F], F]: """This needs to be deterministic for hypothesis replaying""" def decorator(func: F) -> F: @@ -120,18 +124,11 @@ def add_group(self, name: str, data: DataObject) -> None: zarr.group(store=self.store, path=path) zarr.group(store=self.model, path=path) - @rule(data=st.data(), name=node_names, array_and_chunks=np_array_and_chunks()) - def add_array( - self, - data: DataObject, - name: str, - array_and_chunks: tuple[np.ndarray[Any, Any], tuple[int, ...]], - ) -> None: + @rule(data=st.data(), name=node_names) + def add_array(self, data: DataObject, name: str) -> None: # Handle possible case-insensitive file systems (e.g. MacOS) if isinstance(self.store, LocalStore): name = name.lower() - array, chunks = array_and_chunks - fill_value = data.draw(npst.from_dtype(array.dtype)) if self.all_groups: parent = data.draw(st.sampled_from(sorted(self.all_groups)), label="Array parent") else: @@ -140,21 +137,46 @@ def add_array( # TODO: support overwriting potentially by just skipping `self.can_add` path = f"{parent}/{name}".lstrip("/") assume(self.can_add(path)) - note(f"Adding array: path='{path}' shape={array.shape} chunks={chunks}") - for store in [self.store, self.model]: - zarr.array( - array, - chunks=chunks, - path=path, - store=store, - fill_value=fill_value, - zarr_format=3, - dimension_names=data.draw( - dimension_names(ndim=array.ndim), label="dimension names" - ), - # Chose bytes codec to avoid wasting time compressing the data being written - codecs=[BytesCodec()], - ) + + # Generate array on the model store using the arrays strategy + a = data.draw( + zarr_arrays( + stores=st.just(self.model), + paths=st.just(parent), + array_names=st.just(name), + zarr_formats=st.just(3), + compressors=st.just(BytesCodec()), + open_mode="a", + ), + label="generated array", + ) + note(f"Adding array: path='{path}' shape={a.shape} chunks={a.metadata.chunk_grid}") + + # Recreate the same array in the store under test + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata + + chunk_grid = a.metadata.chunk_grid + chunks_param: tuple[int, ...] | list[list[int]] + if isinstance(chunk_grid, RectilinearChunkGridMetadata): + chunks_param = [ + list(dim) if isinstance(dim, tuple) else [dim] for dim in chunk_grid.chunk_shapes + ] + elif isinstance(chunk_grid, RegularChunkGridMetadata): + chunks_param = chunk_grid.chunk_shape + else: + chunks_param = a.chunks + + root = zarr.open_group(store=self.store, mode="a") + arr = root.create_array( + path, + shape=a.shape, + chunks=chunks_param, + dtype=a.dtype, + fill_value=a.fill_value, + dimension_names=a.metadata.dimension_names, # type: ignore[union-attr] + compressors=None, + ) + arr[:] = a[:] self.all_arrays.add(path) @rule() @@ -289,7 +311,7 @@ def delete_dir(self, data: DataObject) -> None: matches = set() for node in self.all_groups | self.all_arrays: - if node.startswith(path): + if node == path or node.startswith(path + "/"): matches.add(node) self.all_groups = self.all_groups - matches self.all_arrays = self.all_arrays - matches @@ -443,7 +465,7 @@ def get(self, key: str, prototype: BufferPrototype) -> Buffer | None: return self._sync(self.store.get(key, prototype=prototype)) def get_partial_values( - self, key_ranges: builtins.list[Any], prototype: BufferPrototype + self, key_ranges: Iterable[Any], prototype: BufferPrototype ) -> builtins.list[Buffer | None]: return self._sync(self.store.get_partial_values(prototype=prototype, key_ranges=key_ranges)) @@ -459,6 +481,9 @@ def clear(self) -> None: def exists(self, key: str) -> bool: return self._sync(self.store.exists(key)) + def getsize_prefix(self, prefix: str) -> int: + return self._sync(self.store.getsize_prefix(prefix)) + def list_dir(self, prefix: str) -> None: raise NotImplementedError @@ -538,7 +563,9 @@ def get_partial_values(self, data: DataObject) -> None: key_ranges(keys=st.sampled_from(sorted(self.model.keys())), max_size=MAX_BINARY_SIZE) ) note(f"(get partial) {key_range=}") - obs_maybe = self.store.get_partial_values(key_range, self.prototype) + # Pass a one-shot generator rather than a list: stores (and wrappers such + # as LoggingStore) must not exhaust the iterable before using it. + obs_maybe = self.store.get_partial_values((kr for kr in key_range), self.prototype) observed = [] for obs in obs_maybe: @@ -548,9 +575,23 @@ def get_partial_values(self, data: DataObject) -> None: model_vals_ls = [] for key, byte_range in key_range: - start = byte_range.start - stop = byte_range.end - model_vals_ls.append(self.model[key][start:stop]) + # Independently model each ByteRequest variant (do NOT reuse the + # store's _normalize_byte_range_index helper, so this stays an + # independent oracle). Bounds may exceed the value length. + value = self.model[key] + n = len(value) + if byte_range is None: + expected = value[:] + elif isinstance(byte_range, RangeByteRequest): + expected = value[byte_range.start : byte_range.end] + elif isinstance(byte_range, OffsetByteRequest): + expected = value[byte_range.offset :] + elif isinstance(byte_range, SuffixByteRequest): + # "last suffix bytes"; suffix > n means the whole value. + expected = value[max(0, n - byte_range.suffix) :] + else: + raise AssertionError(f"unexpected byte_range {byte_range!r}") + model_vals_ls.append(expected) assert all( obs == exp.to_bytes() for obs, exp in zip(observed, model_vals_ls, strict=True) @@ -595,6 +636,21 @@ def exists(self, key: str) -> None: assert self.store.exists(key) == (key in self.model) + @precondition(lambda self: len(self.model.keys()) > 0) + @rule(data=st.data()) + def getsize_prefix(self, data: DataObject) -> None: + # Measure the size under the first path segment of some existing key. + # getsize_prefix(node) must count only keys under the directory "node/", + # not sibling keys that merely share the string prefix (e.g. measuring + # "a" must not include a sibling key "ab/..."). + key = data.draw(st.sampled_from(sorted(self.model.keys()))) + node = key.split("/")[0] + note(f"(getsize_prefix) {node=}") + + observed = self.store.getsize_prefix(node) + expected = sum(len(value) for k, value in self.model.items() if k.startswith(node + "/")) + assert observed == expected, (observed, expected, node) + @invariant() def check_paths_equal(self) -> None: note("Checking that paths are equal") diff --git a/src/zarr/testing/store.py b/src/zarr/testing/store.py index ce83715b86..4c948a783c 100644 --- a/src/zarr/testing/store.py +++ b/src/zarr/testing/store.py @@ -1,14 +1,17 @@ from __future__ import annotations import asyncio -import json import pickle +import time from abc import abstractmethod -from typing import TYPE_CHECKING, Generic, Self, TypeVar +from typing import TYPE_CHECKING, Self + +import numpy as np from zarr.storage import WrapperStore if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterable, Sequence from typing import Any from zarr.core.buffer.core import BufferPrototype @@ -33,31 +36,27 @@ __all__ = ["StoreTests"] -S = TypeVar("S", bound=Store) -B = TypeVar("B", bound=Buffer) - - -class StoreTests(Generic[S, B]): +class StoreTests[S: Store, B: Buffer]: store_cls: type[S] buffer_cls: type[B] @staticmethod def _require_get_sync(store: S) -> SupportsGetSync: - """Skip unless *store* implements :class:`SupportsGetSync`.""" + """Skip unless *store* implements [`SupportsGetSync`][zarr.abc.store.SupportsGetSync].""" if not isinstance(store, SupportsGetSync): pytest.skip("store does not implement SupportsGetSync") return store # type: ignore[unreachable] @staticmethod def _require_set_sync(store: S) -> SupportsSetSync: - """Skip unless *store* implements :class:`SupportsSetSync`.""" + """Skip unless *store* implements [`SupportsSetSync`][zarr.abc.store.SupportsSetSync].""" if not isinstance(store, SupportsSetSync): pytest.skip("store does not implement SupportsSetSync") return store # type: ignore[unreachable] @staticmethod def _require_delete_sync(store: S) -> SupportsDeleteSync: - """Skip unless *store* implements :class:`SupportsDeleteSync`.""" + """Skip unless *store* implements [`SupportsDeleteSync`][zarr.abc.store.SupportsDeleteSync].""" if not isinstance(store, SupportsDeleteSync): pytest.skip("store does not implement SupportsDeleteSync") return store # type: ignore[unreachable] @@ -116,7 +115,7 @@ def test_store_type(self, store: S) -> None: def test_store_eq(self, store: S, store_kwargs: dict[str, Any]) -> None: # check self equality - assert store == store + assert store == store # noqa: PLR0124 -- self-equality is the property under test # check store equality with same inputs # asserting this is important for being able to compare (de)serialized stores @@ -304,10 +303,16 @@ async def test_getsize(self, store: S, key: str, data: bytes) -> None: async def test_getsize_prefix(self, store: S) -> None: """ Test the result of store.getsize_prefix(). + + Includes a sibling key ("cc/0") that shares the string prefix "c" but + belongs to a different directory: getsize_prefix("c") must not count it, + i.e. the prefix is matched as a directory ("c/...") not a raw substring. """ data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") keys = ["c/0/0", "c/0/1", "c/1/0", "c/1/1"] - keys_values = [(k, data_buf) for k in keys] + # Sibling directory sharing the "c" string prefix; must be excluded. + sibling_keys = ["cc/0"] + keys_values = [(k, data_buf) for k in keys + sibling_keys] await store._set_many(keys_values) expected = len(data_buf) * len(keys) observed = await store.getsize_prefix("c") @@ -375,11 +380,19 @@ async def test_get_partial_values( for key, _ in key_ranges: await self.set(store, key, self.buffer_cls.from_bytes(bytes(key, encoding="utf-8"))) - # read back just part of it + # read back just part of it. Pass key_ranges as a one-shot generator + # (a valid Iterable per the method signature) to ensure stores and + # wrappers do not exhaust the iterable before handing it to the backend. observed_maybe = await store.get_partial_values( - prototype=default_buffer_prototype(), key_ranges=key_ranges + prototype=default_buffer_prototype(), + key_ranges=(kr for kr in key_ranges), ) + # One result must be returned per requested key range. Checking this + # explicitly guards against a store/wrapper exhausting the key_ranges + # iterable early and silently returning fewer (or no) results. + assert len(observed_maybe) == len(key_ranges) + observed: list[Buffer] = [] expected: list[Buffer] = [] @@ -387,8 +400,7 @@ async def test_get_partial_values( assert obs is not None observed.append(obs) - for idx in range(len(observed)): - key, byte_range = key_ranges[idx] + for key, byte_range in key_ranges: result = await store.get( key, prototype=default_buffer_prototype(), byte_range=byte_range ) @@ -453,8 +465,8 @@ async def test_list(self, store: S) -> None: prefix = "foo" data = self.buffer_cls.from_bytes(b"") store_dict = { - prefix + "/zarr.json": data, - **{prefix + f"/c/{idx}": data for idx in range(10)}, + f"{prefix}/zarr.json": data, + **{f"{prefix}/c/{idx}": data for idx in range(10)}, } await store._set_many(store_dict.items()) expected_sorted = sorted(store_dict.keys()) @@ -540,10 +552,10 @@ async def test_list_dir(self, store: S) -> None: await store._set_many(store_dict.items()) keys_observed = await _collect_aiterator(store.list_dir(root)) - keys_expected = {k.removeprefix(root + "/").split("/")[0] for k in store_dict} + keys_expected = {k.removeprefix(f"{root}/").split("/")[0] for k in store_dict} assert sorted(keys_observed) == sorted(keys_expected) - keys_observed = await _collect_aiterator(store.list_dir(root + "/")) + keys_observed = await _collect_aiterator(store.list_dir(f"{root}/")) assert sorted(keys_expected) == sorted(keys_observed) async def test_set_if_not_exists(self, store: S) -> None: @@ -562,46 +574,6 @@ async def test_set_if_not_exists(self, store: S) -> None: result = await store.get("k2", default_buffer_prototype()) assert result == new - async def test_get_bytes(self, store: S) -> None: - """ - Test that the get_bytes method reads bytes. - """ - data = b"hello world" - key = "zarr.json" - await self.set(store, key, self.buffer_cls.from_bytes(data)) - assert await store._get_bytes(key, prototype=default_buffer_prototype()) == data - with pytest.raises(FileNotFoundError): - await store._get_bytes("nonexistent_key", prototype=default_buffer_prototype()) - - def test_get_bytes_sync(self, store: S) -> None: - """ - Test that the get_bytes_sync method reads bytes. - """ - data = b"hello world" - key = "zarr.json" - sync(self.set(store, key, self.buffer_cls.from_bytes(data))) - assert store._get_bytes_sync(key, prototype=default_buffer_prototype()) == data - - async def test_get_json(self, store: S) -> None: - """ - Test that the get_json method reads json. - """ - data = {"foo": "bar"} - data_bytes = json.dumps(data).encode("utf-8") - key = "zarr.json" - await self.set(store, key, self.buffer_cls.from_bytes(data_bytes)) - assert await store._get_json(key, prototype=default_buffer_prototype()) == data - - def test_get_json_sync(self, store: S) -> None: - """ - Test that the get_json method reads json. - """ - data = {"foo": "bar"} - data_bytes = json.dumps(data).encode("utf-8") - key = "zarr.json" - sync(self.set(store, key, self.buffer_cls.from_bytes(data_bytes))) - assert store._get_json_sync(key, prototype=default_buffer_prototype()) == data - # ------------------------------------------------------------------- # Synchronous store methods (SupportsSyncStore protocol) # ------------------------------------------------------------------- @@ -648,6 +620,71 @@ def test_delete_sync_missing(self, store: S) -> None: # should not raise deleter.delete_sync("nonexistent_sync") + # ------------------------------------------------------------------- + # Sync/async parity laws + # ------------------------------------------------------------------- + # A store's sync and async methods must observe the same key the same + # way. This is stronger than the individual test_get_sync/test_set_sync/ + # test_delete_sync tests above: those write and read back through the + # *same* API (sync-only or, via `self.set`/`self.get`, bypassing the + # store entirely), so a sync method that skips logic the async method + # applies (e.g. a path prefix) can still pass them. These laws write + # through one API and observe through the other. + + @pytest.mark.parametrize("direction", ["set_async_get_sync", "set_sync_get_async"]) + async def test_sync_async_set_get_parity(self, store: S, direction: str) -> None: + setter = self._require_set_sync(store) + getter = self._require_get_sync(store) + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "parity_set_get" + if direction == "set_async_get_sync": + await store.set(key, data_buf) + result = getter.get_sync(key) + else: + setter.set_sync(key, data_buf) + result = await store.get(key, prototype=default_buffer_prototype()) + assert result is not None + assert_bytes_equal(result, data_buf) + + async def test_delete_sync_visible_to_async_get(self, store: S) -> None: + deleter = self._require_delete_sync(store) + if not store.supports_deletes: + pytest.skip("store does not support deletes") + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "parity_delete" + await store.set(key, data_buf) + deleter.delete_sync(key) + result = await store.get(key, prototype=default_buffer_prototype()) + assert result is None + + @pytest.mark.parametrize( + "byte_range", + [ + None, + RangeByteRequest(1, 4), + OffsetByteRequest(1), + SuffixByteRequest(1), + RangeByteRequest(10, 20), + ], + ids=["none", "range", "offset", "suffix", "range-past-eof"], + ) + async def test_get_sync_byte_range_parity( + self, store: S, byte_range: ByteRequest | None + ) -> None: + getter = self._require_get_sync(store) + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "parity_byte_range" + await store.set(key, data_buf) + sync_result = getter.get_sync(key, byte_range=byte_range) + async_result = await store.get( + key, prototype=default_buffer_prototype(), byte_range=byte_range + ) + if async_result is None: + assert sync_result is None + else: + assert sync_result is not None + assert_bytes_equal(sync_result, async_result) + class LatencyStore(WrapperStore[Store]): """ @@ -656,16 +693,37 @@ class LatencyStore(WrapperStore[Store]): performance testing. """ - get_latency: float - set_latency: float + _get_latency: float | tuple[float, float] + _set_latency: float | tuple[float, float] - def __init__(self, store: Store, *, get_latency: float = 0, set_latency: float = 0) -> None: - self.get_latency = float(get_latency) - self.set_latency = float(set_latency) - self._store = store + def __init__( + self, + store: Store, + *, + get_latency: float | tuple[float, float] = 0, + set_latency: float | tuple[float, float] = 0, + ) -> None: + super().__init__(store) + self._get_latency = get_latency if isinstance(get_latency, tuple) else float(get_latency) + self._set_latency = set_latency if isinstance(set_latency, tuple) else float(set_latency) + + @property + def get_latency(self) -> float: + if isinstance(self._get_latency, float): + return self._get_latency + return max(0.0, np.random.normal(loc=self._get_latency[0], scale=self._get_latency[1])) + + @property + def set_latency(self) -> float: + if isinstance(self._set_latency, float): + return self._set_latency + return max(0.0, np.random.normal(loc=self._set_latency[0], scale=self._set_latency[1])) def _with_store(self, store: Store) -> Self: - return type(self)(store, get_latency=self.get_latency, set_latency=self.set_latency) + # Pass the raw latency config, not the sampled `get_latency`/`set_latency` + # properties — sampling would freeze a `(loc, scale)` distribution into + # one fixed float on derived stores (e.g. via `with_read_only`). + return type(self)(store, get_latency=self._get_latency, set_latency=self._set_latency) async def set(self, key: str, value: Buffer) -> None: """ @@ -710,3 +768,76 @@ async def get( """ await asyncio.sleep(self.get_latency) return await self._store.get(key, prototype=prototype, byte_range=byte_range) + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + """Add latency to `get_sync`. + + Sleeps `self.get_latency` on the calling thread (the sync path runs on + worker threads, not the event loop) before delegating to the wrapped + store. + """ + time.sleep(self.get_latency) + return super().get_sync(key, prototype=prototype, byte_range=byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + """Add latency to `set_sync`. + + Sleeps `self.set_latency` on the calling thread (the sync path runs on + worker threads, not the event loop) before delegating to the wrapped + store. + """ + time.sleep(self.set_latency) + super().set_sync(key, value) + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int | None = None, + max_gap_bytes: int | None = None, + max_coalesced_bytes: int | None = None, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + """Byte-range reads built on `self.get`, so each fetch pays latency. + + Routes through the coalescing `Store.get_ranges` default instead of the + `WrapperStore` delegation, which would bypass this wrapper's `get` and + therefore the synthetic latency. `None` for a coalescing kwarg means + "use the `Store` default". + """ + kwargs: dict[str, int] = {} + if max_concurrency is not None: + kwargs["max_concurrency"] = max_concurrency + if max_gap_bytes is not None: + kwargs["max_gap_bytes"] = max_gap_bytes + if max_coalesced_bytes is not None: + kwargs["max_coalesced_bytes"] = max_coalesced_bytes + async for group in Store.get_ranges(self, key, byte_ranges, prototype=prototype, **kwargs): + yield group + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + """Partial-value reads built on `self.get`, so each fetch pays latency. + + Issues one `self.get` per `(key, byte_range)` pair instead of the + `WrapperStore` delegation, which would bypass this wrapper's `get` and + therefore the synthetic latency. + """ + return list( + await asyncio.gather( + *( + self.get(key, prototype=prototype, byte_range=byte_range) + for key, byte_range in key_ranges + ) + ) + ) diff --git a/src/zarr/testing/strategies.py b/src/zarr/testing/strategies.py index 330f220b56..6679dbcee4 100644 --- a/src/zarr/testing/strategies.py +++ b/src/zarr/testing/strategies.py @@ -1,3 +1,4 @@ +import itertools import math import sys from collections.abc import Callable, Mapping @@ -11,18 +12,26 @@ from hypothesis.strategies import SearchStrategy import zarr -from zarr.abc.store import RangeByteRequest, Store +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) from zarr.codecs.bytes import BytesCodec -from zarr.core.array import Array -from zarr.core.chunk_grids import RegularChunkGrid +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.sharding import SUBCHUNK_WRITE_ORDER, ShardingCodec, SubchunkWriteOrder +from zarr.codecs.zstd import ZstdCodec +from zarr.core.array import Array, CompressorsLike, SerializerLike from zarr.core.chunk_key_encodings import DefaultChunkKeyEncoding -from zarr.core.common import JSON, ZarrFormat +from zarr.core.common import JSON, AccessModeLiteral, ZarrFormat from zarr.core.dtype import get_data_type_from_native_dtype from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata +from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata from zarr.core.sync import sync from zarr.storage import MemoryStore, StoreLike -from zarr.storage._common import _dereference_path -from zarr.storage._utils import normalize_path +from zarr.storage._utils import _join_paths, normalize_path from zarr.types import AnyArray TrueOrFalse = Literal[True, False] @@ -123,11 +132,27 @@ def clear_store(x: Store) -> Store: @st.composite -def dimension_names(draw: st.DrawFn, *, ndim: int | None = None) -> list[None | str] | None: +def dimension_names(draw: st.DrawFn, *, ndim: int | None = None) -> list[str | None] | None: simple_text = st.text(zarr_key_chars, min_size=0) return draw(st.none() | st.lists(st.none() | simple_text, min_size=ndim, max_size=ndim)) # type: ignore[arg-type] +subchunk_write_orders: st.SearchStrategy[SubchunkWriteOrder] = st.sampled_from(SUBCHUNK_WRITE_ORDER) + +# Inner codec chains for a ShardingCodec. We MUST sample the uncompressed, +# single-BytesCodec configuration (no Zstd) — that is the only configuration in +# which the FusedCodecPipeline's vectorized whole-shard "bulk decode" fast path +# engages, so it is the only one that can exercise (and regress-guard) that path +# against arbitrary indexing. Freezing the inner codecs to [BytesCodec, ZstdCodec] +# silently disables the fast path under every property test. +sharding_inner_codecs: st.SearchStrategy[list[BytesCodec | ZstdCodec]] = st.sampled_from( + [ + [BytesCodec()], + [BytesCodec(), ZstdCodec()], + ] +) + + @st.composite def array_metadata( draw: st.DrawFn, @@ -140,11 +165,11 @@ def array_metadata( # separator = draw(st.sampled_from(['/', '\\'])) shape = draw(array_shapes()) ndim = len(shape) - chunk_shape = draw(array_shapes(min_dims=ndim, max_dims=ndim)) np_dtype = draw(dtypes()) dtype = get_data_type_from_native_dtype(np_dtype) fill_value = draw(npst.from_dtype(np_dtype)) if zarr_format == 2: + chunk_shape = draw(array_shapes(min_dims=ndim, max_dims=ndim, min_side=1)) return ArrayV2Metadata( shape=shape, chunks=chunk_shape, @@ -157,10 +182,11 @@ def array_metadata( compressor=None, ) else: + chunk_grid = draw(chunk_grids(shape=shape)) return ArrayV3Metadata( shape=shape, data_type=dtype, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), + chunk_grid=chunk_grid, fill_value=fill_value, attributes=draw(attributes), # type: ignore[arg-type] dimension_names=draw(dimension_names(ndim=ndim)), @@ -194,11 +220,17 @@ def chunk_shapes(draw: st.DrawFn, *, shape: tuple[int, ...]) -> tuple[int, ...]: # We want this strategy to shrink towards arrays with smaller number of chunks # 1. st.integers() shrinks towards smaller values. So we use that to generate number of chunks numchunks = draw( - st.tuples(*[st.integers(min_value=0 if size == 0 else 1, max_value=size) for size in shape]) + st.tuples( + *[ + st.integers(min_value=0 if size == 0 else 1, max_value=max(size, 1)) + for size in shape + ] + ) ) # 2. and now generate the chunks tuple + # Chunk sizes must be >= 1 per spec; for zero-extent dimensions use 1. chunks = tuple( - size // nchunks if nchunks > 0 else 0 + max(1, size // nchunks) if nchunks > 0 else 1 for size, nchunks in zip(shape, numchunks, strict=True) ) @@ -228,7 +260,7 @@ def np_array_and_chunks( draw: st.DrawFn, *, arrays: st.SearchStrategy[npt.NDArray[Any]] = numpy_arrays(), # noqa: B008 -) -> tuple[np.ndarray, tuple[int, ...]]: # type: ignore[type-arg] +) -> tuple[np.ndarray[Any, Any], tuple[int, ...]]: """A hypothesis strategy to generate small sized random arrays. Returns: a tuple of the array and a suitable random chunking for it. @@ -249,6 +281,8 @@ def arrays( arrays: st.SearchStrategy | None = None, attrs: st.SearchStrategy = attrs, zarr_formats: st.SearchStrategy = zarr_formats, + subchunk_write_orders: SearchStrategy[SubchunkWriteOrder] = subchunk_write_orders, + open_mode: AccessModeLiteral = "w", ) -> AnyArray: store = draw(stores, label="store") path = draw(paths, label="array parent") @@ -258,35 +292,70 @@ def arrays( if arrays is None: arrays = numpy_arrays(shapes=shapes) nparray = draw(arrays, label="array data") - chunk_shape = draw(chunk_shapes(shape=nparray.shape), label="chunk shape") - dim_names: None | list[str | None] = None - if zarr_format == 3 and all(c > 0 for c in chunk_shape): - shard_shape = draw( - st.none() | shard_shapes(shape=nparray.shape, chunk_shape=chunk_shape), - label="shard shape", - ) - dim_names = draw(dimension_names(ndim=nparray.ndim), label="dimension names") - else: - shard_shape = None + dim_names: list[str | None] | None = None + serializer: SerializerLike = "auto" + compressors_unsearched: CompressorsLike = "auto" + + # For v3 arrays, optionally use RectilinearChunkGridMetadata + chunk_grid_meta: RegularChunkGridMetadata | RectilinearChunkGridMetadata | None = None + # test that None works too. fill_value = draw(st.one_of([st.none(), npst.from_dtype(nparray.dtype)])) # compressor = draw(compressors) expected_attrs = {} if attributes is None else attributes - array_path = _dereference_path(path, name) - root = zarr.open_group(store, mode="w", zarr_format=zarr_format) - + array_path = _join_paths([path, name]) + root = zarr.open_group(store, mode=open_mode, zarr_format=zarr_format) + + # Convert chunk grid metadata to a form create_array accepts: + # - RegularChunkGridMetadata -> flat tuple of ints + # - RectilinearChunkGridMetadata -> nested list of ints (triggers rectilinear path) + # - v2 -> flat tuple of ints + chunks_param: tuple[int, ...] | list[list[int]] + shard_shape = None + dim_names = None + if zarr_format == 3: + chunk_grid_meta = draw(st.none() | chunk_grids(shape=nparray.shape), label="chunk grid") + dim_names = draw(dimension_names(ndim=nparray.ndim), label="dimension names") + if isinstance(chunk_grid_meta, RectilinearChunkGridMetadata): + chunks_param = [ + list(dim) if isinstance(dim, tuple) else [dim] + for dim in chunk_grid_meta.chunk_shapes + ] + elif isinstance(chunk_grid_meta, RegularChunkGridMetadata): + chunks_param = chunk_grid_meta.chunk_shape + else: + chunks_param = draw(chunk_shapes(shape=nparray.shape), label="chunk shape") + + if all(s > c > 1 for s, c in zip(nparray.shape, chunks_param, strict=True)): + shard_shape = draw( + st.none() | shard_shapes(shape=nparray.shape, chunk_shape=chunks_param), + label="shard shape", + ) + if shard_shape is not None: + subchunk_write_order = draw(subchunk_write_orders) + inner_codecs = draw(sharding_inner_codecs, label="sharding inner codecs") + serializer = ShardingCodec( + subchunk_write_order=subchunk_write_order, + codecs=inner_codecs, + index_codecs=[BytesCodec(), Crc32cCodec()], + chunk_shape=chunks_param, + ) + compressors_unsearched = None + else: + chunks_param = draw(chunk_shapes(shape=nparray.shape), label="chunk shape") a = root.create_array( array_path, shape=nparray.shape, - chunks=chunk_shape, + chunks=chunks_param, shards=shard_shape, dtype=nparray.dtype, attributes=attributes, - # compressor=compressor, # FIXME + compressors=compressors_unsearched, # FIXME fill_value=fill_value, dimension_names=dim_names, + serializer=serializer, ) assert isinstance(a, Array) @@ -294,11 +363,22 @@ def arrays( assert a.fill_value is not None assert a.name is not None assert a.path == normalize_path(array_path) - assert a.name == "/" + a.path + assert a.name == f"/{a.path}" assert isinstance(root[array_path], Array) assert nparray.shape == a.shape - assert chunk_shape == a.chunks - assert shard_shape == a.shards + + # Verify chunks — for rectilinear grids, .chunks raises + if zarr_format == 3: + assert shard_shape == a.shards + if isinstance(a.metadata.chunk_grid, RegularChunkGridMetadata): + assert a.metadata.chunk_grid.chunk_shape == ( + a.shards if shard_shape is not None else a.chunks + ) + assert shard_shape == a.shards + else: + assert isinstance(a.metadata.chunk_grid, RectilinearChunkGridMetadata) + assert shard_shape is None + assert a.basename == name, (a.basename, name) assert dict(a.attrs) == expected_attrs @@ -324,6 +404,122 @@ def simple_arrays( ) +@st.composite +def rectilinear_chunks(draw: st.DrawFn, *, shape: tuple[int, ...]) -> list[list[int]]: + """Generate valid rectilinear chunk shapes for a given array shape. + + Uses two modes per dimension: + - "expanded": random divider points create arbitrary chunk sizes + - "rle": uniform chunks with optional remainder, optionally shuffled + + Keeps max chunks per dimension <= 20 to avoid performance issues + in property tests. With higher dimensions, the total chunk count + grows multiplicatively. + """ + chunk_shapes: list[list[int]] = [] + for size in shape: + assert size > 0 + if size > 1: + mode = draw(st.sampled_from(["expanded", "rle"])) + if mode == "expanded": + event("rectilinear expanded") + max_chunks = min(size - 1, 20) + nchunks = draw(st.integers(min_value=1, max_value=max_chunks)) + dividers = sorted( + draw( + st.lists( + st.integers(min_value=1, max_value=size - 1), + min_size=nchunks - 1, + max_size=nchunks - 1, + unique=True, + ) + ) + ) + chunk_shapes.append( + [a - b for a, b in zip(dividers + [size], [0] + dividers, strict=False)] + ) + else: + # RLE mode: uniform chunks with optional remainder + max_chunk_size = min(size, 20) + chunk_size = draw(st.integers(min_value=1, max_value=max_chunk_size)) + n_full = size // chunk_size + remainder = size % chunk_size + chunks_list = [chunk_size] * n_full + if remainder > 0: + chunks_list.append(remainder) + # Optionally shuffle to create non-contiguous duplicate patterns + if draw(st.booleans()): + event("rectilinear rle shuffled") + chunks_list = draw(st.permutations(chunks_list)) + else: + event("rectilinear rle") + chunk_shapes.append(list(chunks_list)) + else: + chunk_shapes.append([1]) + return chunk_shapes + + +@st.composite +def chunk_grids( + draw: st.DrawFn, *, shape: tuple[int, ...] +) -> RegularChunkGridMetadata | RectilinearChunkGridMetadata: + """Generate either a RegularChunkGridMetadata or RectilinearChunkGridMetadata. + + This strategy depends on the global state of the config having rectilinear chunk grids enabled or not. + This means that it may be a possible source of a hypothesis FlakyStrategy error due dependence + on global state. However, in practice this seems unlikely to happen. + + This allows property tests to exercise both chunk grid types. + """ + # RectilinearChunkGridMetadata doesn't support zero-sized dimensions, + # so use RegularChunkGridMetadata if any dimension is 0 + if any(s == 0 for s in shape): + event("using RegularChunkGridMetadata (zero-sized dimensions)") + return RegularChunkGridMetadata(chunk_shape=draw(chunk_shapes(shape=shape))) + + if zarr.config.get("array.rectilinear_chunks") and draw(st.booleans()): + chunks = draw(rectilinear_chunks(shape=shape)) + event("using RectilinearChunkGridMetadata") + return RectilinearChunkGridMetadata(chunk_shapes=tuple(tuple(dim) for dim in chunks)) + else: + event("using RegularChunkGridMetadata") + return RegularChunkGridMetadata(chunk_shape=draw(chunk_shapes(shape=shape))) + + +# Rectilinear arrays need min_side >= 1 so every dimension has at least one element +_rectilinear_shapes = npst.array_shapes(max_dims=3, min_side=1, max_side=20) + + +@st.composite +def rectilinear_arrays( + draw: st.DrawFn, + *, + shapes: st.SearchStrategy[tuple[int, ...]] = _rectilinear_shapes, +) -> Any: + """Generate a zarr v3 array with rectilinear (variable) chunk grid.""" + shape = draw(shapes) + chunk_shapes = draw(rectilinear_chunks(shape=shape)) + + np_dtype = draw(dtypes()) + nparray = draw(numpy_arrays(shapes=st.just(shape), dtype=np_dtype)) + fill_value = draw(st.one_of([st.none(), npst.from_dtype(np_dtype)])) + dim_names = draw(dimension_names(ndim=len(shape))) + + store = MemoryStore() + with zarr.config.set({"array.rectilinear_chunks": True}): + a = zarr.create_array( + store=store, + shape=shape, + chunks=chunk_shapes, + dtype=np_dtype, + fill_value=fill_value, + dimension_names=dim_names, + ) + a[:] = nparray + + return a + + def is_negative_slice(idx: Any) -> bool: return isinstance(idx, slice) and idx.step is not None and idx.step < 0 @@ -416,29 +612,211 @@ def orthogonal_indices( return tuple(zindexer), tuple(np.broadcast_arrays(*npindexer)) +@st.composite +def block_indices( + draw: st.DrawFn, *, chunk_sizes: tuple[tuple[int, ...], ...] +) -> tuple[tuple[int | slice, ...], tuple[slice, ...]]: + """ + Strategy for block-selection indexers over a chunk grid. + + Block indexing is basic indexing applied to the block grid (the grid of + chunks), so each axis is drawn with ``basic_indices`` over that axis's chunk + count, mirroring how ``orthogonal_indices`` reuses ``basic_indices`` per + axis. ``chunk_sizes`` gives the per-chunk data sizes of the array's *outer* + (block) grid for every axis — i.e. ``Array.write_chunk_sizes``, the grid that + ``Array.blocks`` addresses (the shard grid when sharding is used). For + example ``(3, 3, 3, 1)`` for a length-10 axis with a regular chunk size of 3, + or the explicit edges of a rectilinear axis; ``nchunks`` for an axis is + ``len(chunk_sizes[axis])``. + + The array-space translation uses the cumulative sum of those sizes, matching + ``BlockIndexer``'s use of ``dim_grid.chunk_offset``. Because the sizes are + clipped to the array extent, the final offset equals the extent and the + translation is exact for regular (uniform), rectilinear, and sharded grids + alike. + + Block indexing only supports integers and step-1 slices whose start + references an existing chunk, so strided slices and slices starting at the + grid edge are filtered out. + + Returns + ------- + block_indexer + A per-axis tuple of ints / step-1 slices addressing whole chunks, + suitable for ``Array.blocks`` / ``get_block_selection`` / ``set_block_selection``. + array_indexer + The equivalent array-space selection (a tuple of slices) for indexing + the corresponding numpy array, used as the comparison oracle. + """ + + def supported(nchunks: int) -> Callable[[tuple[Any, ...]], bool]: + # Block indexing only accepts step-1 slices whose start references an + # existing chunk (a slice starting at nchunks raises, unlike numpy). + def predicate(value: tuple[Any, ...]) -> bool: + dim_sel = value[0] + if isinstance(dim_sel, slice): + if dim_sel.step not in (None, 1): + return False + start = dim_sel.start or 0 + return 0 <= (start + nchunks if start < 0 else start) < nchunks + return True + + return predicate + + block_indexer: list[int | slice] = [] + array_indexer: list[slice] = [] + for sizes in chunk_sizes: + nchunks = len(sizes) + # offsets[i] is the array-space start of chunk i; length nchunks + 1. + offsets = list(itertools.accumulate(sizes, initial=0)) + dim_strategy = ( + basic_indices(min_dims=1, shape=(nchunks,), allow_ellipsis=False) + # normalize bare ints / slices to a 1-tuple, skip the empty tuple + .map(lambda x: (x,) if not isinstance(x, tuple) else x) + .filter(bool) + .filter(supported(nchunks)) + ) + # basic_indices draws slices far more often than bare integers, so the + # integer (single-block) branch below would only be hit on rare draws. + # Union in an explicit integer so it is reliably exercised — keeping + # coverage deterministic under the derandomized ``ci`` Hypothesis profile. + (dim_sel,) = draw( + dim_strategy | st.integers(min_value=0, max_value=nchunks - 1).map(lambda i: (i,)) + ) + block_indexer.append(dim_sel) + if isinstance(dim_sel, slice): + start, stop, _ = dim_sel.indices(nchunks) + array_indexer.append(slice(offsets[start], offsets[stop])) + else: + block = dim_sel % nchunks + array_indexer.append(slice(offsets[block], offsets[block + 1])) + return tuple(block_indexer), tuple(array_indexer) + + +@st.composite +def block_test_arrays( + draw: st.DrawFn, +) -> tuple[Array[Any], np.ndarray[Any, Any]]: + """Draw an array for block-indexing property tests, with its source contents. + + Two arms, selected with equal probability: + + - **regular**: a regular chunk grid, optionally wrapped in sharding. + - **rectilinear**: a variable (rectilinear) chunk grid, always unsharded. + + Returns ``(zarray, nparray)``. The per-axis block sizes the oracle needs are + ``zarray.write_chunk_sizes`` — the array's *outer* (block / shard) grid, which + is exactly the grid ``Array.blocks`` addresses; the caller reads it directly. + """ + chunks: tuple[int, ...] | list[list[int]] + if draw(st.booleans()): + # regular arm, optionally sharded + nparray, chunks = draw( + np_array_and_chunks( + arrays=numpy_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1)) + ) + ) + # min_side=1 chunking guarantees shape // chunk >= 1 on every axis, which + # shard_shapes requires. + shards = draw(st.none() | shard_shapes(shape=nparray.shape, chunk_shape=chunks)) + event("block regular sharded" if shards is not None else "block regular unsharded") + rectilinear = False + else: + # rectilinear arm, always unsharded + event("block rectilinear") + shape = draw(_rectilinear_shapes) + chunks = draw(rectilinear_chunks(shape=shape)) + nparray = draw(numpy_arrays(shapes=st.just(shape), dtype=draw(dtypes()))) + shards, rectilinear = None, True + + store = draw(stores) + with zarr.config.set({"array.rectilinear_chunks": rectilinear}): + zarray = zarr.create_array( + store=store, + shape=nparray.shape, + chunks=chunks, + shards=shards, + dtype=nparray.dtype, + ) + zarray[...] = nparray + return zarray, nparray + + def key_ranges( keys: SearchStrategy[str] = node_names, max_size: int = sys.maxsize -) -> SearchStrategy[list[tuple[str, RangeByteRequest]]]: +) -> SearchStrategy[list[tuple[str, ByteRequest | None]]]: """ Function to generate key_ranges strategy for get_partial_values() returns list strategy w/ form:: - [(key, (range_start, range_end)), - (key, (range_start, range_end)),...] + [(key, byte_request), + (key, byte_request),...] + + where ``byte_request`` is ``None`` or any of the concrete ``ByteRequest`` + subtypes. The bounds are drawn independently of each value's length, so the + offsets/suffixes routinely exceed the data and exercise the clamping logic + in ``_normalize_byte_range_index``. """ - def make_request(start: int, length: int) -> RangeByteRequest: + def make_range(start: int, length: int) -> RangeByteRequest: return RangeByteRequest(start, end=min(start + length, max_size)) - byte_ranges = st.builds( - make_request, - start=st.integers(min_value=0, max_value=max_size), - length=st.integers(min_value=0, max_value=max_size), + bound = st.integers(min_value=0, max_value=max_size) + byte_ranges: SearchStrategy[ByteRequest | None] = st.one_of( + st.none(), + st.builds(make_range, start=bound, length=bound), + st.builds(OffsetByteRequest, offset=bound), + st.builds(SuffixByteRequest, suffix=bound), ) key_tuple = st.tuples(keys, byte_ranges) return st.lists(key_tuple, min_size=1, max_size=10) +@st.composite +def complex_rectilinear_arrays( + draw: st.DrawFn, + *, + stores: st.SearchStrategy[StoreLike] = stores, + paths: st.SearchStrategy[str] = paths(), # noqa: B008 + array_names: st.SearchStrategy = array_names, + attrs: st.SearchStrategy = attrs, +) -> tuple[npt.NDArray[Any], AnyArray]: + """Generate a rectilinear array with many small chunks. + + The shape is derived from the chunk edges (5-10 chunks per dim, + sizes 1-5), exercising higher chunk counts than ``rectilinear_arrays``. + """ + ndim = draw(st.integers(min_value=1, max_value=3)) + nchunks = draw(st.integers(min_value=5, max_value=10)) + dim_chunks = st.lists(st.integers(min_value=1, max_value=5), min_size=nchunks, max_size=nchunks) + chunk_shapes = draw(st.lists(dim_chunks, min_size=ndim, max_size=ndim)) + + shape = tuple(sum(dim) for dim in chunk_shapes) + nparray = draw(numpy_arrays(shapes=st.just(shape))) + dim_names = draw(dimension_names(ndim=ndim)) + fill_value = draw(st.one_of([st.none(), npst.from_dtype(nparray.dtype)])) + attributes = draw(attrs) + + store = draw(stores, label="store") + path = draw(paths, label="array parent") + name = draw(array_names, label="array name") + array_path = _join_paths([path, name]) + + root = zarr.open_group(store, mode="w", zarr_format=3) + with zarr.config.set({"array.rectilinear_chunks": True}): + a = root.create_array( + array_path, + shape=shape, + chunks=chunk_shapes, + dtype=nparray.dtype, + fill_value=fill_value, + dimension_names=dim_names, + attributes=attributes, + ) + a[:] = nparray + return nparray, a + + @st.composite def chunk_paths(draw: st.DrawFn, ndim: int, numblocks: tuple[int, ...], subset: bool = True) -> str: blockidx = draw( diff --git a/src/zarr/testing/utils.py b/src/zarr/testing/utils.py index 2a4c3e45c5..94f73f6798 100644 --- a/src/zarr/testing/utils.py +++ b/src/zarr/testing/utils.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, TypeVar, cast +from typing import TYPE_CHECKING, cast import pytest @@ -37,13 +37,10 @@ def has_cupy() -> bool: return False -T = TypeVar("T") - - gpu_mark = pytest.mark.gpu skip_if_no_gpu = pytest.mark.skipif(not has_cupy(), reason="CuPy not installed or no GPU available") # Decorator for GPU tests -def gpu_test(func: T) -> T: +def gpu_test[T](func: T) -> T: return cast(T, gpu_mark(skip_if_no_gpu(func))) diff --git a/src/zarr/types.py b/src/zarr/types.py index 38990982f9..8b77d344b2 100644 --- a/src/zarr/types.py +++ b/src/zarr/types.py @@ -1,23 +1,38 @@ -from typing import Any, TypeAlias +from typing import Any from zarr.core.array import Array, AsyncArray +from zarr.core.common import JSON, ZarrFormat +from zarr.core.dtype.common import DTypeConfig_V2, DTypeJSON from zarr.core.metadata.v2 import ArrayV2Metadata from zarr.core.metadata.v3 import ArrayV3Metadata -AnyAsyncArray: TypeAlias = AsyncArray[Any] +type AnyAsyncArray = AsyncArray[Any] """A Zarr format 2 or 3 `AsyncArray`""" -AsyncArrayV2: TypeAlias = AsyncArray[ArrayV2Metadata] +type AsyncArrayV2 = AsyncArray[ArrayV2Metadata] """A Zarr format 2 `AsyncArray`""" -AsyncArrayV3: TypeAlias = AsyncArray[ArrayV3Metadata] +type AsyncArrayV3 = AsyncArray[ArrayV3Metadata] """A Zarr format 3 `AsyncArray`""" -AnyArray: TypeAlias = Array[Any] +type AnyArray = Array[Any] """A Zarr format 2 or 3 `Array`""" -ArrayV2: TypeAlias = Array[ArrayV2Metadata] +type ArrayV2 = Array[ArrayV2Metadata] """A Zarr format 2 `Array`""" -ArrayV3: TypeAlias = Array[ArrayV3Metadata] +type ArrayV3 = Array[ArrayV3Metadata] """A Zarr format 3 `Array`""" + +__all__ = ( + "JSON", + "AnyArray", + "AnyAsyncArray", + "ArrayV2", + "ArrayV3", + "AsyncArrayV2", + "AsyncArrayV3", + "DTypeConfig_V2", + "DTypeJSON", + "ZarrFormat", +) diff --git a/tests/benchmarks/test_e2e.py b/tests/benchmarks/test_e2e.py index 65d0e65ac9..9720778d8f 100644 --- a/tests/benchmarks/test_e2e.py +++ b/tests/benchmarks/test_e2e.py @@ -4,51 +4,162 @@ from __future__ import annotations -from typing import TYPE_CHECKING +import os +import platform +import subprocess +import warnings +from functools import lru_cache +from operator import getitem, setitem +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np +import pytest +import zarr from tests.benchmarks.common import Layout +from zarr import create_array +from zarr.core.config import config as zarr_config +from zarr.testing.store import LatencyStore + + +def clear_cache() -> None: + """Drop the OS page cache between benchmark rounds. + + Requires passwordless sudo, so it is opt-in: set `ZARR_BENCHMARK_CLEAR_CACHE=1` + to enable it (as the benchmark CI jobs do). By default this is a no-op, so a + plain `pytest` run never prompts for a sudo password (see issue #4199). + `sudo -n` guarantees we fail instead of blocking on a password prompt even + when the variable is set. + """ + if os.environ.get("ZARR_BENCHMARK_CLEAR_CACHE", "") not in ("1", "true"): + return + if platform.system() == "Darwin": + subprocess.call(["sync"]) + subprocess.call(["sudo", "-n", "purge"]) + elif platform.system() == "Linux": + subprocess.call(["sudo", "-n", "sh", "-c", "sync; echo 3 > /proc/sys/vm/drop_caches"]) + else: + warnings.warn( + f"ZARR_BENCHMARK_CLEAR_CACHE is set but cache clearing is not supported on " + f"{platform.system()}; skipping.", + stacklevel=2, + ) + if TYPE_CHECKING: + from collections.abc import Callable, Iterator + from types import EllipsisType + from pytest_benchmark.fixture import BenchmarkFixture from zarr.abc.store import Store from zarr.core.common import NamedConfig -from operator import getitem, setitem -from typing import Any, Literal -import pytest -from zarr import create_array +@lru_cache +def _data(shape: tuple[int]) -> np.ndarray: + n = shape[0] + period = 256 + noise_level = 1 + pattern = (np.sin(np.linspace(0, 2 * np.pi, period)) * 50 + 128).round().astype(np.uint8) + data = np.tile(pattern, int(np.ceil(n / period)))[:n].astype(np.int16) + rng = np.random.default_rng(0) + data += rng.integers(-noise_level, noise_level + 1, size=n, dtype=np.int16) + return np.clip(data, 0, 255).astype(np.uint8) -CompressorName = Literal["gzip"] | None + +CompressorName = Literal["zstd"] | None compressors: dict[CompressorName, NamedConfig[Any, Any] | None] = { None: None, - "gzip": {"name": "gzip", "configuration": {"level": 1}}, + # Default v3 + "zstd": {"name": "zstd", "configuration": {"level": 0, "checksum": False}}, } layouts: tuple[Layout, ...] = ( # No shards, just 1000 chunks - Layout(shape=(1_000_000,), chunks=(1000,), shards=None), + Layout(shape=(100_000_000,), chunks=(100_000,), shards=None), # 1:1 chunk:shard shape, should measure overhead of sharding - Layout(shape=(1_000_000,), chunks=(1000,), shards=(1000,)), - # One shard with all the chunks, should measure overhead of handling inner shard chunks - Layout(shape=(1_000_000,), chunks=(100,), shards=(10000 * 100,)), + Layout(shape=(100_000_000,), chunks=(100_000,), shards=(100_000,)), + # One shard with all the chunks, should measure over/under-head of handling inner shard chunks + Layout(shape=(100_000_000,), chunks=(100_000,), shards=(100_000 * 1_000,)), + # Mixed layout balancing inner vs. outer concurrency (likely the most real-world case) + Layout(shape=(1_000_000_000,), chunks=(100_000,), shards=(100_000 * 100,)), ) +_PIPELINE_SETTINGS = { + "batched": {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"}, + "fused_full_threaded": { + "codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline", + "codec_pipeline.max_workers": None, + }, + "fused_single_threaded": { + "codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline", + "codec_pipeline.max_workers": 1, + }, +} + +_LATENCY_VALUES = (0, 0.03) + + +@pytest.fixture(params=_LATENCY_VALUES, ids=lambda v: f"latency={v}") +def latency(request: pytest.FixtureRequest) -> float: + return request.param # type: ignore[no-any-return] + + +@pytest.fixture +def bench_store(store: Store, latency: float, request: pytest.FixtureRequest) -> Store: + """Wraps the underlying store in LatencyStore when latency > 0. + + Local-store cases skip nonzero latency — synthetic latency on top of + a real LocalStore is double-counting; latency simulation only applies + to the in-process memory store. + """ + callspec = getattr(request.node, "callspec", None) + store_kind = callspec.params.get("store", "memory") if callspec is not None else "memory" + if latency > 0: + if store_kind == "local": + pytest.skip("latency injection only applies to in-memory store") + return LatencyStore( + store, get_latency=(latency, latency * 1.2), set_latency=(latency, latency * 1.2) + ) + if store_kind == "memory": + pytest.skip("memory store doesn't offer much over local without latency") + return store + + +@pytest.fixture(params=["batched"]) # , "fused_full_threaded", "fused_single_threaded"]) +def pipeline(request: pytest.FixtureRequest) -> Iterator[str]: + """Set ``codec_pipeline.path`` for the duration of the benchmark. + + Yields the pipeline name so each parametrize cell has a distinct + benchmark id. + """ + name = request.param + with zarr_config.set(_PIPELINE_SETTINGS[name]): + yield name + -@pytest.mark.parametrize("compression_name", [None, "gzip"]) +@pytest.mark.parametrize( + "get_data", [lambda shape: 1, lambda shape: _data(shape)], ids=["repeated", "semi_random"] +) +@pytest.mark.parametrize("compression_name", ["zstd", None]) @pytest.mark.parametrize("layout", layouts, ids=str) -@pytest.mark.parametrize("store", ["memory", "local"], indirect=["store"]) +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) def test_write_array( - store: Store, layout: Layout, compression_name: CompressorName, benchmark: BenchmarkFixture + bench_store: Store, + layout: Layout, + compression_name: CompressorName, + pipeline: str, + benchmark: BenchmarkFixture, + get_data: Callable[[tuple[int]], np.ndarray | int], ) -> None: """ Test the time required to fill an array with a single value """ arr = create_array( - store, + bench_store, dtype="uint8", shape=layout.shape, chunks=layout.chunks, @@ -57,20 +168,72 @@ def test_write_array( fill_value=0, ) - benchmark(setitem, arr, Ellipsis, 1) + def setup() -> tuple[tuple[zarr.Array, EllipsisType, int | np.ndarray], dict]: # type: ignore[type-arg] + clear_cache() + return (arr, Ellipsis, get_data(layout.shape)), {} # type: ignore[arg-type] + benchmark.pedantic(setitem, setup=setup, rounds=3) # type: ignore[no-untyped-call] -@pytest.mark.parametrize("compression_name", [None, "gzip"]) + +@pytest.mark.parametrize( + "get_data", [lambda shape: 1, lambda shape: _data(shape)], ids=["repeated", "semi_random"] +) +@pytest.mark.parametrize("compression_name", ["zstd", None]) @pytest.mark.parametrize("layout", layouts, ids=str) -@pytest.mark.parametrize("store", ["memory", "local"], indirect=["store"]) +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) def test_read_array( - store: Store, layout: Layout, compression_name: CompressorName, benchmark: BenchmarkFixture + bench_store: Store, + layout: Layout, + compression_name: CompressorName, + pipeline: str, + benchmark: BenchmarkFixture, + get_data: Callable[[tuple[int]], np.ndarray | int], ) -> None: """ - Test the time required to fill an array with a single value + Test the time required to read the entirety of an array + """ + arr = create_array( + bench_store, + dtype="uint8", + shape=layout.shape, + chunks=layout.chunks, + shards=layout.shards, + compressors=compressors[compression_name], # type: ignore[arg-type] + fill_value=0, + ) + arr[:] = get_data(layout.shape) # type: ignore[arg-type] + + def setup() -> tuple[tuple[zarr.Array, EllipsisType], dict]: # type: ignore[type-arg] + clear_cache() + return (arr, Ellipsis), {} + + benchmark.pedantic(getitem, setup=setup, rounds=3) # type: ignore[no-untyped-call] + + +_CONCURRENT_READ_THREADS = 8 +_concurrent_layout = Layout(shape=(64_000_000,), chunks=(4_000_000,), shards=None) + + +@pytest.mark.parametrize("pipeline", ["batched", "fused_full_threaded"], indirect=True) +@pytest.mark.parametrize("compression_name", ["zstd", None]) +@pytest.mark.parametrize("store", ["local"], indirect=["store"]) +def test_read_array_concurrent( + bench_store: Store, + compression_name: CompressorName, + pipeline: str, + benchmark: BenchmarkFixture, +) -> None: + """Dask-style access: several user threads each reading one chunk per call. + + All sync-API calls are serviced by the one global event loop, so this + measures how much of each read's IO+compute the pipeline runs while + holding the loop: anything inline serializes the readers. """ + from concurrent.futures import ThreadPoolExecutor + + layout = _concurrent_layout arr = create_array( - store, + bench_store, dtype="uint8", shape=layout.shape, chunks=layout.chunks, @@ -78,5 +241,18 @@ def test_read_array( compressors=compressors[compression_name], # type: ignore[arg-type] fill_value=0, ) - arr[:] = 1 - benchmark(getitem, arr, Ellipsis) + arr[:] = _data(layout.shape) + selections = [ + slice(start, start + layout.chunks[0]) + for start in range(0, layout.shape[0], layout.chunks[0]) + ] + + def read_all_chunks_concurrently() -> None: + with ThreadPoolExecutor(max_workers=_CONCURRENT_READ_THREADS) as executor: + list(executor.map(lambda sel: arr[sel], selections)) + + def setup() -> tuple[tuple[()], dict]: # type: ignore[type-arg] + clear_cache() + return (), {} + + benchmark.pedantic(read_all_chunks_concurrently, setup=setup, rounds=3) # type: ignore[no-untyped-call] diff --git a/tests/benchmarks/test_indexing.py b/tests/benchmarks/test_indexing.py index 385a85b5b5..c9b80f9ff6 100644 --- a/tests/benchmarks/test_indexing.py +++ b/tests/benchmarks/test_indexing.py @@ -74,7 +74,7 @@ def test_sharded_morton_indexing( The Morton order cache is cleared before each iteration to measure the full computation cost. """ - from zarr.core.indexing import _morton_order, _morton_order_keys + from zarr.core.indexing import _morton_order, morton_order_coords # Create array where each shard contains many small chunks # e.g., shards=(32,32,32) with chunks=(2,2,2) means 16x16x16 = 4096 chunks per shard @@ -98,7 +98,7 @@ def test_sharded_morton_indexing( def read_with_cache_clear() -> None: _morton_order.cache_clear() - _morton_order_keys.cache_clear() + morton_order_coords.cache_clear() getitem(data, indexer) benchmark(read_with_cache_clear) @@ -126,7 +126,7 @@ def test_sharded_morton_indexing_large( the Morton order computation a more significant portion of total time. The Morton order cache is cleared before each iteration. """ - from zarr.core.indexing import _morton_order, _morton_order_keys + from zarr.core.indexing import _morton_order, morton_order_coords # 1x1x1 chunks means chunks_per_shard equals shard shape shape = tuple(s * 2 for s in shards) # 2 shards per dimension @@ -149,7 +149,7 @@ def test_sharded_morton_indexing_large( def read_with_cache_clear() -> None: _morton_order.cache_clear() - _morton_order_keys.cache_clear() + morton_order_coords.cache_clear() getitem(data, indexer) benchmark(read_with_cache_clear) @@ -169,7 +169,7 @@ def test_sharded_morton_single_chunk( computing the full Morton order, making the optimization impact clear. The Morton order cache is cleared before each iteration. """ - from zarr.core.indexing import _morton_order, _morton_order_keys + from zarr.core.indexing import _morton_order, morton_order_coords # 1x1x1 chunks means chunks_per_shard equals shard shape shape = tuple(s * 2 for s in shards) # 2 shards per dimension @@ -192,13 +192,13 @@ def test_sharded_morton_single_chunk( def read_with_cache_clear() -> None: _morton_order.cache_clear() - _morton_order_keys.cache_clear() + morton_order_coords.cache_clear() getitem(data, indexer) benchmark(read_with_cache_clear) -# Benchmark for morton_order_iter directly (no I/O) +# Benchmark for morton_order_coords directly (no I/O) morton_iter_shapes = ( (8, 8, 8), # 512 elements (power-of-2) (10, 10, 10), # 1000 elements (non-power-of-2) @@ -211,23 +211,23 @@ def read_with_cache_clear() -> None: @pytest.mark.parametrize("shape", morton_iter_shapes, ids=str) -def test_morton_order_iter( +def test_morton_order( shape: tuple[int, ...], benchmark: BenchmarkFixture, ) -> None: - """Benchmark morton_order_iter directly without I/O. + """Benchmark morton_order_coords directly without I/O. This isolates the Morton order computation to measure the optimization impact without array read/write overhead. The cache is cleared before each iteration. """ - from zarr.core.indexing import _morton_order, _morton_order_keys, morton_order_iter + from zarr.core.indexing import _morton_order, morton_order_coords def compute_morton_order() -> None: _morton_order.cache_clear() - _morton_order_keys.cache_clear() - # Consume the iterator to force computation - list(morton_order_iter(shape)) + morton_order_coords.cache_clear() + # Build the full sequence to force computation + list(morton_order_coords(shape)) benchmark(compute_morton_order) @@ -250,7 +250,12 @@ def test_sharded_morton_write_single_chunk( """ import numpy as np - from zarr.core.indexing import _morton_order, _morton_order_keys + from zarr.core.indexing import ( + _lexicographic_order, + _morton_order, + lexicographic_order_coords, + morton_order_coords, + ) # 1x1x1 chunks means chunks_per_shard equals shard shape shape = tuple(s * 2 for s in shards) # 2 shards per dimension @@ -272,8 +277,67 @@ def test_sharded_morton_write_single_chunk( indexer = (slice(1), slice(1), slice(1)) def write_with_cache_clear() -> None: + # Clear every coordinate cache the write path touches, not just morton: + # the sharded write also builds the lexicographic grid (dict.fromkeys / + # to_dict_vectorized), so a partial clear would leave that path warm and + # under-report the cold build cost. _morton_order.cache_clear() - _morton_order_keys.cache_clear() + morton_order_coords.cache_clear() + _lexicographic_order.cache_clear() + lexicographic_order_coords.cache_clear() data[indexer] = write_data benchmark(write_with_cache_clear) + + +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize("shards", large_morton_shards, ids=str) +def test_sharded_morton_write_single_chunk_warm_cache( + store: Store, + shards: tuple[int, ...], + benchmark: BenchmarkFixture, +) -> None: + """Benchmark a single-chunk shard write with the chunk-order cache warm. + + Unlike ``test_sharded_morton_write_single_chunk``, this does NOT clear the + order cache between iterations: it warms the cache once, then repeatedly + writes the same single chunk. This isolates the amortized per-write cost the + cache exists to optimize — the regime where the coordinate grid was already + built (by an earlier write to this shard, or to any same-shaped shard) and is + reused rather than rebuilt. Repeated writes to one shard and writes spread + across many same-shaped shards exercise that cache reuse identically. + + This is the regime the cold benchmark cannot see. A regression that rebuilds + the per-shard coordinate tuples on every write (rather than reusing the + cached sequence) is invisible to the cold benchmark but shows up here. + """ + import numpy as np + + from zarr.core.indexing import _morton_order, morton_order_coords + + shape = tuple(s * 2 for s in shards) # 2 shards per dimension + chunks = (1,) * 3 # 1x1x1 chunks: chunks_per_shard = shards + + data = create_array( + store=store, + shape=shape, + dtype="uint8", + chunks=chunks, + shards=shards, + compressors=None, + filters=None, + fill_value=0, + ) + + write_data = np.ones((1, 1, 1), dtype="uint8") + indexer = (slice(1), slice(1), slice(1)) + + # Warm the cache once up front; the timed writes then hit the warm path. + _morton_order.cache_clear() + morton_order_coords.cache_clear() + data[indexer] = write_data + + def write_warm() -> None: + data[indexer] = write_data + + benchmark(write_warm) diff --git a/tests/conftest.py b/tests/conftest.py index 23a1e87d0a..7ccf9958e7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,6 +3,7 @@ import math import os import pathlib +import re import sys from collections.abc import Mapping, Sequence from dataclasses import dataclass, field @@ -16,16 +17,22 @@ import zarr.registry from zarr import AsyncGroup, config from zarr.abc.store import Store -from zarr.codecs.sharding import ShardingCodec, ShardingCodecIndexLocation +from zarr.codecs.sharding import IndexLocation, ShardingCodec from zarr.core.array import ( _parse_chunk_encoding_v2, _parse_chunk_encoding_v3, _parse_chunk_key_encoding, ) -from zarr.core.chunk_grids import RegularChunkGrid, _auto_partition +from zarr.core.chunk_grids import ( + SHARDED_INNER_CHUNK_MAX_BYTES, + as_regular_shape, + guess_chunks, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) from zarr.core.common import ( JSON, - DimensionNames, + DimensionNamesLike, MemoryOrder, ShapeLike, ZarrFormat, @@ -37,17 +44,16 @@ ) from zarr.core.dtype.common import HasItemSize from zarr.core.metadata.v2 import ArrayV2Metadata -from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.core.metadata.v3 import ArrayV3Metadata, create_chunk_grid_metadata from zarr.core.sync import sync from zarr.storage import FsspecStore, LocalStore, MemoryStore, StorePath, ZipStore from zarr.testing.store import LatencyStore if TYPE_CHECKING: from collections.abc import Generator + from contextlib import AbstractContextManager from typing import Any, Literal - from _pytest.compat import LEGACY_PATH - from zarr.abc.codec import Codec from zarr.core.array import CompressorsLike, FiltersLike, SerializerLike, ShardsLike from zarr.core.chunk_key_encodings import ( @@ -58,6 +64,38 @@ from zarr.core.dtype.wrapper import ZDType +@dataclass(frozen=True) +class Expect[TIn, TOut]: + """A test case with explicit input, expected output, and a human-readable id.""" + + input: TIn + output: TOut + id: str + + +@dataclass(frozen=True) +class ExpectFail[TIn]: + """A test case that should raise an exception. + + `msg` is a regex matched against the exception text (pytest's native + `match=` semantics). Leave it `None` to assert only the exception type. Set + `escape=True` when `msg` is a literal that contains regex metacharacters + such as `(`, `[`, or `.`; `escape` has no effect when `msg` is `None`. + """ + + input: TIn + exception: type[Exception] + id: str + msg: str | None = None + escape: bool = False + + def raises(self) -> AbstractContextManager[pytest.ExceptionInfo[Exception]]: + if self.msg is None: + return pytest.raises(self.exception) + pattern = re.escape(self.msg) if self.escape else self.msg + return pytest.raises(self.exception, match=pattern) + + async def parse_store( store: Literal["local", "memory", "fsspec", "zip", "memory_get_latency"], path: str ) -> LocalStore | MemoryStore | FsspecStore | ZipStore | LatencyStore: @@ -68,9 +106,9 @@ async def parse_store( if store == "fsspec": return await FsspecStore.open(url=path) if store == "zip": - return await ZipStore.open(path + "/zarr.zip", mode="w") + return await ZipStore.open(f"{path}/zarr.zip", mode="w") if store == "memory_get_latency": - return LatencyStore(MemoryStore(), get_latency=0.0001, set_latency=0) + return LatencyStore(MemoryStore(), get_latency=0.0001, set_latency=0.0) raise AssertionError @@ -81,14 +119,14 @@ def path_type(request: pytest.FixtureRequest) -> Any: # todo: harmonize this with local_store fixture @pytest.fixture -async def store_path(tmpdir: LEGACY_PATH) -> StorePath: - store = await LocalStore.open(str(tmpdir)) +async def store_path(tmp_path: pathlib.Path) -> StorePath: + store = await LocalStore.open(str(tmp_path)) return StorePath(store) @pytest.fixture -async def local_store(tmpdir: LEGACY_PATH) -> LocalStore: - return await LocalStore.open(str(tmpdir)) +async def local_store(tmp_path: pathlib.Path) -> LocalStore: + return await LocalStore.open(str(tmp_path)) @pytest.fixture @@ -102,29 +140,30 @@ async def memory_store() -> MemoryStore: @pytest.fixture -async def zip_store(tmpdir: LEGACY_PATH) -> ZipStore: - return await ZipStore.open(str(tmpdir / "zarr.zip"), mode="w") +async def zip_store(tmp_path: pathlib.Path) -> ZipStore: + return await ZipStore.open(str(tmp_path / "zarr.zip"), mode="w") @pytest.fixture -async def store(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> Store: +async def store(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: param = request.param - return await parse_store(param, str(tmpdir)) + return await parse_store(param, str(tmp_path)) @pytest.fixture -async def store2(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> Store: +async def store2(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: """Fixture to create a second store for testing copy operations between stores""" param = request.param - store2_path = tmpdir.mkdir("store2") + store2_path = tmp_path / "store2" + store2_path.mkdir() return await parse_store(param, str(store2_path)) @pytest.fixture(params=["local", "memory", "zip"]) -def sync_store(request: pytest.FixtureRequest, tmp_path: LEGACY_PATH) -> Store: +def sync_store(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: result = sync(parse_store(request.param, str(tmp_path))) if not isinstance(result, Store): - raise TypeError("Wrong store class returned by test fixture! got " + result + " instead") + raise TypeError(f"Wrong store class returned by test fixture! got {result} instead") return result @@ -136,10 +175,10 @@ class AsyncGroupRequest: @pytest.fixture -async def async_group(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> AsyncGroup: +async def async_group(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> AsyncGroup: param: AsyncGroupRequest = request.param - store = await parse_store(param.store, str(tmpdir)) + store = await parse_store(param.store, str(tmp_path)) return await AsyncGroup.from_store( store, attributes=param.attributes, @@ -313,7 +352,7 @@ def create_array_metadata( zarr_format: ZarrFormat, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, ) -> ArrayV2Metadata | ArrayV3Metadata: """ Create array metadata @@ -326,10 +365,18 @@ def create_array_metadata( item_size = 1 if isinstance(dtype_parsed, HasItemSize): item_size = dtype_parsed.item_size - shard_shape_parsed, chunk_shape_parsed = _auto_partition( + if chunks == "auto": + chunks_normalized = guess_chunks( + shape_parsed, + item_size, + max_bytes=SHARDED_INNER_CHUNK_MAX_BYTES if shards is not None else None, + ) + else: + chunks_normalized = normalize_chunks_nd(chunks, shape_parsed) + outer_chunks, inner = resolve_outer_and_inner_chunks( array_shape=shape_parsed, + chunks=chunks_normalized, shard_shape=shards, - chunk_shape=chunks, item_size=item_size, ) @@ -337,7 +384,6 @@ def create_array_metadata( order_parsed = zarr_config.get("array.order") else: order_parsed = order - chunks_out: tuple[int, ...] if zarr_format == 2: filters_parsed, compressor_parsed = _parse_chunk_encoding_v2( @@ -347,7 +393,7 @@ def create_array_metadata( return ArrayV2Metadata( shape=shape_parsed, dtype=dtype_parsed, - chunks=chunk_shape_parsed, + chunks=as_regular_shape(outer_chunks), order=order_parsed, dimension_separator=chunk_key_encoding_parsed.separator, fill_value=fill_value, @@ -365,32 +411,30 @@ def create_array_metadata( sub_codecs: tuple[Codec, ...] = (*array_array, array_bytes, *bytes_bytes) codecs_out: tuple[Codec, ...] - if shard_shape_parsed is not None: - index_location = None + if inner is not None: + inner_chunks_flat = as_regular_shape(inner.outer_chunks) + index_location: IndexLocation = "end" if isinstance(shards, dict): - index_location = ShardingCodecIndexLocation(shards.get("index_location", None)) - if index_location is None: - index_location = ShardingCodecIndexLocation.end + index_location = cast("IndexLocation", shards.get("index_location", "end")) sharding_codec = ShardingCodec( - chunk_shape=chunk_shape_parsed, + chunk_shape=inner_chunks_flat, codecs=sub_codecs, index_location=index_location, ) + validation_grid = create_chunk_grid_metadata(outer_chunks) sharding_codec.validate( - shape=chunk_shape_parsed, + shape=inner_chunks_flat, dtype=dtype_parsed, - chunk_grid=RegularChunkGrid(chunk_shape=shard_shape_parsed), + chunk_grid=validation_grid, ) codecs_out = (sharding_codec,) - chunks_out = shard_shape_parsed else: - chunks_out = chunk_shape_parsed codecs_out = sub_codecs return ArrayV3Metadata( shape=shape_parsed, data_type=dtype_parsed, - chunk_grid=RegularChunkGrid(chunk_shape=chunks_out), + chunk_grid=create_chunk_grid_metadata(outer_chunks), chunk_key_encoding=chunk_key_encoding_parsed, fill_value=fill_value, codecs=codecs_out, @@ -452,7 +496,7 @@ def meta_from_array( zarr_format: ZarrFormat = 3, attributes: dict[str, JSON] | None = None, chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None = None, - dimension_names: DimensionNames = None, + dimension_names: DimensionNamesLike = None, ) -> ArrayV3Metadata | ArrayV2Metadata: """ Create array metadata from an array @@ -499,3 +543,37 @@ def deep_nan_equal(a: object, b: object) -> bool: if isinstance(a, Sequence) and isinstance(b, Sequence): return all(deep_nan_equal(a[i], b[i]) for i in range(len(a))) return nan_equal(a, b) + + +# Shared mock-S3 (moto) backend. A single server is reused across the whole test session by +# every test that needs S3 -- both the fsspec store tests and the documentation examples -- +# instead of each module standing up its own. Consumers create their own buckets and choose +# how the endpoint reaches the client (explicit storage_options vs. the AWS_ENDPOINT_URL +# env var) on top of this fixture. + + +@pytest.fixture(scope="session") +def moto_server() -> Generator[str, None, None]: + """Start a session-scoped moto S3 server and yield its endpoint URL. + + The server binds an ephemeral port (port=0), so the endpoint is only known at + runtime; consumers must take it from this fixture rather than a constant. A fixed + port deadlocks under pytest-xdist: session-scoped fixtures run once per *worker*, so + concurrent workers race to bind the same port, and the losers block forever inside + ThreadedMotoServer.start(), whose server thread dies on "Address already in use" + before ever setting the ready event that start() waits on. + + importorskip lives inside the fixture so moto is only required when a test actually + requests an S3 backend, not for the whole test session.""" + moto_server_mod = pytest.importorskip("moto.moto_server.threaded_moto_server") + + server = moto_server_mod.ThreadedMotoServer(ip_address="127.0.0.1", port=0) + server.start() + host, port = server.get_host_and_port() + # moto needs *some* credentials present; use throwaway values if the environment has none. + os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "foo") + os.environ.setdefault("AWS_ACCESS_KEY_ID", "foo") + try: + yield f"http://{host}:{port}/" + finally: + server.stop() diff --git a/tests/package_with_entrypoint/__init__.py b/tests/package_with_entrypoint/__init__.py index 7b5dfb5a1e..23afcf1dc2 100644 --- a/tests/package_with_entrypoint/__init__.py +++ b/tests/package_with_entrypoint/__init__.py @@ -9,8 +9,8 @@ from zarr.abc.codec import ArrayBytesCodec, CodecInput, CodecPipeline from zarr.codecs import BytesCodec from zarr.core.buffer import Buffer, NDBuffer -from zarr.core.dtype.common import DataTypeValidationError, DTypeJSON, DTypeSpec_V2 from zarr.core.dtype.npy.bool import Bool +from zarr.errors import DataTypeValidationError if TYPE_CHECKING: from collections.abc import Iterable @@ -18,6 +18,7 @@ from zarr.core.array_spec import ArraySpec from zarr.core.common import ZarrFormat + from zarr.core.dtype.common import DTypeJSON, DTypeSpec_V2 class TestEntrypointCodec(ArrayBytesCodec): diff --git a/tests/test_api.py b/tests/test_api.py index a306ff3dc3..45d0c0dee4 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -75,11 +75,11 @@ def test_create(memory_store: Store) -> None: assert z.chunks == (40,) # create array with float shape - with pytest.raises(TypeError): + with pytest.raises(TypeError, match="Expected an iterable of integers"): z = create(shape=(400.5, 100), store=store, overwrite=True) # type: ignore[arg-type] # create array with float chunk shape - with pytest.raises(TypeError): + with pytest.raises(TypeError, match="Chunk specification must be an integer or an iterable"): z = create(shape=(400, 100), chunks=(16, 16.5), store=store, overwrite=True) # type: ignore[arg-type] @@ -137,7 +137,7 @@ async def test_array_like_creation( kwargs["fill_value"] = out_fill expect_fill = out_fill elif func is zarr.api.asynchronous.open_like: # type: ignore[comparison-overlap] - if out_fill == "keep": + if out_fill == "keep": # type: ignore[unreachable] expect_fill = ref_fill else: kwargs["fill_value"] = out_fill @@ -161,13 +161,60 @@ async def test_array_like_creation( else: expect_dtype = ref_arr.dtype # type: ignore[assignment] - new_arr = await func(ref_arr, path="foo", zarr_format=zarr_format, **kwargs) # type: ignore[call-arg] + new_arr = await func(ref_arr, path="foo", zarr_format=zarr_format, **kwargs) assert new_arr.shape == expect_shape assert new_arr.chunks == expect_chunks assert new_arr.dtype == expect_dtype assert np.all(Array(new_arr)[:] == expect_fill) +@pytest.mark.parametrize("mode_kwargs", [{}, {"mode": None}]) +async def test_open_like_creates_array_by_default( + zarr_format: ZarrFormat, mode_kwargs: dict[str, None] +) -> None: + ref_arr = zarr.create_array( + store={}, + shape=(11, 12), + dtype="uint8", + chunks=(11, 12), + zarr_format=zarr_format, + fill_value=100, + ) + + new_arr = await zarr.api.asynchronous.open_like( + ref_arr, + path="foo", + store={}, + zarr_format=zarr_format, + **mode_kwargs, + ) + + assert new_arr.shape == ref_arr.shape + assert new_arr.chunks == ref_arr.chunks + assert new_arr.dtype == ref_arr.dtype + assert np.all(Array(new_arr)[:] == ref_arr.fill_value) + + +async def test_open_like_default_mode_rejects_read_only_store( + zarr_format: ZarrFormat, +) -> None: + ref_arr = zarr.create_array( + store={}, + shape=(11, 12), + dtype="uint8", + chunks=(11, 12), + zarr_format=zarr_format, + ) + + with pytest.raises(ValueError, match="Store is read-only but mode is 'a'"): + await zarr.api.asynchronous.open_like( + ref_arr, + path="foo", + store=MemoryStore(read_only=True), + zarr_format=zarr_format, + ) + + # TODO: parametrize over everything this function takes @pytest.mark.parametrize("store", ["memory"], indirect=True) def test_create_array(store: Store, zarr_format: ZarrFormat) -> None: @@ -187,7 +234,7 @@ def test_create_array(store: Store, zarr_format: ZarrFormat) -> None: array_w[:] = data_val assert array_w.shape == shape assert array_w.attrs == attrs - assert np.array_equal(array_w[:], np.zeros(shape, dtype=array_w.dtype) + data_val) + assert np.array_equal(array_w[:], np.zeros(shape, dtype=array_w.dtype) + data_val) # type: ignore[unreachable] @pytest.mark.parametrize("write_empty_chunks", [True, False]) @@ -280,7 +327,19 @@ async def test_open_array(memory_store: MemoryStore, zarr_format: ZarrFormat) -> zarr.api.synchronous.open(store="doesnotexist", mode="r", zarr_format=zarr_format) -@pytest.mark.asyncio +def test_open_array_rectilinear_chunks(tmp_path: Path) -> None: + """zarr.open with rectilinear (dask-style) chunks preserves the chunk grid.""" + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + chunks = ((3, 3, 4), (5, 5)) + with zarr.config.set({"array.rectilinear_chunks": True}): + z = zarr.open(store=tmp_path, shape=(10, 10), dtype="float64", chunks=chunks, mode="w") + assert isinstance(z, Array) + assert z.shape == (10, 10) + assert isinstance(z.metadata.chunk_grid, RectilinearChunkGridMetadata) + assert z.read_chunk_sizes == ((3, 3, 4), (5, 5)) + + async def test_async_array_open_array_not_found() -> None: """Test that AsyncArray.open raises ArrayNotFoundError when array doesn't exist""" store = MemoryStore() @@ -313,7 +372,7 @@ async def test_create_group(store: Store, zarr_format: ZarrFormat) -> None: node = create_group(store, path=path, attributes=attrs, zarr_format=zarr_format) assert isinstance(node, Group) assert node.attrs == attrs - assert node.metadata.zarr_format == zarr_format + assert node.metadata.zarr_format == zarr_format # type: ignore[unreachable] async def test_open_group(memory_store: MemoryStore) -> None: @@ -339,16 +398,16 @@ async def test_open_group(memory_store: MemoryStore) -> None: @pytest.mark.parametrize("zarr_format", [None, 2, 3]) -async def test_open_group_unspecified_version(tmpdir: Path, zarr_format: ZarrFormat) -> None: +async def test_open_group_unspecified_version(tmp_path: Path, zarr_format: ZarrFormat) -> None: """Regression test for https://github.com/zarr-developers/zarr-python/issues/2175""" # create a group with specified zarr format (could be 2, 3, or None) _ = await zarr.api.asynchronous.open_group( - store=str(tmpdir), mode="w", zarr_format=zarr_format, attributes={"foo": "bar"} + store=str(tmp_path), mode="w", zarr_format=zarr_format, attributes={"foo": "bar"} ) # now open that group without specifying the format - g2 = await zarr.api.asynchronous.open_group(store=str(tmpdir), mode="r") + g2 = await zarr.api.asynchronous.open_group(store=str(tmp_path), mode="r") assert g2.attrs == {"foo": "bar"} @@ -360,13 +419,13 @@ async def test_open_group_unspecified_version(tmpdir: Path, zarr_format: ZarrFor @pytest.mark.parametrize("n_args", [10, 1, 0]) @pytest.mark.parametrize("n_kwargs", [10, 1, 0]) @pytest.mark.parametrize("path", [None, "some_path"]) -def test_save(store: Store, n_args: int, n_kwargs: int, path: None | str) -> None: +def test_save(store: Store, n_args: int, n_kwargs: int, path: str | None) -> None: data = np.arange(10) args = [np.arange(10) for _ in range(n_args)] kwargs = {f"arg_{i}": data for i in range(n_kwargs)} if n_kwargs == 0 and n_args == 0: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="at least one array must be provided"): save(store, path=path) elif n_args == 1 and n_kwargs == 0: save(store, *args, path=path) @@ -384,18 +443,36 @@ def test_save(store: Store, n_args: int, n_kwargs: int, path: None | str) -> Non assert group.nmembers() == n_args + n_kwargs +@pytest.mark.parametrize( + "data", + [ + np.array(42, dtype=np.int64), + np.array("teststr", dtype=np.bytes_), + ], +) +@pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") +def test_group_setitem_loads_scalar_arrays(sync_store: Store, data: np.ndarray) -> None: + root = zarr.open_group(store=sync_store) + root["test"] = data + + assert_array_equal(root["test"][...], data) + assert_array_equal(zarr.load(store=sync_store, path="test"), data) + + def test_save_errors() -> None: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="at least one array must be provided"): # no arrays provided save_group("data/group.zarr") - with pytest.raises(TypeError): + with pytest.raises(TypeError, match="missing 1 required positional argument: 'arr'"): # no array provided save_array("data/group.zarr") # type: ignore[call-arg] - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="at least one array must be provided"): # no arrays provided save("data/group.zarr") a = np.arange(10) - with pytest.raises(TypeError): + with pytest.raises( + TypeError, match="Keyword argument 'mode' must be a numpy or other NDArrayLike array" + ): # mode is no valid argument and would get handled as an array zarr.save("data/example.zarr", a, mode="w") @@ -809,9 +886,9 @@ def test_tree() -> None: # assert len(source) == len(dest) # for key in source: # if self._version == 3: -# dest_key = key[:10] + "new/" + key[10:] +# dest_key = f"{key[:10]}new/{key[10:]}" # else: -# dest_key = "new/" + key +# dest_key = f"new/{key}" # assert source[key] == dest[dest_key] # def test_source_dest_path(self): @@ -828,7 +905,7 @@ def test_tree() -> None: # assert source[key] == dest[dest_key] # else: # assert key not in dest -# assert ("new/" + key) not in dest +# assert (f"new/{key}") not in dest # def test_excludes_includes(self): # source = self.source @@ -840,16 +917,16 @@ def test_tree() -> None: # assert len(dest) == 2 # root = "" -# assert root + "foo" not in dest +# assert "f{root}foo" not in dest # # multiple excludes # dest = self._get_dest_store() # excludes = "b.z", ".*x" # copy_store(source, dest, excludes=excludes) # assert len(dest) == 1 -# assert root + "foo" in dest -# assert root + "bar/baz" not in dest -# assert root + "bar/qux" not in dest +# assert f"{root}foo" in dest +# assert f"{root}bar/baz" not in dest +# assert f"{root}bar/qux" not in dest # # excludes and includes # dest = self._get_dest_store() @@ -857,9 +934,9 @@ def test_tree() -> None: # includes = ".*x" # copy_store(source, dest, excludes=excludes, includes=includes) # assert len(dest) == 2 -# assert root + "foo" in dest -# assert root + "bar/baz" not in dest -# assert root + "bar/qux" in dest +# assert f"{root}foo" in dest +# assert f"{root}bar/baz" not in dest +# assert f"{root}bar/qux" in dest # def test_dry_run(self): # source = self.source @@ -871,7 +948,7 @@ def test_tree() -> None: # source = self.source # dest = self._get_dest_store() # root = "" -# dest[root + "bar/baz"] = b"mmm" +# dest[f"{root}bar/baz"] = b"mmm" # # default ('raise') # with pytest.raises(CopyError): @@ -884,16 +961,16 @@ def test_tree() -> None: # # skip # copy_store(source, dest, if_exists="skip") # assert 3 == len(dest) -# assert dest[root + "foo"] == b"xxx" -# assert dest[root + "bar/baz"] == b"mmm" -# assert dest[root + "bar/qux"] == b"zzz" +# assert dest[f"{root}foo"] == b"xxx" +# assert dest[f"{root}bar/baz"] == b"mmm" +# assert dest[f"{root}bar/qux"] == b"zzz" # # replace # copy_store(source, dest, if_exists="replace") # assert 3 == len(dest) -# assert dest[root + "foo"] == b"xxx" -# assert dest[root + "bar/baz"] == b"yyy" -# assert dest[root + "bar/qux"] == b"zzz" +# assert dest[f"{root}foo"] == b"xxx" +# assert dest[f"{root}bar/baz"] == b"yyy" +# assert dest[f"{root}bar/qux"] == b"zzz" # # invalid option # with pytest.raises(ValueError): diff --git a/tests/test_api/test_asynchronous.py b/tests/test_api/test_asynchronous.py index 362195e858..6ebec36bbd 100644 --- a/tests/test_api/test_asynchronous.py +++ b/tests/test_api/test_asynchronous.py @@ -75,6 +75,7 @@ def test_get_shape_chunks( "chunks": (10,), "shape": (100,), "dtype": np.dtype("f8"), + "fill_value": np.float64(0.0), "compressor": None, "filters": None, "order": "C", diff --git a/tests/test_api/test_synchronous.py b/tests/test_api/test_synchronous.py index d6ae61f1ca..9b15ec32f6 100644 --- a/tests/test_api/test_synchronous.py +++ b/tests/test_api/test_synchronous.py @@ -44,7 +44,7 @@ def test_docstrings_match(callable_name: str) -> None: @pytest.mark.parametrize( ("parameter_name", "array_creation_routines"), [ - ( + pytest.param( ("store", "path"), ( asynchronous.create_array, @@ -54,8 +54,9 @@ def test_docstrings_match(callable_name: str) -> None: zarr.AsyncGroup.create_array, zarr.Group.create_array, ), + id="store-path-create_array_group", ), - ( + pytest.param( ( "store", "path", @@ -64,11 +65,10 @@ def test_docstrings_match(callable_name: str) -> None: asynchronous.create, synchronous.create, zarr.Group.create, - zarr.AsyncArray.create, - zarr.Array.create, ), + id="store-path-create", ), - ( + pytest.param( ( ( "filters", @@ -88,12 +88,10 @@ def test_docstrings_match(callable_name: str) -> None: synchronous.create_array, zarr.AsyncGroup.create_array, zarr.Group.create_array, - zarr.AsyncGroup.create_dataset, - zarr.Group.create_dataset, ), + id="encoding-params-create_and_array", ), ], - ids=str, ) def test_docstring_consistent_parameters( parameter_name: str, array_creation_routines: tuple[Callable[[Any], Any], ...] diff --git a/tests/test_array.py b/tests/test_array.py index 5b85c6ba1d..b1a7a3c0f2 100644 --- a/tests/test_array.py +++ b/tests/test_array.py @@ -45,8 +45,13 @@ default_serializer_v3, ) from zarr.core.array_spec import ArrayConfig, ArrayConfigParams -from zarr.core.buffer import NDArrayLike, NDArrayLikeOrScalar, default_buffer_prototype -from zarr.core.chunk_grids import _auto_partition +from zarr.core.buffer import NDArrayLike, NDArrayLikeOrScalar, cpu, default_buffer_prototype +from zarr.core.chunk_grids import ( + SHARDED_INNER_CHUNK_MAX_BYTES, + guess_chunks, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) from zarr.core.chunk_key_encodings import ChunkKeyEncodingParams from zarr.core.common import JSON, ZarrFormat, ceildiv from zarr.core.dtype import ( @@ -64,7 +69,6 @@ ) from zarr.core.dtype.common import ENDIANNESS_STR, EndiannessStr from zarr.core.dtype.npy.common import NUMPY_ENDIANNESS_STR, endianness_from_numpy_str -from zarr.core.dtype.npy.string import UTF8Base from zarr.core.group import AsyncGroup from zarr.core.indexing import BasicIndexer, _iter_grid, _iter_regions from zarr.core.metadata.v2 import ArrayV2Metadata @@ -209,19 +213,19 @@ def test_array_name_properties_with_group( @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") @pytest.mark.parametrize("store", ["memory"], indirect=True) -@pytest.mark.parametrize("specifiy_fill_value", [True, False]) +@pytest.mark.parametrize("specify_fill_value", [True, False]) @pytest.mark.parametrize( "zdtype", zdtype_examples, ids=tuple(str(type(v)) for v in zdtype_examples) ) def test_array_fill_value_default( - store: MemoryStore, specifiy_fill_value: bool, zdtype: ZDType[Any, Any] + store: MemoryStore, specify_fill_value: bool, zdtype: ZDType[Any, Any] ) -> None: """ Test that creating an array with the fill_value parameter set to None, or unspecified, results in the expected fill_value attribute of the array, i.e. the default value of the dtype """ shape = (10,) - if specifiy_fill_value: + if specify_fill_value: arr = zarr.create_array( store=store, shape=shape, @@ -443,6 +447,8 @@ async def test_chunks_initialized( arr = zarr.create_array( store, name=path, shape=shape, shards=shard_shape, chunks=chunk_shape, dtype="i1" ) + if path: + await store.set(path, cpu.Buffer.from_bytes(b"")) chunks_accumulated = tuple( accumulate(tuple(tuple(v.split(" ")) for v in arr._iter_shard_keys())) @@ -786,8 +792,6 @@ def test_resize_growing_skips_chunk_enumeration( store: MemoryStore, zarr_format: ZarrFormat ) -> None: """Growing an array should not enumerate chunk coords for deletion (#3650 mitigation).""" - from zarr.core.chunk_grids import RegularChunkGrid - z = zarr.create( shape=(10, 10), chunks=(5, 5), @@ -798,11 +802,13 @@ def test_resize_growing_skips_chunk_enumeration( ) z[:] = np.ones((10, 10), dtype="i4") + grid_cls = type(z._chunk_grid) + # growth only - ensure no chunk coords are enumerated with mock.patch.object( - RegularChunkGrid, + grid_cls, "all_chunk_coords", - wraps=z.metadata.chunk_grid.all_chunk_coords, + wraps=z._chunk_grid.all_chunk_coords, ) as mock_coords: z.resize((20, 20)) mock_coords.assert_not_called() @@ -813,9 +819,9 @@ def test_resize_growing_skips_chunk_enumeration( # shrink - ensure no regression of behaviour with mock.patch.object( - RegularChunkGrid, + grid_cls, "all_chunk_coords", - wraps=z.metadata.chunk_grid.all_chunk_coords, + wraps=z._chunk_grid.all_chunk_coords, ) as mock_coords: z.resize((5, 5)) assert mock_coords.call_count > 0 @@ -836,9 +842,9 @@ def test_resize_growing_skips_chunk_enumeration( z2[:] = np.ones((10, 10), dtype="i4") with mock.patch.object( - RegularChunkGrid, + grid_cls, "all_chunk_coords", - wraps=z2.metadata.chunk_grid.all_chunk_coords, + wraps=z2._chunk_grid.all_chunk_coords, ) as mock_coords: z2.resize((20, 5)) assert mock_coords.call_count > 0 @@ -1073,36 +1079,53 @@ def test_auto_partition_auto_shards( where there are 8 or more chunks. """ dtype = np.dtype("uint8") + chunks_normalized = normalize_chunks_nd(chunk_shape, array_shape) with pytest.warns( ZarrUserWarning, match="Automatic shard shape inference is experimental and may change without notice.", ): with zarr.config.set({"array.target_shard_size_bytes": target_shard_size_bytes}): - auto_shards, _ = _auto_partition( + outer_chunks, _ = resolve_outer_and_inner_chunks( array_shape=array_shape, - chunk_shape=chunk_shape, + chunks=chunks_normalized, shard_shape="auto", item_size=dtype.itemsize, ) + auto_shards = tuple(dim[0] for dim in outer_chunks) assert auto_shards == expected_shards def test_auto_partition_auto_shards_with_auto_chunks_should_be_close_to_1MiB() -> None: """ - Test that automatically picking a shard size and a chunk size gives roughly 1MiB chunks. + Test that automatically picking chunk and shard sizes together produces + chunks close to 1 MiB and shards that are a multiple of the chunk size. """ + array_shape = (10_000_000,) + item_size = 1 + # Auto-chunks with sharding use the default inner chunk size target + chunks_normalized = guess_chunks( + array_shape, item_size, max_bytes=SHARDED_INNER_CHUNK_MAX_BYTES + ) + chunk_shape = tuple(dim[0] for dim in chunks_normalized) + chunk_bytes = np.prod(chunk_shape) * item_size + assert chunk_bytes <= SHARDED_INNER_CHUNK_MAX_BYTES + assert chunk_bytes > SHARDED_INNER_CHUNK_MAX_BYTES // 4 # should be in the right ballpark + with pytest.warns( ZarrUserWarning, match="Automatic shard shape inference is experimental and may change without notice.", ): with zarr.config.set({"array.target_shard_size_bytes": 10_000_000}): - _, chunk_shape = _auto_partition( - array_shape=(10_000_000,), - chunk_shape="auto", + outer_chunks, inner = resolve_outer_and_inner_chunks( + array_shape=array_shape, + chunks=chunks_normalized, shard_shape="auto", - item_size=1, + item_size=item_size, ) - assert chunk_shape == (625000,) + assert inner is not None + shard_shape = tuple(dim[0] for dim in outer_chunks) + # Shard dimensions must be multiples of chunk dimensions + assert all(s % c == 0 for s, c in zip(shard_shape, chunk_shape, strict=True)) def test_chunks_and_shards() -> None: @@ -1576,7 +1599,7 @@ async def test_with_data(impl: Literal["sync", "async"], store: Store) -> None: elif impl == "async": arr = await create_array(store, name=name, data=data, zarr_format=3) stored = await arr._get_selection( - BasicIndexer(..., shape=arr.shape, chunk_grid=arr.metadata.chunk_grid), + BasicIndexer(..., shape=arr.shape, chunk_grid=arr._chunk_grid), prototype=default_buffer_prototype(), ) else: @@ -1645,7 +1668,7 @@ async def test_name(store: Store, zarr_format: ZarrFormat, path: str | None) -> else: expected_path = path assert arr.path == expected_path - assert arr.name == "/" + expected_path + assert arr.name == f"/{expected_path}" # test that implicit groups were created path_parts = expected_path.split("/") @@ -1663,7 +1686,7 @@ def test_default_endianness( store: Store, zarr_format: ZarrFormat, endianness: EndiannessStr ) -> None: """ - Test that that endianness is correctly set when creating an array when not specifying a serializer + Test that endianness is correctly set when creating an array when not specifying a serializer. """ dtype = Int16(endianness=endianness) arr = zarr.create_array(store=store, shape=(1,), dtype=dtype, zarr_format=zarr_format) @@ -1672,7 +1695,8 @@ def test_default_endianness( assert endianness_from_numpy_str(byte_order) == endianness # type: ignore[arg-type] -@pytest.mark.parametrize("value", [1, 1.4, "a", b"a", np.array(1)]) +# The explicit id for b"a" avoids colliding with the auto-generated id for "a". +@pytest.mark.parametrize("value", [1, 1.4, "a", pytest.param(b"a", id="a-bytes"), np.array(1)]) @pytest.mark.parametrize("zarr_format", [2, 3]) @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") def test_scalar_array(value: Any, zarr_format: ZarrFormat) -> None: @@ -1853,24 +1877,21 @@ def test_roundtrip_numcodecs() -> None: # Create the array with the correct codecs root = zarr.group(store) - warn_msg = "Numcodecs codecs are not in the Zarr version 3 specification and may not be supported by other zarr implementations." - with pytest.warns(ZarrUserWarning, match=warn_msg): - root.create_array( - "test", - shape=(720, 1440), - chunks=(720, 1440), - dtype="float64", - compressors=compressors, # type: ignore[arg-type] - filters=filters, # type: ignore[arg-type] - fill_value=-9.99, - dimension_names=["lat", "lon"], - ) + root.create_array( + "test", + shape=(720, 1440), + chunks=(720, 1440), + dtype="float64", + compressors=compressors, # type: ignore[arg-type] + filters=filters, # type: ignore[arg-type] + fill_value=-9.99, + dimension_names=["lat", "lon"], + ) BYTES_CODEC = {"name": "bytes", "configuration": {"endian": "little"}} # Read in the array again and check compressor config root = zarr.open_group(store) - with pytest.warns(ZarrUserWarning, match=warn_msg): - metadata = root["test"].metadata.to_dict() + metadata = root["test"].metadata.to_dict() expected = (*filters, BYTES_CODEC, *compressors) assert metadata["codecs"] == expected @@ -1884,9 +1905,18 @@ def _index_array(arr: AnyArray, index: Any) -> Any: [ pytest.param( "fork", - marks=pytest.mark.skipif( - sys.platform in ("win32", "darwin"), reason="fork not supported on Windows or OSX" - ), + marks=[ + pytest.mark.skipif( + sys.platform in ("win32", "darwin"), + reason="fork not supported on Windows or OSX", + ), + # Python 3.15 deprecates fork() in multi-threaded processes, and zarr's + # sync event-loop thread is always running here. Fork-safety despite + # those threads is exactly what this test pins down, so keep running it. + pytest.mark.filterwarnings( + r"ignore:This process \(pid=\d+\) is multi-threaded, use of fork\(\):DeprecationWarning" + ), + ], ), "spawn", pytest.param( @@ -1962,23 +1992,14 @@ def test_array_repr(store: Store) -> None: assert str(arr) == f"" -class UnknownObjectDtype(UTF8Base[np.dtypes.ObjectDType]): - object_codec_id = "unknown" # type: ignore[assignment] - - def to_native_dtype(self) -> np.dtypes.ObjectDType: - """ - Create a NumPy object dtype from this VariableLengthUTF8 ZDType. +class UnknownObjectCodecDtype(VariableLengthUTF8): + """A data type that requires an object codec with an unknown id, used for error-path tests.""" - Returns - ------- - np.dtypes.ObjectDType - The NumPy object dtype. - """ - return np.dtype("o") # type: ignore[return-value] + object_codec_id = "unknown" # type: ignore[assignment] @pytest.mark.parametrize( - "dtype", [VariableLengthUTF8(), VariableLengthBytes(), UnknownObjectDtype()] + "dtype", [VariableLengthUTF8(), VariableLengthBytes(), UnknownObjectCodecDtype()] ) def test_chunk_encoding_no_object_codec_errors(dtype: ZDType[Any, Any]) -> None: """ @@ -2005,7 +2026,7 @@ def test_unknown_object_codec_default_serializer_v3() -> None: Test that we get a valueerrror when trying to create the default serializer for a data type that requires an unknown object codec """ - dtype = UnknownObjectDtype() + dtype = UnknownObjectCodecDtype() msg = f"Data type {dtype} requires an unknown object codec: {dtype.object_codec_id!r}." with pytest.raises(ValueError, match=re.escape(msg)): default_serializer_v3(dtype) @@ -2016,7 +2037,7 @@ def test_unknown_object_codec_default_filters_v2() -> None: Test that we get a valueerrror when trying to create the default serializer for a data type that requires an unknown object codec """ - dtype = UnknownObjectDtype() + dtype = UnknownObjectCodecDtype() msg = f"Data type {dtype} requires an unknown object codec: {dtype.object_codec_id!r}." with pytest.raises(ValueError, match=re.escape(msg)): default_filters_v2(dtype) @@ -2259,9 +2280,34 @@ def test_create_array_with_data_num_gets( data = zarr.zeros(shape, dtype="int64") zarr.create_array(store, data=data, chunks=chunk_shape, shards=shard_shape, fill_value=-1) # type: ignore[arg-type] - # one get for the metadata and one per shard. - # Note: we don't actually need one get per shard, but this is the current behavior - assert store.counter["get"] == 1 + num_shards + # One get for the metadata; full-shard writes should not read shard payloads. + assert store.counter["get"] == 1 + + +@pytest.mark.parametrize( + ("selection", "expected_gets"), + [(slice(None), 0), (slice(1, 9), 1)], +) +def test_shard_write_num_gets(selection: slice, expected_gets: int) -> None: + """ + Test that partial-shard writes read the existing data and full-shard writes don't. + """ + store = LoggingStore(store=MemoryStore()) + arr = zarr.create_array( + store, + shape=(10,), + chunks=(1,), + shards=(10,), + dtype="int64", + fill_value=-1, + ) + arr[:] = 0 + + store.counter.clear() + + arr[selection] = 1 + + assert store.counter["get"] == expected_gets @pytest.mark.parametrize("config", [{}, {"write_empty_chunks": True}, {"order": "C"}]) @@ -2299,3 +2345,44 @@ def test_with_config_polymorphism() -> None: arr_source_config_dict = arr.with_config(source_config_dict) assert arr_source_config.config == arr_source_config_dict.config + + +@pytest.mark.parametrize( + ("chunk_input", "expected"), + [ + (-1, ((10,),)), + ((-1,), ((10,),)), + ((10,), ((10,),)), + ((5,), ((5, 5),)), + ((3,), ((3, 3, 3, 1),)), + ], + ids=["scalar-neg1", "tuple-neg1", "exact", "half", "remainder"], +) +async def test_create_array_chunks_1d( + chunk_input: int | tuple[int, ...], + expected: tuple[tuple[int, ...], ...], +) -> None: + """Test that chunk normalization produces the expected chunk sizes for 1D arrays.""" + arr = await create_array(store={}, shape=(10,), chunks=chunk_input, dtype="uint8") + assert arr.write_chunk_sizes == expected + + +@pytest.mark.parametrize( + ("chunk_input", "expected"), + [ + (-1, ((10,), (12,), (15,))), + ((3, 4, 5), ((3, 3, 3, 1), (4, 4, 4), (5, 5, 5))), + ((-1, 4, -1), ((10,), (4, 4, 4), (15,))), + ((10, 12, 15), ((10,), (12,), (15,))), + ((7, 3, 2), ((7, 3), (3, 3, 3, 3), (2, 2, 2, 2, 2, 2, 2, 1))), + ], + ids=["all-neg1", "mixed", "neg1-middle", "exact", "remainder"], +) +async def test_create_array_chunks_3d( + chunk_input: int | tuple[int, ...], + expected: tuple[tuple[int, ...], ...], +) -> None: + """Test that chunk normalization produces the expected chunk sizes for 3D arrays.""" + shape = (10, 12, 15) + arr = await create_array(store={}, shape=shape, chunks=chunk_input, dtype="float64") + assert arr.write_chunk_sizes == expected diff --git a/tests/test_array_spec.py b/tests/test_array_spec.py new file mode 100644 index 0000000000..4fbc0b1205 --- /dev/null +++ b/tests/test_array_spec.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import BufferPrototype, default_buffer_prototype +from zarr.core.buffer.cpu import NDBuffer +from zarr.core.dtype import get_data_type_from_native_dtype + +if TYPE_CHECKING: + from collections.abc import Callable + + from zarr.core.common import MemoryOrder + + +def _make_spec( + *, + shape: tuple[int, ...] = (4, 4), + native_dtype: Any = "int16", + fill_value: Any = 0, + order: MemoryOrder = "C", + write_empty_chunks: bool = False, + prototype: BufferPrototype | None = None, +) -> ArraySpec: + """Creates an ArraySpec with common defaults""" + zdtype = get_data_type_from_native_dtype(np.dtype(native_dtype)) + fill_value = zdtype.cast_scalar(fill_value) # mirrors ArrayV3Metadata's fill_value + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=fill_value, + config=ArrayConfig(order=order, write_empty_chunks=write_empty_chunks), + prototype=prototype if prototype is not None else default_buffer_prototype(), + ) + + +class _AltNDBuffer(NDBuffer): + """A distinct NDBuffer subclass""" + + +_ALT_PROTOTYPE = BufferPrototype( + buffer=default_buffer_prototype().buffer, + nd_buffer=_AltNDBuffer, +) # a distinct BufferPrototype with a different nd_buffer subclass + + +# Difficult / important cases: +# issue #3054: np.void is unhashable when writeable +# nan/NaT aren't self-equal yet must compare equal for a ArraySpec +SPECS = [ + pytest.param({"native_dtype": "int16", "fill_value": 7}, id="int16"), + pytest.param({"native_dtype": "float64", "fill_value": 1.5}, id="float64"), + pytest.param({"native_dtype": "float64", "fill_value": float("nan")}, id="float64-nan"), + pytest.param({"native_dtype": "float64", "fill_value": -0.0}, id="float64-negzero"), + pytest.param({"native_dtype": "complex128", "fill_value": 1 + 2j}, id="complex128"), + pytest.param( + {"native_dtype": "complex128", "fill_value": complex(-0.0, -0.0)}, + id="complex128-negzero", + ), + pytest.param({"native_dtype": "bool", "fill_value": True}, id="bool"), + pytest.param( + {"native_dtype": "datetime64[s]", "fill_value": np.datetime64("2020-01-01")}, + id="datetime64", + ), + pytest.param( + {"native_dtype": "datetime64[s]", "fill_value": np.datetime64("NaT", "s")}, + id="datetime64-NaT", + ), + pytest.param( + {"native_dtype": [("a", "f8"), ("b", "i8")], "fill_value": (1.0, 2)}, + id="structured-void", + ), + pytest.param({"native_dtype": "U5", "fill_value": "hello"}, id="fixed-string"), + pytest.param({"shape": ()}, id="scalar-shape"), + pytest.param({"shape": (0,)}, id="zero-size"), + pytest.param({"order": "F"}, id="order-F"), +] + + +# Mutations: each mutate kwargs to an unequal version +def _grow_shape(kw: dict[str, Any]) -> dict[str, Any]: + return {"shape": (*kw.get("shape", (4, 4)), 1)} + + +def _flip_order(kw: dict[str, Any]) -> dict[str, Any]: + return {"order": "F" if kw.get("order", "C") == "C" else "C"} + + +def _swap_prototype(_kw: dict[str, Any]) -> dict[str, Any]: + return {"prototype": _ALT_PROTOTYPE} + + +MUTATIONS = [ + pytest.param(_grow_shape, id="shape"), + pytest.param(_flip_order, id="order"), + pytest.param(_swap_prototype, id="prototype"), +] + + +@pytest.mark.parametrize("kwargs", SPECS) +def test_hashable(kwargs: dict[str, Any]) -> None: + """Every ArraySpec is hashable, including structured (np.void) fill values.""" + assert isinstance(hash(_make_spec(**kwargs)), int) + + +@pytest.mark.parametrize("kwargs", SPECS) +def test_equal_specs_hash_equal(kwargs: dict[str, Any]) -> None: + """Independently built specs with identical fields are equal and hash equal.""" + a = _make_spec(**kwargs) + b = _make_spec(**kwargs) + assert a == b + assert hash(a) == hash(b) + + +@pytest.mark.parametrize("kwargs", SPECS) +@pytest.mark.parametrize("mutate", MUTATIONS) +def test_distinct_specs_unequal( + mutate: Callable[[dict[str, Any]], dict[str, Any]], + kwargs: dict[str, Any], +) -> None: + """Changing one dtype-independent field makes a spec unequal to its base.""" + base = _make_spec(**kwargs) + variant = _make_spec(**{**kwargs, **mutate(kwargs)}) + assert base != variant + + +@pytest.mark.parametrize( + ("base", "variant"), + [ + pytest.param({"fill_value": 0}, {"fill_value": 1}, id="fill_value"), + pytest.param({"native_dtype": "int16"}, {"native_dtype": "int32"}, id="dtype"), + pytest.param( + {"native_dtype": "float32", "fill_value": 1.0}, + {"native_dtype": "float64", "fill_value": 1.0}, + id="dtype-float-promote", + ), + ], +) +def test_dtype_and_fill_value_matter(base: dict[str, Any], variant: dict[str, Any]) -> None: + """dtype and fill_value participate in equality; they can't join the cross + product because fill_value is coupled to dtype.""" + assert _make_spec(**base) != _make_spec(**variant) + + +@pytest.mark.parametrize( + ("native_dtype", "neg_fill", "pos_fill"), + [ + pytest.param("float16", -0.0, 0.0, id="float16"), + pytest.param("float32", -0.0, 0.0, id="float32"), + pytest.param("float64", -0.0, 0.0, id="float64"), + pytest.param("complex128", complex(-0.0, -0.0), 0j, id="complex128-both"), + pytest.param("complex128", complex(0.0, -0.0), 0j, id="complex128-imag"), + pytest.param("complex128", complex(-0.0, 0.0), 0j, id="complex128-real"), + pytest.param([("a", "f8")], (-0.0,), (0.0,), id="structured"), + ], +) +def test_signed_zero_fills_are_distinct(native_dtype: Any, neg_fill: Any, pos_fill: Any) -> None: + """A -0.0 fill writes different bytes than +0.0, so the specs are not equal.""" + neg = _make_spec(native_dtype=native_dtype, fill_value=neg_fill) + pos = _make_spec(native_dtype=native_dtype, fill_value=pos_fill) + assert neg != pos + + +@pytest.mark.parametrize( + ("obj"), + [ + pytest.param(None, id="None"), + pytest.param(42, id="int"), + pytest.param("hello", id="str"), + pytest.param([1, 2, 3], id="list"), + pytest.param({"a": 1}, id="dict"), + ], +) +def test_unequal_with_invalid_type(obj: Any) -> None: + assert (_make_spec() == obj) is False + assert _make_spec() != obj diff --git a/tests/test_buffer.py b/tests/test_buffer.py index b50e5abb67..b4a16ed1de 100644 --- a/tests/test_buffer.py +++ b/tests/test_buffer.py @@ -44,7 +44,6 @@ def test_nd_array_like(xp: types.ModuleType) -> None: assert isinstance(ary, NDArrayLike) -@pytest.mark.asyncio async def test_async_array_prototype() -> None: """Test the use of a custom buffer prototype""" @@ -73,7 +72,6 @@ async def test_async_array_prototype() -> None: @gpu_test -@pytest.mark.asyncio async def test_async_array_gpu_prototype() -> None: """Test the use of the GPU buffer prototype""" @@ -97,7 +95,6 @@ async def test_async_array_gpu_prototype() -> None: assert cp.array_equal(expect, got) -@pytest.mark.asyncio async def test_codecs_use_of_prototype() -> None: expect = np.zeros((10, 10), dtype="uint16", order="F") a = await zarr.api.asynchronous.create_array( @@ -126,7 +123,6 @@ async def test_codecs_use_of_prototype() -> None: @gpu_test -@pytest.mark.asyncio async def test_codecs_use_of_gpu_prototype() -> None: expect = cp.zeros((10, 10), dtype="uint16", order="F") a = await zarr.api.asynchronous.create_array( @@ -155,7 +151,6 @@ async def test_codecs_use_of_gpu_prototype() -> None: @gpu_test -@pytest.mark.asyncio async def test_sharding_use_of_gpu_prototype() -> None: with zarr.config.enable_gpu(): expect = cp.zeros((10, 10), dtype="uint16", order="F") diff --git a/tests/test_chunk_grids.py b/tests/test_chunk_grids.py index 2920b5d6f3..4640c43d1c 100644 --- a/tests/test_chunk_grids.py +++ b/tests/test_chunk_grids.py @@ -3,7 +3,26 @@ import numpy as np import pytest -from zarr.core.chunk_grids import _guess_chunks, normalize_chunks +from tests.conftest import Expect, ExpectFail +from zarr.core.chunk_grids import ( + ChunkLayout, + _guess_regular_chunks, + normalize_chunks_1d, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) + + +def _assert_chunks_equal( + actual: tuple[Any, ...], + expected: tuple[tuple[int, ...], ...], +) -> None: + """Compare a ChunksTuple (tuple of np.int64 arrays) against a tuple of int tuples.""" + assert len(actual) == len(expected), f"axis count mismatch: {len(actual)} vs {len(expected)}" + for axis, (a, e) in enumerate(zip(actual, expected, strict=True)): + assert np.array_equal(a, np.asarray(e, dtype=np.int64)), ( + f"axis {axis}: {list(a)} != {list(e)}" + ) @pytest.mark.parametrize( @@ -11,7 +30,7 @@ ) @pytest.mark.parametrize("itemsize", [1, 2, 4]) def test_guess_chunks(shape: tuple[int, ...], itemsize: int) -> None: - chunks = _guess_chunks(shape, itemsize) + chunks = _guess_regular_chunks(shape, itemsize) chunk_size = np.prod(chunks) * itemsize assert isinstance(chunks, tuple) assert len(chunks) == len(shape) @@ -21,43 +40,240 @@ def test_guess_chunks(shape: tuple[int, ...], itemsize: int) -> None: @pytest.mark.parametrize( - ("chunks", "shape", "typesize", "expected"), + ("chunks", "shape", "expected"), [ - ((10,), (100,), 1, (10,)), - ([10], (100,), 1, (10,)), - (10, (100,), 1, (10,)), - ((10, 10), (100, 10), 1, (10, 10)), - (10, (100, 10), 1, (10, 10)), - ((10, None), (100, 10), 1, (10, 10)), - (30, (100, 20, 10), 1, (30, 30, 30)), - ((30,), (100, 20, 10), 1, (30, 20, 10)), - ((30, None), (100, 20, 10), 1, (30, 20, 10)), - ((30, None, None), (100, 20, 10), 1, (30, 20, 10)), - ((30, 20, None), (100, 20, 10), 1, (30, 20, 10)), - ((30, 20, 10), (100, 20, 10), 1, (30, 20, 10)), - # dask-style chunks (uniform with optional smaller final chunk) - (((100, 100, 100), (50, 50)), (300, 100), 1, (100, 50)), - (((100, 100, 50),), (250,), 1, (100,)), - (((100,),), (100,), 1, (100,)), - # auto chunking - (None, (100,), 1, (100,)), - (-1, (100,), 1, (100,)), - ((30, -1, None), (100, 20, 10), 1, (30, 20, 10)), + # 1D cases + ((10,), (100,), ((10,) * 10,)), + ([10], (100,), ((10,) * 10,)), + (10, (100,), ((10,) * 10,)), + # 2D cases + ((10, 10), (100, 10), ((10,) * 10, (10,))), + (10, (100, 10), ((10,) * 10, (10,))), + ((10, -1), (100, 10), ((10,) * 10, (10,))), + # 3D cases + (30, (100, 20, 10), ((30, 30, 30, 30), (30,), (30,))), + ((30, -1, -1), (100, 20, 10), ((30, 30, 30, 30), (20,), (10,))), + ((30, 20, -1), (100, 20, 10), ((30, 30, 30, 30), (20,), (10,))), + ((30, 20, 10), (100, 20, 10), ((30, 30, 30, 30), (20,), (10,))), + # dask-style chunks (explicit per-chunk sizes) + (((100, 100, 100), (50, 50)), (300, 100), ((100, 100, 100), (50, 50))), + (((100, 100, 50),), (250,), ((100, 100, 50),)), + (((100,),), (100,), ((100,),)), + # no chunking (False means each dimension is one chunk spanning the full extent) + (False, (100,), ((100,),)), + (False, (100, 50), ((100,), (50,))), + # sentinel values + (-1, (100,), ((100,),)), + # zero-length dimensions preserve the declared chunk size + (10, (0,), ((10,),)), + ((5, 10), (0, 100), ((5,), (10,) * 10)), + ((5, 10), (20, 0), ((5, 5, 5, 5), (10,))), + # numpy integers are accepted anywhere a python int is, whether as the scalar + # convenience form, as per-dimension entries, or as the `-1` sentinel. + (np.int64(10), (100,), ((10,) * 10,)), + ((np.int64(2), np.int64(2)), (4, 4), ((2, 2), (2, 2))), + ((1, 3, np.int64(16), np.int64(16)), (1, 3, 32, 32), ((1,), (3,), (16, 16), (16, 16))), + ((np.int32(30), np.int64(-1)), (100, 20), ((30, 30, 30, 30), (20,))), + (np.array([10, 10]), (100, 100), ((10,) * 10, (10,) * 10)), + # rectilinear chunks given as numpy arrays + ((np.array([60, 40]), np.array([50, 50])), (100, 100), ((60, 40), (50, 50))), ], ) def test_normalize_chunks( - chunks: Any, shape: tuple[int, ...], typesize: int, expected: tuple[int, ...] + chunks: Any, shape: tuple[int, ...], expected: tuple[tuple[int, ...], ...] +) -> None: + _assert_chunks_equal(normalize_chunks_nd(chunks, shape), expected) + + +@pytest.mark.parametrize( + ("array_shape", "chunks_input", "shard_shape", "expected_outer", "expected_inner_outer"), + [ + # no sharding: outer = chunks, inner = None + ((100,), (10,), None, ((10,) * 10,), None), + # explicit regular shards + ((100,), (10,), (50,), ((50, 50),), ((10,) * 10,)), + # rectilinear shards + ((100,), (10,), ((60, 40),), ((60, 40),), ((10,) * 10,)), + # dict-style shards + ((100, 100), (10, 10), {"shape": (50, 50)}, ((50, 50), (50, 50)), ((10,) * 10, (10,) * 10)), + ], +) +def test_resolve_outer_and_inner_chunks( + array_shape: tuple[int, ...], + chunks_input: tuple[int, ...], + shard_shape: Any, + expected_outer: tuple[tuple[int, ...], ...], + expected_inner_outer: tuple[tuple[int, ...], ...] | None, +) -> None: + chunks = normalize_chunks_nd(chunks_input, array_shape) + outer_chunks, inner = resolve_outer_and_inner_chunks( + array_shape=array_shape, chunks=chunks, shard_shape=shard_shape, item_size=1 + ) + _assert_chunks_equal(outer_chunks, expected_outer) + if expected_inner_outer is None: + assert inner is None + else: + assert inner is not None + _assert_chunks_equal(inner.outer_chunks, expected_inner_outer) + assert inner.inner is None + + +def test_chunk_layout_nested() -> None: + """Test that ChunkLayout supports recursive nesting for nested sharding.""" + leaf = normalize_chunks_nd((5, 5), (100, 100)) + mid = ChunkLayout( + outer_chunks=normalize_chunks_nd((25, 25), (100, 100)), + inner=ChunkLayout(outer_chunks=leaf), + ) + top = ChunkLayout(outer_chunks=normalize_chunks_nd((50, 50), (100, 100)), inner=mid) + + # Three levels: top -> mid -> leaf + _assert_chunks_equal(top.outer_chunks, ((50, 50), (50, 50))) + assert top.inner is not None + _assert_chunks_equal(top.inner.outer_chunks, ((25,) * 4, (25,) * 4)) + assert top.inner.inner is not None + _assert_chunks_equal(top.inner.inner.outer_chunks, ((5,) * 20, (5,) * 20)) + assert top.inner.inner.inner is None + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input=(0, 100), + exception=ValueError, + id="zero-uniform", + msg="Chunk size must be positive", + ), + ExpectFail( + input=(-2, 100), + exception=ValueError, + id="negative-uniform", + msg="Chunk size must be positive", + ), + ExpectFail( + input=(np.int64(0), 100), + exception=ValueError, + id="zero-uniform-numpy", + msg="Chunk size must be positive", + ), + ExpectFail(input=([], 100), exception=ValueError, id="empty-list", msg="must not be empty"), + # Scalars that are neither integers nor iterable name themselves in the error, + # rather than surfacing an opaque "object is not iterable" from `list(chunks)`. + ExpectFail( + input=(2.5, 100), + exception=TypeError, + id="non-iterable-scalar", + msg="must be an integer or an iterable of integers; got 2.5 of type float", + escape=True, + ), + ExpectFail( + input=([10, -1, 10], 100), + exception=ValueError, + id="negative-element", + msg="must be positive", + ), + ExpectFail( + input=([10, 0, 10], 20), exception=ValueError, id="zero-element", msg="must be positive" + ), + ExpectFail( + input=([10, 20], 100), exception=ValueError, id="wrong-sum", msg="do not sum to span" + ), + # Nested/RLE form for a single dim is rejected with offending indices. + ExpectFail( + input=([[3, 3], 1], 7), + exception=TypeError, + id="rle-single-dim", + msg="non-integer element(s) ([3, 3],) at indices (0,)", + escape=True, + ), + # Multiple non-int elements: all offending indices reported. + ExpectFail( + input=([1, [2, 2], 1, [3]], 9), + exception=TypeError, + id="multiple-non-ints", + msg="non-integer element(s) ([2, 2], [3]) at indices (1, 3)", + escape=True, + ), + # Strings are non-integers and should be reported the same way. + ExpectFail( + input=([2, "3", 5], 10), + exception=TypeError, + id="string-element", + msg="non-integer element(s) ('3',) at indices (1,)", + escape=True, + ), + ], + ids=lambda c: c.id, +) +def test_normalize_chunks_1d_errors(case: ExpectFail[tuple[Any, int]]) -> None: + """Invalid 1D chunk specifications are rejected with informative error messages.""" + chunks, span = case.input + with case.raises(): + normalize_chunks_1d(chunks, span=span) + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input=(None, (100,)), + exception=ValueError, + id="none", + msg="None is not a valid chunk input", + ), + # `True` is rejected explicitly because bool is a subclass of int — without + # this guard, `chunks=True` would silently produce size-1 chunks. + ExpectFail( + input=(True, (100,)), + exception=ValueError, + id="true", + msg="True is not a valid chunk input", + ), + ExpectFail(input=("foo", (100,)), exception=ValueError, id="string", msg="dimensions"), + ExpectFail( + input=((100, 10), (100,)), exception=ValueError, id="too-many-dims", msg="dimensions" + ), + ExpectFail( + input=((10,), (100, 100)), exception=ValueError, id="too-few-dims", msg="dimensions" + ), + # End-to-end: per-dim RLE surfaces through normalize_chunks_nd. + ExpectFail( + input=([[6, 4], [[3, 3], 1]], (10, 10)), + exception=TypeError, + id="rle-inner-dim", + msg="non-integer element(s) ([3, 3],) at indices (0,)", + escape=True, + ), + ], + ids=lambda c: c.id, +) +def test_normalize_chunks_nd_errors(case: ExpectFail[tuple[Any, tuple[int, ...]]]) -> None: + """Invalid N-D chunk specifications are rejected with informative error messages.""" + chunks, shape = case.input + with case.raises(): + normalize_chunks_nd(chunks, shape) + + +@pytest.mark.parametrize( + "case", + [ + # uniform-chunks branch: one int → broadcast across span via np.full. + Expect(input=(1000, 100_000), output=[1000] * 100, id="uniform"), + # explicit-per-chunk branch. + Expect(input=([10, 20, 30, 40], 100), output=[10, 20, 30, 40], id="explicit-list"), + # -1 sentinel branch: one chunk covering the full span. + Expect(input=(-1, 100), output=[100], id="full-span-sentinel"), + ], + ids=lambda c: c.id, +) +def test_normalize_chunks_1d_returns_int64_array( + case: Expect[tuple[Any, int], list[int]], ) -> None: - assert expected == normalize_chunks(chunks, shape, typesize) - - -def test_normalize_chunks_errors() -> None: - with pytest.raises(ValueError): - normalize_chunks("foo", (100,), 1) - with pytest.raises(ValueError): - normalize_chunks((100, 10), (100,), 1) - # dask-style irregular chunks should raise - with pytest.raises(ValueError, match="Irregular chunk sizes"): - normalize_chunks(((10, 20, 30),), (60,), 1) - with pytest.raises(ValueError, match="Irregular chunk sizes"): - normalize_chunks(((100, 100), (10, 20)), (200, 30), 1) + """Every branch of normalize_chunks_1d must produce a 1D int64 array.""" + chunks, span = case.input + result = normalize_chunks_1d(chunks, span) + assert isinstance(result, np.ndarray) + assert result.dtype == np.int64 + assert result.ndim == 1 + assert result.tolist() == case.output diff --git a/tests/test_chunk_key_encodings.py b/tests/test_chunk_key_encodings.py new file mode 100644 index 0000000000..dcc93b9249 --- /dev/null +++ b/tests/test_chunk_key_encodings.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import pytest + +from zarr.core.chunk_key_encodings import DefaultChunkKeyEncoding, V2ChunkKeyEncoding + + +@pytest.mark.parametrize("separator", ["/", "."]) +@pytest.mark.parametrize( + "coords", + [(), (0,), (1, 2), (10, 0, 3)], +) +def test_default_encoding_round_trips(separator: str, coords: tuple[int, ...]) -> None: + """Encoding coordinates and decoding the result returns the coordinates.""" + encoding = DefaultChunkKeyEncoding(separator=separator) # type: ignore[arg-type] + + key = encoding.encode_chunk_key(coords) + assert encoding.decode_chunk_key(key) == coords + + +@pytest.mark.parametrize("separator", ["/", "."]) +@pytest.mark.parametrize("coords", [(0,), (1, 2), (10, 0, 3)]) +def test_v2_encoding_round_trips(separator: str, coords: tuple[int, ...]) -> None: + """The v2 encoding round-trips coordinates for either separator.""" + encoding = V2ChunkKeyEncoding(separator=separator) # type: ignore[arg-type] + + key = encoding.encode_chunk_key(coords) + assert encoding.decode_chunk_key(key) == coords + + +@pytest.mark.parametrize("separator", ["/", "."]) +def test_v2_zero_dimensional_key_is_ambiguous(separator: str) -> None: + """A 0-d v2 array stores its sole chunk under `"0"`, the same key a 1-d + array uses for chunk 0, so decoding cannot recover the empty tuple on its + own -- the array's dimensionality is what disambiguates it.""" + encoding = V2ChunkKeyEncoding(separator=separator) # type: ignore[arg-type] + + assert encoding.encode_chunk_key(()) == "0" + assert encoding.decode_chunk_key("0") == (0,) + + +@pytest.mark.parametrize( + "chunk_key", + [ + "0/1", # no "c" prefix at all + "c0/1", # "c" not followed by the separator + "x/0/1", # wrong prefix character + "", + ], +) +def test_default_encoding_rejects_key_without_prefix(chunk_key: str) -> None: + """A key that does not carry the `c` prefix is not a chunk key + for this encoding, and must be rejected rather than silently decoded.""" + encoding = DefaultChunkKeyEncoding(separator="/") + + with pytest.raises(ValueError, match="Invalid chunk key"): + encoding.decode_chunk_key(chunk_key) + + +def test_default_encoding_rejects_key_using_the_other_separator() -> None: + """A key encoded with `.` is not valid for a `/`-separated encoding.""" + encoding = DefaultChunkKeyEncoding(separator="/") + + with pytest.raises(ValueError, match="Invalid chunk key"): + encoding.decode_chunk_key("c.0.1") diff --git a/tests/test_chunk_transform.py b/tests/test_chunk_transform.py new file mode 100644 index 0000000000..d2a2b39c41 --- /dev/null +++ b/tests/test_chunk_transform.py @@ -0,0 +1,154 @@ +"""Unit tests for ChunkTransform -- the per-chunk synchronous codec chain. + +ChunkTransform is the data structure FusedCodecPipeline uses to encode/decode a +single chunk through a sequence of codecs synchronously. These tests exercise it +directly (no pipeline, no store): construction and its rejection of codecs that +lack a synchronous implementation, encode/decode roundtrips across codec chains, +compute_encoded_size, and None short-circuiting when an array->array codec +returns None. End-to-end pipeline behavior lives in the pipeline test modules. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest + +from zarr.abc.codec import ArrayBytesCodec, Codec +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.zstd import ZstdCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import Buffer, NDBuffer, default_buffer_prototype +from zarr.core.chunk_utils import ChunkTransform +from zarr.core.dtype import get_data_type_from_native_dtype + + +class AsyncOnlyCodec(ArrayBytesCodec): + """A codec that only supports async, for testing rejection of non-sync codecs.""" + + is_fixed_size = True + + async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + raise NotImplementedError # pragma: no cover + + async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + raise NotImplementedError # pragma: no cover + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + return input_byte_length # pragma: no cover + + +def _make_array_spec(shape: tuple[int, ...], dtype: np.dtype[np.generic]) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(dtype) + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + +def _make_nd_buffer(arr: np.ndarray[Any, np.dtype[Any]]) -> NDBuffer: + return default_buffer_prototype().nd_buffer.from_numpy_array(arr) + + +@pytest.mark.parametrize( + ("shape", "codecs"), + [ + ((100,), (BytesCodec(),)), + ((100,), (BytesCodec(), GzipCodec())), + ((3, 4), (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec())), + ], + ids=["bytes-only", "with-compression", "full-chain"], +) +def test_construction(shape: tuple[int, ...], codecs: tuple[Codec, ...]) -> None: + """Construction succeeds when all codecs implement SupportsSyncCodec.""" + _ = _make_array_spec(shape, np.dtype("float64")) + ChunkTransform(codecs=codecs) + + +@pytest.mark.parametrize( + ("shape", "codecs"), + [ + ((100,), (AsyncOnlyCodec(),)), + ((3, 4), (TransposeCodec(order=(1, 0)), AsyncOnlyCodec())), + ], + ids=["async-only", "mixed-sync-and-async"], +) +def test_construction_rejects_non_sync(shape: tuple[int, ...], codecs: tuple[Codec, ...]) -> None: + """Construction raises TypeError when any codec lacks SupportsSyncCodec.""" + _ = _make_array_spec(shape, np.dtype("float64")) + with pytest.raises(TypeError, match="AsyncOnlyCodec"): + ChunkTransform(codecs=codecs) + + +@pytest.mark.parametrize( + ("arr", "codecs"), + [ + (np.arange(100, dtype="float64"), (BytesCodec(),)), + (np.arange(100, dtype="float64"), (BytesCodec(), GzipCodec(level=1))), + ( + np.arange(12, dtype="float64").reshape(3, 4), + (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec(level=1)), + ), + (np.arange(100, dtype="float64"), (BytesCodec(), Crc32cCodec())), + (np.arange(50, dtype="int32"), (BytesCodec(), ZstdCodec(level=1))), + ], + ids=["bytes-only", "gzip", "transpose+zstd", "crc32c", "int32"], +) +def test_encode_decode_roundtrip( + arr: np.ndarray[Any, np.dtype[Any]], codecs: tuple[Codec, ...] +) -> None: + """Data survives a full encode/decode cycle.""" + spec = _make_array_spec(arr.shape, arr.dtype) + chain = ChunkTransform(codecs=codecs) + nd_buf = _make_nd_buffer(arr) + + encoded = chain.encode_chunk(nd_buf, spec) + assert encoded is not None + decoded = chain.decode_chunk(encoded, spec) + np.testing.assert_array_equal(arr, decoded.as_numpy_array()) + + +@pytest.mark.parametrize( + ("shape", "codecs", "input_size", "expected_size"), + [ + ((100,), (BytesCodec(),), 800, 800), + ((100,), (BytesCodec(), Crc32cCodec()), 800, 804), + ((3, 4), (TransposeCodec(order=(1, 0)), BytesCodec()), 96, 96), + ], + ids=["bytes-only", "crc32c", "transpose"], +) +def test_compute_encoded_size( + shape: tuple[int, ...], + codecs: tuple[Codec, ...], + input_size: int, + expected_size: int, +) -> None: + """compute_encoded_size returns the correct byte length.""" + spec = _make_array_spec(shape, np.dtype("float64")) + chain = ChunkTransform(codecs=codecs) + assert chain.compute_encoded_size(input_size, spec) == expected_size + + +def test_encode_returns_none_propagation() -> None: + """When an AA codec returns None, encode short-circuits and returns None.""" + + class NoneReturningAACodec(TransposeCodec): + """An ArrayArrayCodec that always returns None from encode.""" + + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer | None: + return None + + spec = _make_array_spec((3, 4), np.dtype("float64")) + chain = ChunkTransform( + codecs=(NoneReturningAACodec(order=(1, 0)), BytesCodec()), + ) + arr = np.arange(12, dtype="float64").reshape(3, 4) + nd_buf = _make_nd_buffer(arr) + assert chain.encode_chunk(nd_buf, spec) is None diff --git a/tests/test_cli/test_migrate_v3.py b/tests/test_cli/test_migrate_v3.py index 8bda31d208..7213aada12 100644 --- a/tests/test_cli/test_migrate_v3.py +++ b/tests/test_cli/test_migrate_v3.py @@ -16,7 +16,6 @@ from zarr.codecs.numcodecs import LZMA, Delta from zarr.codecs.transpose import TransposeCodec from zarr.codecs.zstd import ZstdCodec -from zarr.core.chunk_grids import RegularChunkGrid from zarr.core.chunk_key_encodings import V2ChunkKeyEncoding from zarr.core.common import JSON, ZarrFormat from zarr.core.dtype.npy.int import UInt8, UInt16 @@ -32,8 +31,6 @@ runner = typer_testing.CliRunner() -NUMCODECS_USER_WARNING = "Numcodecs codecs are not in the Zarr version 3 specification and may not be supported by other zarr implementations." - def test_migrate_array(local_store: LocalStore) -> None: shape = (10, 10) @@ -63,7 +60,7 @@ def test_migrate_array(local_store: LocalStore) -> None: expected_metadata = ArrayV3Metadata( shape=shape, data_type=UInt16(endianness="little"), - chunk_grid=RegularChunkGrid(chunk_shape=chunks), + chunk_grid={"name": "regular", "configuration": {"chunk_shape": chunks}}, chunk_key_encoding=V2ChunkKeyEncoding(separator="."), fill_value=fill_value, codecs=( @@ -316,7 +313,6 @@ def test_migrate_compressor( assert np.all(zarr_array[:] == 1) -@pytest.mark.filterwarnings(f"ignore:{NUMCODECS_USER_WARNING}:UserWarning") def test_migrate_numcodecs_compressor(local_store: LocalStore) -> None: """Test migration of a numcodecs compressor without a zarr.codecs equivalent.""" @@ -360,7 +356,6 @@ def test_migrate_numcodecs_compressor(local_store: LocalStore) -> None: assert np.all(zarr_array[:] == 1) -@pytest.mark.filterwarnings(f"ignore:{NUMCODECS_USER_WARNING}:UserWarning") def test_migrate_filter(local_store: LocalStore) -> None: filter_v2 = numcodecs.Delta(dtype=" None: fill_value=0, ) - with pytest.warns(UserWarning, match=NUMCODECS_USER_WARNING): - result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) assert result.exit_code == 1 assert isinstance(result.exception, TypeError) @@ -548,8 +542,7 @@ def test_migrate_incorrect_compressor(local_store: LocalStore) -> None: fill_value=0, ) - with pytest.warns(UserWarning, match=NUMCODECS_USER_WARNING): - result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) assert result.exit_code == 1 assert isinstance(result.exception, TypeError) diff --git a/tests/test_coalesce.py b/tests/test_coalesce.py new file mode 100644 index 0000000000..cb8ff29ec7 --- /dev/null +++ b/tests/test_coalesce.py @@ -0,0 +1,674 @@ +# tests/test_coalesce.py +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +import pytest + +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + SuffixByteRequest, +) +from zarr.core._coalesce import ( + coalesce_ranges, + coalesced_get, +) +from zarr.core.buffer import Buffer, default_buffer_prototype + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable, Mapping, Sequence + + +def _buf(data: bytes) -> Buffer: + return default_buffer_prototype().buffer.from_bytes(data) + + +@dataclass +class FakeFetch: + """Records every call and serves canned bytes from an in-memory blob.""" + + blob: bytes + key_exists: bool = True + raise_on: Callable[[ByteRequest | None], bool] | None = None + calls: list[ByteRequest | None] = field(default_factory=list) + + async def __call__(self, byte_range: ByteRequest | None) -> Buffer | None: + self.calls.append(byte_range) + if not self.key_exists: + return None + if self.raise_on is not None and self.raise_on(byte_range): + raise OSError("injected") + if byte_range is None: + return _buf(self.blob) + if isinstance(byte_range, RangeByteRequest): + return _buf(self.blob[byte_range.start : byte_range.end]) + if isinstance(byte_range, OffsetByteRequest): + return _buf(self.blob[byte_range.offset :]) + if isinstance(byte_range, SuffixByteRequest): + return _buf(self.blob[-byte_range.suffix :]) + raise AssertionError(f"unknown byte_range {byte_range!r}") + + +async def _collect( + agen: AsyncIterator[Sequence[tuple[int, Buffer | None]]], +) -> list[list[tuple[int, Buffer | None]]]: + """Drain an async generator of groups into a list of lists of tuples.""" + return [list(group) async for group in agen] + + +def _contents(groups: list[list[tuple[int, Buffer | None]]]) -> dict[int, bytes]: + """Flatten to {index: bytes}.""" + result: dict[int, bytes] = {} + for group in groups: + for idx, buf in group: + assert buf is not None + result[idx] = buf.to_bytes() + return result + + +# --------------------------------------------------------------------------- +# Shared coalescing-knob bundles. Each is a complete mapping of all three +# kwargs to splat into `coalesced_get`; `coalesce_ranges` ignores +# `max_concurrency`. The leaf functions in `_coalesce.py` require all knobs +# explicitly — `Store.get_ranges` is the public entry point and owns the +# canonical defaults. Tests pick their own values appropriate to the scenario. +# --------------------------------------------------------------------------- + +# Permissive default for tests that don't care about specific thresholds. Mirrors +# `Store.get_ranges`'s public defaults but the test file owns this independently +# of any production constants. +DEFAULT: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": 1 << 20, + "max_coalesced_bytes": 16 << 20, +} +"""Permissive defaults; mirrors `Store.get_ranges`'s baseline.""" + +MERGE_GAP_50: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": 50, + "max_coalesced_bytes": 1 << 20, +} +"""Merge ranges within 50 bytes of each other.""" + +NO_MERGE: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, +} +"""No merging: any positive gap is > -1, so no pair ever coalesces.""" + +CAP_50: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": 1000, + "max_coalesced_bytes": 50, +} +"""Gap permissive but merged size capped at 50 bytes.""" + + +def _grouping(opts: Mapping[str, int]) -> dict[str, int]: + """Return only the grouping knobs from a full options bundle. + + `coalesce_ranges` rejects `max_concurrency`; this lets test bundles be + full kwargs maps (for `coalesced_get`) and still be passed to the pure + planner via splat. + """ + return {k: v for k, v in opts.items() if k != "max_concurrency"} + + +# A deterministic blob used for content-sensitive cases: byte i == (i % 256). +_INDEXED_BLOB = bytes(i % 256 for i in range(10_000)) + + +# --------------------------------------------------------------------------- +# Parametrized structural/content tests (cases without async timing or errors). +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class StructuralCase: + """One row of the parametrized structure-and-contents table.""" + + id: str + """pytest id for the case.""" + ranges: list[ByteRequest | None] + """Input to coalesced_get.""" + options: Mapping[str, int] + """Coalescing knobs to splat into `coalesced_get`.""" + expected_group_sizes: list[int] + """Sorted list of group tuple-counts (order-independent).""" + expected_contents: dict[int, bytes] | None = None + """{input_index: bytes} to verify bytes, or None to skip the content check.""" + expected_n_fetches: int | None = None + """Exact number of calls to the fetch callable, or None to skip the check.""" + + +_STRUCTURAL_CASES: list[StructuralCase] = [ + StructuralCase( + id="empty-input", + ranges=[], + options=DEFAULT, + expected_group_sizes=[], + expected_n_fetches=0, + ), + StructuralCase( + id="single-range", + ranges=[RangeByteRequest(2, 5)], + options=DEFAULT, + expected_group_sizes=[1], + expected_contents={0: _INDEXED_BLOB[2:5]}, + expected_n_fetches=1, + ), + StructuralCase( + id="disjoint-3-no-merge", + ranges=[ + RangeByteRequest(0, 10), + RangeByteRequest(200, 210), + RangeByteRequest(500, 510), + ], + options=MERGE_GAP_50, + expected_group_sizes=[1, 1, 1], + expected_contents={ + 0: _INDEXED_BLOB[0:10], + 1: _INDEXED_BLOB[200:210], + 2: _INDEXED_BLOB[500:510], + }, + expected_n_fetches=3, + ), + StructuralCase( + id="adjacent-3-one-merged-group", + ranges=[ + RangeByteRequest(0, 5), + RangeByteRequest(10, 15), + RangeByteRequest(20, 25), + ], + options=MERGE_GAP_50, + expected_group_sizes=[3], + expected_contents={ + 0: _INDEXED_BLOB[0:5], + 1: _INDEXED_BLOB[10:15], + 2: _INDEXED_BLOB[20:25], + }, + expected_n_fetches=1, + ), + StructuralCase( + id="two-clusters-one-singleton", + ranges=[ + RangeByteRequest(0, 10), + RangeByteRequest(20, 30), + RangeByteRequest(500, 510), + ], + options=MERGE_GAP_50, + expected_group_sizes=[1, 2], + expected_contents={ + 0: _INDEXED_BLOB[0:10], + 1: _INDEXED_BLOB[20:30], + 2: _INDEXED_BLOB[500:510], + }, + expected_n_fetches=2, + ), + StructuralCase( + id="uncoalescable-mixed-with-range", + ranges=[ + RangeByteRequest(0, 3), + OffsetByteRequest(5), + SuffixByteRequest(2), + None, + ], + options=DEFAULT, + expected_group_sizes=[1, 1, 1, 1], + expected_contents={ + 0: _INDEXED_BLOB[0:3], + 1: _INDEXED_BLOB[5:], + 2: _INDEXED_BLOB[-2:], + 3: _INDEXED_BLOB, + }, + expected_n_fetches=4, + ), + StructuralCase( + id="shuffled-input-indices-preserved", + ranges=[ + RangeByteRequest(500, 510), + RangeByteRequest(0, 10), + RangeByteRequest(200, 210), + RangeByteRequest(300, 310), + ], + options=MERGE_GAP_50, + expected_group_sizes=[1, 1, 1, 1], + expected_contents={ + 0: _INDEXED_BLOB[500:510], + 1: _INDEXED_BLOB[0:10], + 2: _INDEXED_BLOB[200:210], + 3: _INDEXED_BLOB[300:310], + }, + expected_n_fetches=4, + ), + StructuralCase( + id="cap-prevents-merge-of-close-ranges", + # 20 + 20 gap + 20 = 60-byte merged span > cap of 50. + ranges=[RangeByteRequest(0, 20), RangeByteRequest(40, 60)], + options=CAP_50, + expected_group_sizes=[1, 1], + expected_n_fetches=2, + ), + StructuralCase( + id="single-range-larger-than-cap-passes-through", + # Cap only applies to MERGE decisions; a lone oversized range still fetches. + ranges=[RangeByteRequest(0, 200)], + options=CAP_50, + expected_group_sizes=[1], + expected_contents={0: _INDEXED_BLOB[0:200]}, + expected_n_fetches=1, + ), +] + + +@pytest.mark.parametrize("case", _STRUCTURAL_CASES, ids=lambda c: c.id) +async def test_coalescing_structure_and_contents(case: StructuralCase) -> None: + """Group structure, byte contents, and fetch-call count for the deterministic cases.""" + fetch = FakeFetch(_INDEXED_BLOB) + groups = await _collect(coalesced_get(fetch, case.ranges, **case.options)) + + assert sorted(len(g) for g in groups) == sorted(case.expected_group_sizes) + + if case.expected_contents is not None: + assert _contents(groups) == case.expected_contents + + if case.expected_n_fetches is not None: + assert len(fetch.calls) == case.expected_n_fetches + + +# --------------------------------------------------------------------------- +# Focused non-parametrized tests for cases with distinctive assertion shapes. +# --------------------------------------------------------------------------- + + +async def test_within_group_ordering_is_start_offset() -> None: + """Within a merged group, tuples are ordered by start offset, not input order.""" + fetch = FakeFetch(_INDEXED_BLOB) + # Two ranges that merge; one has a later start but is listed first in input. + ranges: list[ByteRequest | None] = [RangeByteRequest(20, 25), RangeByteRequest(0, 5)] + groups = await _collect(coalesced_get(fetch, ranges, **MERGE_GAP_50)) + assert len(groups) == 1 + # Input index 1 (start=0) comes first, then 0 (start=20). + assert [idx for idx, _ in groups[0]] == [1, 0] + + +async def test_adjacent_ranges_fire_single_fetch_spanning_merged_region() -> None: + """Verify the merged fetch covers exactly the span from min-start to max-end.""" + fetch = FakeFetch(_INDEXED_BLOB) + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 5), + RangeByteRequest(10, 15), + RangeByteRequest(20, 25), + ] + await _collect(coalesced_get(fetch, ranges, **MERGE_GAP_50)) + assert len(fetch.calls) == 1 + call = fetch.calls[0] + assert isinstance(call, RangeByteRequest) + assert call.start == 0 + assert call.end == 25 + + +# --------------------------------------------------------------------------- +# Concurrency and cancellation. +# --------------------------------------------------------------------------- + + +async def test_max_concurrency_is_honored() -> None: + """With 10 non-mergeable ranges and max_concurrency=3, peak in-flight must not exceed 3.""" + in_flight = 0 + peak = 0 + lock = asyncio.Lock() + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + nonlocal in_flight, peak + async with lock: + in_flight += 1 + peak = max(peak, in_flight) + # give the scheduler a chance to run other tasks + await asyncio.sleep(0.01) + async with lock: + in_flight -= 1 + return _buf(b"x") + + ranges: list[ByteRequest | None] = [RangeByteRequest(i * 1000, i * 1000 + 1) for i in range(10)] + opts: Mapping[str, int] = { + "max_gap_bytes": 0, # force no merging + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 3, + } + async for _group in coalesced_get(fetch, ranges, **opts): + pass + assert peak <= 3 + assert peak >= 2 # must have been some real concurrency + + +async def test_consumer_break_cancels_pending_fetches() -> None: + """Breaking out of the async for should cancel pending fetches rather than let them complete.""" + completed_calls = 0 + cancelled_calls = 0 + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + nonlocal completed_calls, cancelled_calls + assert isinstance(byte_range, RangeByteRequest) + start = byte_range.start + try: + # First fetch returns fast so the async-for body runs and can break. + # Later fetches sleep long enough that cancellation has room to land. + await asyncio.sleep(0.001 if start == 0 else 2.0) + except asyncio.CancelledError: + cancelled_calls += 1 + raise + completed_calls += 1 + return _buf(b"x") + + opts: Mapping[str, int] = { + "max_gap_bytes": -1, # no merging + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 3, + } + ranges: list[ByteRequest | None] = [RangeByteRequest(i * 1000, i * 1000 + 1) for i in range(6)] + + agen = coalesced_get(fetch, ranges, **opts) + async for _group in agen: + break + # Explicitly close the generator so its finally block runs (cancelling + # in-flight tasks) before we make assertions. + await agen.aclose() + + # The fast task completes; the remaining tasks are either cancelled while + # sleeping (raising CancelledError into the user try block) or cancelled + # while still waiting on the semaphore (which doesn't enter the try at all). + # Either way, none of them should be allowed to complete. + assert completed_calls == 1 + assert cancelled_calls >= 1 + assert completed_calls + cancelled_calls <= len(ranges) + + +# --------------------------------------------------------------------------- +# Key-missing semantics. +# --------------------------------------------------------------------------- + + +async def test_key_missing_from_first_call_raises() -> None: + """If the very first fetch returns None, the iterator raises an ExceptionGroup containing FileNotFoundError.""" + fetch = FakeFetch(b"x" * 100, key_exists=False) + ranges: list[ByteRequest | None] = [RangeByteRequest(0, 10), RangeByteRequest(20, 30)] + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await _collect(coalesced_get(fetch, ranges, **DEFAULT)) + + +@pytest.mark.parametrize( + "byte_range", + [OffsetByteRequest(5), SuffixByteRequest(5), None], + ids=["offset", "suffix", "none"], +) +async def test_key_missing_on_uncoalescable_input_raises( + byte_range: ByteRequest | None, +) -> None: + """Uncoalescable inputs take a distinct path; key-missing must still raise (wrapped in a group).""" + fetch = FakeFetch(b"x" * 100, key_exists=False) + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await _collect(coalesced_get(fetch, [byte_range], **DEFAULT)) + + +async def test_key_missing_mid_stream_raises_after_earlier_groups() -> None: + """If a later fetch returns None, earlier-completed groups yield before the raise.""" + call_count = 0 + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + nonlocal call_count + call_count += 1 + # Deterministic: first call serves, second returns None. + await asyncio.sleep(0.01 if call_count == 1 else 0.02) + if call_count >= 2: + return None + return _buf(b"ok") + + opts: Mapping[str, int] = { + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 1, # serialize for determinism + } + ranges: list[ByteRequest | None] = [RangeByteRequest(0, 2), RangeByteRequest(100, 102)] + agen = coalesced_get(fetch, ranges, **opts) + first = await anext(agen) + assert len(first) == 1 + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + + +async def test_key_missing_mid_stream_with_concurrency_cancels_late_arrivals() -> None: + """ + Under max_concurrency > 1, a mid-stream miss should raise FileNotFoundError + and cancel still-in-flight unrelated tasks rather than wait for them. + """ + late_gate = asyncio.Event() + miss_fired = asyncio.Event() + # Driven by the test body after the first successful yield, so the miss + # task can't race past the start=0 result. + fire_miss = asyncio.Event() + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + assert isinstance(byte_range, RangeByteRequest) + start = byte_range.start + if start == 0: + return _buf(b"ok") + if start == 1000: + # Wait for the test to give the green light before returning None. + # This makes ordering deterministic regardless of scheduling. + await asyncio.wait_for(fire_miss.wait(), timeout=5.0) + miss_fired.set() + return None + # Late arrivals would block on this gate; they should be cancelled + # before they ever return. + await asyncio.wait_for(late_gate.wait(), timeout=5.0) + return _buf(b"ok") + + opts: Mapping[str, int] = { + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 3, + } + ranges: list[ByteRequest | None] = [RangeByteRequest(i * 1000, i * 1000 + 1) for i in range(7)] + + agen = coalesced_get(fetch, ranges, **opts) + first = await anext(agen) + assert len(first) == 1 + idx, buf = first[0] + assert idx == 0 + assert buf is not None + # Now that #0 has yielded, signal the miss task to return None. + fire_miss.set() + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + assert miss_fired.is_set() + # Sanity: late_gate was never set, so the cancellation path is what completed the test. + assert not late_gate.is_set() + + +# --------------------------------------------------------------------------- +# Error propagation. +# --------------------------------------------------------------------------- + + +async def test_fetch_raises_propagates() -> None: + """An exception raised by fetch propagates on the yield that produced the failing group.""" + fetch = FakeFetch( + _INDEXED_BLOB, + raise_on=lambda r: isinstance(r, RangeByteRequest) and r.start >= 100, + ) + opts: Mapping[str, int] = { + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 1, + } + ranges: list[ByteRequest | None] = [RangeByteRequest(0, 10), RangeByteRequest(200, 210)] + with pytest.RaisesGroup(pytest.RaisesExc(OSError, match="injected")): + await _collect(coalesced_get(fetch, ranges, **opts)) + + +# --------------------------------------------------------------------------- +# Property-style coverage invariant. +# --------------------------------------------------------------------------- + + +async def test_coverage_invariant_random_inputs() -> None: + """For any random RangeByteRequest input, every input index appears exactly once.""" + import random + + rng = random.Random(42) + fetch = FakeFetch(_INDEXED_BLOB) + + ranges: list[ByteRequest | None] = [] + for _ in range(50): + start = rng.randint(0, 9000) + length = rng.randint(1, 500) + ranges.append(RangeByteRequest(start, start + length)) + + groups = await _collect(coalesced_get(fetch, ranges, **DEFAULT)) + seen: list[int] = [idx for group in groups for idx, _buf in group] + assert sorted(seen) == list(range(len(ranges))) + + flat = _contents(groups) + for i, r in enumerate(ranges): + assert isinstance(r, RangeByteRequest) + assert flat[i] == _INDEXED_BLOB[r.start : r.end] + + +# --------------------------------------------------------------------------- +# Pure-function tests for coalesce_ranges (no async, no fetch). +# --------------------------------------------------------------------------- + + +def test_coalesce_ranges_empty_input() -> None: + groups, uncoalescable = coalesce_ranges([], max_gap_bytes=1 << 20, max_coalesced_bytes=16 << 20) + assert groups == [] + assert uncoalescable == [] + + +def test_coalesce_ranges_separates_coalescable_from_uncoalescable() -> None: + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + OffsetByteRequest(100), + SuffixByteRequest(5), + None, + RangeByteRequest(20, 30), + ] + groups, uncoalescable = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + + # Both range requests fall within MERGE_GAP_50's gap budget. + assert len(groups) == 1 + assert [idx for idx, _ in groups[0]] == [0, 4] + + # Non-RangeByteRequest entries preserve their original input indices. + assert [(idx, type(req).__name__ if req else None) for idx, req in uncoalescable] == [ + (1, "OffsetByteRequest"), + (2, "SuffixByteRequest"), + (3, None), + ] + + +def test_coalesce_ranges_no_merge_when_gap_exceeds_budget() -> None: + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + RangeByteRequest(200, 210), + RangeByteRequest(500, 510), + ] + groups, uncoalescable = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert uncoalescable == [] + assert [len(g) for g in groups] == [1, 1, 1] + assert [idx for g in groups for idx, _ in g] == [0, 1, 2] + + +def test_coalesce_ranges_merges_within_gap_budget() -> None: + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 5), + RangeByteRequest(10, 15), + RangeByteRequest(20, 25), + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert len(groups) == 1 + assert [idx for idx, _ in groups[0]] == [0, 1, 2] + + +def test_coalesce_ranges_respects_max_coalesced_bytes() -> None: + # Gap budget is permissive (1000), but the merged span would exceed CAP_50's + # 50-byte cap, so the second range starts a new group. + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 30), + RangeByteRequest(40, 80), + ] + groups, _ = coalesce_ranges(ranges, **_grouping(CAP_50)) + assert [len(g) for g in groups] == [1, 1] + + +def test_coalesce_ranges_groups_are_sorted_by_start() -> None: + """Input order is irrelevant; groups always emerge in start-offset order.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(500, 510), + RangeByteRequest(0, 10), + RangeByteRequest(20, 30), + RangeByteRequest(200, 210), + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + # First group is the {0-10, 20-30} cluster (from input indices 1, 2). + # Then the {200-210} singleton, then {500-510}. + flat = [idx for g in groups for idx, _ in g] + assert flat == [1, 2, 3, 0] + # Within each group, members are sorted by start. + for g in groups: + starts = [r.start for _, r in g] + assert starts == sorted(starts) + + +def test_coalesce_ranges_overlapping_ranges_merge() -> None: + """Nested/overlapping ranges have a non-positive 'gap' and always merge.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 100), + RangeByteRequest(50, 60), # nested + RangeByteRequest(80, 120), # overlaps + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert len(groups) == 1 + assert [idx for idx, _ in groups[0]] == [0, 1, 2] + + +def test_coalesce_ranges_running_end_handles_nesting() -> None: + """A subsequent range fully inside the running span must not extend group_end backwards.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 1000), # group_end=1000 + RangeByteRequest(100, 200), # nested; group_end stays at 1000 + RangeByteRequest(990, 1010), # gap = -10 from running end, still merges + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert len(groups) == 1 + assert {idx for idx, _ in groups[0]} == {0, 1, 2} + + +def test_coalesce_ranges_only_uncoalescable_inputs() -> None: + ranges: list[ByteRequest | None] = [None, OffsetByteRequest(10), SuffixByteRequest(5)] + groups, uncoalescable = coalesce_ranges( + ranges, max_gap_bytes=1 << 20, max_coalesced_bytes=16 << 20 + ) + assert groups == [] + assert [idx for idx, _ in uncoalescable] == [0, 1, 2] + + +def test_coalesce_ranges_total_index_coverage() -> None: + """Every input index appears exactly once across groups + uncoalescable.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + None, + RangeByteRequest(15, 25), + OffsetByteRequest(100), + RangeByteRequest(30, 40), + ] + groups, uncoalescable = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + seen = sorted([idx for g in groups for idx, _ in g] + [idx for idx, _ in uncoalescable]) + assert seen == list(range(len(ranges))) diff --git a/tests/test_codec_entrypoints.py b/tests/test_codec_entrypoints.py index fc7b79fe54..69cd0a1577 100644 --- a/tests/test_codec_entrypoints.py +++ b/tests/test_codec_entrypoints.py @@ -7,7 +7,7 @@ @pytest.mark.usefixtures("set_path") @pytest.mark.parametrize("codec_name", ["TestEntrypointCodec", "TestEntrypointGroup.Codec"]) def test_entrypoint_codec(codec_name: str) -> None: - config.set({"codecs.test": "package_with_entrypoint." + codec_name}) + config.set({"codecs.test": f"package_with_entrypoint.{codec_name}"}) cls_test = zarr.registry.get_codec_class("test") assert cls_test.__qualname__ == codec_name @@ -24,7 +24,7 @@ def test_entrypoint_pipeline() -> None: def test_entrypoint_buffer(buffer_name: str) -> None: config.set( { - "buffer": "package_with_entrypoint." + buffer_name, + "buffer": f"package_with_entrypoint.{buffer_name}", "ndbuffer": "package_with_entrypoint.TestEntrypointNDBuffer", } ) diff --git a/tests/test_codec_pipeline.py b/tests/test_codec_pipeline.py new file mode 100644 index 0000000000..b069792fd8 --- /dev/null +++ b/tests/test_codec_pipeline.py @@ -0,0 +1,323 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +pytest.importorskip("hypothesis") + +import hypothesis.strategies as st +from hypothesis import given + +import zarr +from zarr.codecs import BytesCodec, CastValue, GzipCodec, TransposeCodec +from zarr.core.array import _get_chunk_spec +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.codec_pipeline import codecs_from_list +from zarr.core.config import config as zarr_config +from zarr.core.indexing import BasicIndexer +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from zarr.abc.codec import Codec + + +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None]: + """Enable rectilinear chunks for all tests in this module.""" + with zarr_config.set({"array.rectilinear_chunks": True}): + yield + + +pipeline_paths = [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", +] + + +@pytest.fixture(params=pipeline_paths, ids=["batched", "sync"]) +def pipeline_class(request: pytest.FixtureRequest) -> Generator[str]: + """Temporarily set the codec pipeline class for the test.""" + path = request.param + with zarr_config.set({"codec_pipeline.path": path}): + yield path + + +# --------------------------------------------------------------------------- +# GetResult status tests (low-level pipeline API) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("write_slice", "read_slice", "expected_statuses"), + [ + (slice(None), slice(None), ("present", "present", "present")), + (slice(0, 2), slice(None), ("present", "missing", "missing")), + (None, slice(None), ("missing", "missing", "missing")), + ], +) +async def test_read_returns_get_results( + pipeline_class: str, + write_slice: slice | None, + read_slice: slice, + expected_statuses: tuple[str, ...], +) -> None: + """CodecPipeline.read returns GetResult with correct statuses.""" + store = MemoryStore() + arr = zarr.open_array(store, mode="w", shape=(6,), chunks=(2,), dtype="int64", fill_value=-1) + + if write_slice is not None: + arr[write_slice] = 0 + + async_arr = arr._async_array + pipeline = async_arr.codec_pipeline + metadata = async_arr.metadata + + prototype = default_buffer_prototype() + config = async_arr.config + indexer = BasicIndexer( + read_slice, + shape=metadata.shape, + chunk_grid=async_arr._chunk_grid, + ) + + out_buffer = prototype.nd_buffer.empty( + shape=indexer.shape, + dtype=metadata.dtype.to_native_dtype(), + order=config.order, + ) + + results = await pipeline.read( + [ + ( + async_arr.store_path / metadata.encode_chunk_key(chunk_coords), + _get_chunk_spec(metadata, async_arr._chunk_grid, chunk_coords, config, prototype), + chunk_selection, + out_selection, + is_complete_chunk, + ) + for chunk_coords, chunk_selection, out_selection, is_complete_chunk in indexer + ], + out_buffer, + drop_axes=indexer.drop_axes, + ) + + assert len(results) == len(expected_statuses) + for result, expected_status in zip(results, expected_statuses, strict=True): + assert result["status"] == expected_status + + +# --------------------------------------------------------------------------- +# write_empty_chunks / read_missing_chunks config tests +# --------------------------------------------------------------------------- + + +async def test_write_empty_chunks_false_no_store(pipeline_class: str) -> None: + """With write_empty_chunks=False, fill_value-only chunks should not be stored.""" + store: dict[str, Any] = {} + arr = zarr.create_array( + store=store, + shape=(20,), + dtype="float64", + chunks=(10,), + shards=None, + compressors=None, + fill_value=0.0, + config={"write_empty_chunks": False}, + ) + arr[:] = 0.0 # all fill_value + + # Chunks should NOT be persisted + assert "c/0" not in store + assert "c/1" not in store + + # But reading should still return fill values + np.testing.assert_array_equal(arr[:], np.zeros(20, dtype="float64")) + + +try: + import cast_value_rs # noqa: F401 + + _HAS_CAST_VALUE_RS = True +except ModuleNotFoundError: + _HAS_CAST_VALUE_RS = False + +requires_cast_value_rs = pytest.mark.skipif( + not _HAS_CAST_VALUE_RS, reason="cast-value-rs not installed" +) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + ("source_dtype", "target_dtype"), + [ + # Source is single-byte (no endianness); target is multi-byte (has endianness). + # Without the fix, BytesCodec.evolve_from_array_spec sees the source dtype, + # strips its `endian` to None, and then chokes when the chunk_spec dtype + # gets transformed to the multi-byte target before bytes-decoding. + ("int8", "int16"), + ("uint8", "int32"), + ("int8", "float32"), + # Source is multi-byte; target is single-byte (the reverse direction also + # exercises the spec-threading logic). + ("int16", "int8"), + ], +) +def test_codec_pipeline_threads_dtype_through_evolve(source_dtype: str, target_dtype: str) -> None: + """Regression for #3937: each codec must be evolved against the spec it + will see at runtime, not the original array spec. cast_value transforms + the dtype between AA codecs and the array->bytes serializer.""" + arr = zarr.create_array( + store={}, + shape=(4,), + chunks=(4,), + dtype=source_dtype, + fill_value=0, + filters=[CastValue(data_type=target_dtype)], + serializer=BytesCodec(endian="little"), + compressors=[], + zarr_format=3, + overwrite=True, + ) + arr[:] = np.asarray([0, 1, 2, 3], dtype=source_dtype) + np.testing.assert_array_equal(arr[:], np.asarray([0, 1, 2, 3], dtype=source_dtype)) + + +def test_evolve_threads_spec_preserving_serializer_endian(pipeline_class: str) -> None: + """Regression for #3937, dependency-free variant. + + `evolve_from_array_spec` must thread the spec FORWARD through the codec chain: + each codec is evolved against the spec produced by the previous one, not the + original array spec. An array->array codec that widens the dtype from a + single-byte type (no endianness) to a multi-byte type means the BytesCodec + serializer must be evolved against the *widened* dtype — otherwise it sees + the single-byte source, strips its `endian` to None, and later fails to + decode the multi-byte data. + + The original regression test for this needs `cast_value_rs` (so it only runs + in the optional-deps CI job). This variant uses a minimal dtype-widening AA + codec stub, so it runs everywhere and on both pipelines via `pipeline_class`. + """ + from dataclasses import dataclass + + from zarr.abc.codec import ArrayArrayCodec + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.dtype import get_data_type_from_native_dtype + from zarr.registry import get_pipeline_class + + @dataclass(frozen=True) + class _WidenToInt16(ArrayArrayCodec): + """Test-only AA codec: reports the encoded dtype as int16 (no real encode).""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "_widen_to_int16"} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _WidenToInt16: + return cls() + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + from dataclasses import replace + + return replace(chunk_spec, dtype=get_data_type_from_native_dtype(np.dtype("int16"))) + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + async def _encode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + zdtype = get_data_type_from_native_dtype(np.dtype("int8")) # single-byte source + spec = ArraySpec( + shape=(4,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + + from zarr.core.codec_pipeline import BatchedCodecPipeline, FusedCodecPipeline + + pipeline = get_pipeline_class().from_codecs((_WidenToInt16(), BytesCodec(endian="little"))) + evolved = pipeline.evolve_from_array_spec(spec) + # Both concrete pipelines expose `array_bytes_codec`; narrow off the ABC. + assert isinstance(evolved, (BatchedCodecPipeline, FusedCodecPipeline)) + serializer = evolved.array_bytes_codec + + # The serializer must keep its little-endian setting: it is evolved against + # the widened (int16) dtype, not the single-byte source. + assert isinstance(serializer, BytesCodec) + assert serializer.endian is not None, ( + "BytesCodec serializer lost its `endian` — evolve_from_array_spec did not " + "thread the dtype-widening AA codec's spec into the serializer" + ) + + +# Property-based check of codecs_from_list ordering validation. +# +# Valid codec orderings are exactly: (ArrayArrayCodec)* (ArrayBytesCodec) +# (BytesBytesCodec)*. codecs_from_list walks adjacent pairs and must raise +# TypeError the moment a codec appears in a structurally invalid position -- +# notably, a BytesBytesCodec immediately following an ArrayArrayCodec with no +# ArrayBytesCodec in between (which previously built an error message but never +# raised it, falling through to an unrelated ValueError instead). +_AA = "AA" # ArrayArrayCodec -> TransposeCodec +_AB = "AB" # ArrayBytesCodec -> BytesCodec +_BB = "BB" # BytesBytesCodec -> GzipCodec + +_CODEC_FACTORY: dict[str, Callable[[], Codec]] = { + _AA: lambda: TransposeCodec(order=(0, 1)), + _AB: BytesCodec, + _BB: GzipCodec, +} + + +def _expected_codec_order_outcome(labels: list[str]) -> str: + """Independently predict codecs_from_list's outcome: 'TypeError', + 'ValueError' or 'ok', mirroring its left-to-right scan and the order in + which it checks ordering violations (TypeError) vs. the ArrayBytes-count + constraints (ValueError).""" + prev = None + seen_array_bytes = False + for cur in labels: + if cur == _AA: + if prev in (_AB, _BB): + return "TypeError" + elif cur == _AB: + if prev == _BB: + return "TypeError" + if seen_array_bytes: + return "ValueError" # two ArrayBytesCodecs + seen_array_bytes = True + else: # _BB + if prev == _AA: + return "TypeError" + prev = cur + if not seen_array_bytes: + return "ValueError" # Required ArrayBytesCodec was not found + return "ok" + + +@given(labels=st.lists(st.sampled_from([_AA, _AB, _BB]), min_size=1, max_size=5)) +def test_codecs_from_list_outcome_matches_order_rules(labels: list[str]) -> None: + codecs = [_CODEC_FACTORY[label]() for label in labels] + expected = _expected_codec_order_outcome(labels) + if expected == "TypeError": + with pytest.raises(TypeError): + codecs_from_list(codecs) + elif expected == "ValueError": + with pytest.raises(ValueError): + codecs_from_list(codecs) + else: + # Valid ordering: must classify without raising. + aa, _ab, bb = codecs_from_list(codecs) + assert labels.count(_AA) == len(aa) + assert labels.count(_BB) == len(bb) diff --git a/tests/test_codec_pipeline_suite.py b/tests/test_codec_pipeline_suite.py new file mode 100644 index 0000000000..f0376d185a --- /dev/null +++ b/tests/test_codec_pipeline_suite.py @@ -0,0 +1,590 @@ +"""Shared codec-pipeline behavior suite, run against EVERY codec pipeline. + +The defining property of a codec pipeline is that the array semantics it +produces must be identical no matter which pipeline is configured. To make +"one pipeline diverges from the others" structurally hard to ship, every +pipeline-agnostic behavior test lives as a method on ``CodecPipelineTests`` and +is instantiated once per pipeline (``TestBatchedPipeline`` / ``TestFusedPipeline``). + +Each test also runs over a *store axis* that exercises both code paths the +synchronous pipelines branch on: + +* ``sync`` -> ``MemoryStore`` (full sync surface: fast path) +* ``async`` -> ``_NoSyncIOStore(MemoryStore())`` (NOT sync-capable: async fallback) + +The async axis is deliberate: a regression that only affects the async fallback +of the default pipeline (e.g. a codec-spec-evolution bug that surfaces only on +remote stores) is invisible if every test runs on MemoryStore. Running the same +battery over a non-sync store closes that gap. + +Pipeline-specific tests (construction, ``from_codecs``, the byte-range write +fast path, etc.) stay in their own modules; only behavior that ALL pipelines +must share belongs here. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import numcodecs +import numpy as np +import pytest + +import zarr +from zarr.codecs import BytesCodec, GzipCodec, ShardingCodec, TransposeCodec +from zarr.core.config import config as zarr_config +from zarr.errors import ChunkNotFoundError +from zarr.storage import MemoryStore +from zarr.testing.store import LatencyStore + +if TYPE_CHECKING: + from collections.abc import Iterator + + from zarr.abc.store import Store + from zarr.codecs.sharding import SubchunkWriteOrder + + +# --- store axis: a sync store and a non-sync (async-fallback) store ---------- + +STORE_KINDS = ["sync", "async"] + + +class _NoSyncIOStore(LatencyStore): + """An in-memory store that advertises no sync IO capability, so a + synchronous pipeline must fall back to its async path. (A plain wrapper + won't do: `WrapperStore` forwards the wrapped store's sync capability.)""" + + @property + def _supports_sync_io(self) -> bool: + return False + + +def _make_store(kind: str) -> Store: + if kind == "sync": + # MemoryStore supports get_sync/set_sync -> synchronous fast path. + return MemoryStore() + if kind == "async": + return _NoSyncIOStore(MemoryStore(), get_latency=0.0, set_latency=0.0) + raise AssertionError(kind) + + +# --- scenario model ---------------------------------------------------------- +# +# Most pipeline behavior tests have one shape: +# create an array, apply some writes, (optionally) assert which chunk keys +# exist, then assert reads come back correct. A Scenario captures exactly those +# variables so one parametrized test covers them all. Correctness is checked +# against a numpy reference array that the scenario mutates in lock-step with +# the zarr array, so cases don't hand-maintain expected values. + + +@dataclass(frozen=True) +class Scenario: + id: str + array_kwargs: dict[str, Any] + # (selection, value) writes applied in order. value may be a scalar or array. + writes: tuple[tuple[Any, Any], ...] = () + # selections to read back and check against the reference. () means "read all". + reads: tuple[Any, ...] = (slice(None),) + # substrings of chunk keys that must be present / absent after the writes. + # Only checked on the sync store (key layout is identical across stores, but + # we keep it to one axis to avoid asserting store internals twice). + keys_present: tuple[str, ...] = () + keys_absent: tuple[str, ...] = () + + def reference(self) -> np.ndarray: + """The numpy array the scenario's writes should produce, starting from + the array's fill value.""" + kw = self.array_kwargs + shape = kw["shape"] + dtype = np.dtype(kw["dtype"]) + fill = kw.get("fill_value", 0) + ref = np.full(shape, fill, dtype=dtype) + for sel, value in self.writes: + ref[sel] = value + return ref + + +def _val(n: int, dtype: str, offset: int = 1) -> np.ndarray: + return np.arange(offset, offset + n, dtype=dtype) + + +# Common dtype/chunk presets reused below. +_F64 = {"dtype": "float64", "fill_value": 0.0} +_I32 = {"dtype": "int32", "fill_value": -1} + +SCENARIOS: tuple[Scenario, ...] = ( + # --- full-array roundtrips across layouts/codecs ------------------------ + Scenario( + "1d-unsharded-roundtrip", + {"shape": (100,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-sharded-roundtrip", + {"shape": (100,), "chunks": (10,), "shards": (100,), "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-multi-chunk-shard-roundtrip", + {"shape": (100,), "chunks": (10,), "shards": (50,), "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "2d-unsharded-roundtrip", + {"shape": (10, 20), "chunks": (5, 10), "shards": None, "compressors": None, **_I32}, + writes=((slice(None), np.arange(200, dtype="int32").reshape(10, 20)),), + ), + Scenario( + "2d-sharded-roundtrip", + {"shape": (20, 20), "chunks": (5, 5), "shards": (10, 10), "compressors": None, **_I32}, + writes=((slice(None), np.arange(400, dtype="int32").reshape(20, 20)),), + ), + Scenario( + "1d-gzip-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": {"name": "gzip", "configuration": {"level": 1}}, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-zstd-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": {"name": "zstd", "configuration": {"level": 1}}, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-float32-roundtrip", + { + "shape": (50,), + "chunks": (10,), + "shards": None, + "compressors": None, + "dtype": "float32", + "fill_value": 0.0, + }, + writes=((slice(None), _val(50, "float32")),), + ), + # zarr v2 goes through the V2Codec wrapper (filters + compressor), a + # different codec path than the v3 AA/AB/BB chain — and a different sync + # implementation under FusedCodecPipeline. Without these scenarios, v2 was + # only exercised implicitly via whichever pipeline is the global default. + Scenario( + "v2-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": None, + "zarr_format": 2, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "v2-gzip-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": numcodecs.GZip(level=1), + "zarr_format": 2, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + # v2 filters are the other half of the V2Codec wrapper (numcodecs + # array->array filters, a distinct branch from the compressor in + # _encode_sync/_decode_sync). + Scenario( + "v2-filter-gzip-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "filters": numcodecs.Delta(dtype="float64"), + "compressors": numcodecs.GZip(level=1), + "zarr_format": 2, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + # --- read unwritten chunks -> fill value -------------------------------- + Scenario( + "missing-chunks-fill", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": None, + "dtype": "float64", + "fill_value": -7.0, + }, + writes=(), + ), + Scenario( + "missing-chunks-fill-sharded", + { + "shape": (100,), + "chunks": (10,), + "shards": (100,), + "compressors": None, + "dtype": "float64", + "fill_value": -7.0, + }, + writes=(), + ), + # --- partial write, varied read selections ------------------------------ + Scenario( + "partial-write-full-read", + {"shape": (100,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(5, 15), _val(10, "float64")),), + reads=(slice(None),), + ), + Scenario( + "full-write-strided-read", + {"shape": (100,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + reads=(np.s_[::3], np.s_[10:20]), + ), + Scenario( + "partial-write-partial-read-sharded", + {"shape": (100,), "chunks": (10,), "shards": (100,), "compressors": None, **_F64}, + writes=((slice(20, 70), _val(50, "float64")),), + reads=(np.s_[30:60], slice(None)), + ), + # scalar single-element reads from a sharded array hit the sharding codec's + # partial-decode path (_decode_partial_single), distinct from slice reads. + Scenario( + "sharded-scalar-reads-1d", + {"shape": (100,), "chunks": (10,), "shards": (50,), "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + reads=(np.s_[0], np.s_[50], np.s_[99], np.s_[::3]), + ), + Scenario( + "sharded-scalar-reads-2d", + {"shape": (20, 20), "chunks": (5, 5), "shards": (10, 10), "compressors": None, **_I32}, + writes=((slice(None), np.arange(400, dtype="int32").reshape(20, 20)),), + reads=(np.s_[0, 0], np.s_[10, 10], np.s_[19, 19]), + ), + # --- spec-changing codec (transpose): the async-spec-evolution guard ---- + Scenario( + "transpose", + { + "shape": (8, 12), + "chunks": (2, 4), + "shards": None, + "filters": [TransposeCodec(order=(1, 0))], + "serializer": BytesCodec(), + **_I32, + }, + writes=((slice(None), np.arange(96, dtype="int32").reshape(8, 12)),), + reads=(slice(None), np.s_[1:7, 2:10]), + ), + Scenario( + "transpose-gzip", + { + "shape": (8, 12), + "chunks": (2, 4), + "shards": None, + "filters": [TransposeCodec(order=(1, 0))], + "serializer": BytesCodec(), + "compressors": GzipCodec(level=1), + **_I32, + }, + writes=((slice(None), np.arange(96, dtype="int32").reshape(8, 12)),), + reads=(slice(None), np.s_[1:7, 2:10]), + ), + # --- nested sharding ---------------------------------------------------- + Scenario( + "nested-sharding", + { + "shape": (20, 20), + "chunks": (10, 10), + "shards": None, + "compressors": None, + **_I32, + "fill_value": 0, + "serializer": ShardingCodec( + chunk_shape=(10, 10), codecs=[ShardingCodec(chunk_shape=(5, 5))] + ), + }, + writes=((slice(None), np.arange(400, dtype="int32").reshape(20, 20)),), + ), + # --- partial overwrite of an existing shard (merge) --------------------- + Scenario( + "partial-shard-overwrite", + { + "shape": (40,), + "chunks": (4,), + "shards": (40,), + "compressors": None, + **_I32, + "config": {"write_empty_chunks": True}, + }, + writes=( + (slice(None), np.arange(40, dtype="int32")), + (slice(7, 18), _val(11, "int32", 700)), + ), + ), + # --- write_empty_chunks: storage-key presence/absence ------------------- + Scenario( + "write-empty-false-omits-fill-chunk", + { + "shape": (20,), + "chunks": (10,), + "shards": None, + "compressors": None, + **_F64, + "config": {"write_empty_chunks": False}, + }, + writes=((slice(0, 10), _val(10, "float64")), (slice(10, 20), np.zeros(10, "float64"))), + keys_present=("c/0",), + keys_absent=("c/1",), + ), + Scenario( + "write-empty-true-persists-fill-chunk", + { + "shape": (20,), + "chunks": (10,), + "shards": None, + "compressors": None, + **_F64, + "config": {"write_empty_chunks": True}, + }, + writes=((slice(None), np.zeros(20, "float64")),), + keys_present=("c/0", "c/1"), + ), + # default config (no explicit write_empty_chunks) must still skip fill chunks + Scenario( + "default-config-omits-fill-chunk", + {"shape": (20,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(10, 20), np.zeros(10, "float64")),), + keys_absent=("c/1",), + ), +) + + +class CodecPipelineTests: + """Behavior every codec pipeline must satisfy, on sync and async stores. + + Subclasses set ``pipeline_path`` to the fully-qualified pipeline class. + """ + + pipeline_path: str + + @pytest.fixture(autouse=True) + def _use_pipeline(self) -> Iterator[None]: + with zarr_config.set({"codec_pipeline.path": self.pipeline_path}): + yield + + @pytest.fixture(params=STORE_KINDS) + def store(self, request: pytest.FixtureRequest) -> Store: + return _make_store(request.param) + + @staticmethod + def _chunk_keys(store: Store) -> set[str]: + """All non-metadata keys currently in the store (v3 and v2 metadata).""" + import asyncio + + def _is_metadata(key: str) -> bool: + tail = key.rsplit("/", 1)[-1] + return tail in ("zarr.json", ".zarray", ".zattrs", ".zgroup", ".zmetadata") + + async def _list() -> set[str]: + return {k async for k in store.list() if not _is_metadata(k)} + + return asyncio.run(_list()) + + # -- the common shape: create -> write -> [assert keys] -> assert reads ---- + + @pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.id) + def test_scenario(self, store: Store, scenario: Scenario) -> None: + """Create an array, apply the scenario's writes, optionally assert which + chunk keys exist, then assert each read selection matches a numpy + reference. Run against every pipeline (subclass) and store kind (fixture). + """ + arr = zarr.create_array(store=store, **scenario.array_kwargs) + for sel, value in scenario.writes: + arr[sel] = value + + ref = scenario.reference() + for sel in scenario.reads: + np.testing.assert_array_equal( + arr[sel], ref[sel], err_msg=f"{scenario.id}: read {sel!r} mismatch" + ) + + if scenario.keys_present or scenario.keys_absent: + keys = self._chunk_keys(store) + for present in scenario.keys_present: + assert any(present in k for k in keys), (present, keys) + for absent in scenario.keys_absent: + assert not any(absent in k for k in keys), (absent, keys) + + # -- outliers that don't fit the create/write/read scenario shape ---------- + + def test_read_missing_chunks_false_raises(self, store: Store) -> None: + """read_missing_chunks=False makes reading an unwritten chunk an error, + not a fill — a different assertion (raises) than the scenario shape.""" + arr = zarr.create_array( + store=store, + shape=(20,), + dtype="float64", + chunks=(10,), + shards=None, + compressors=None, + fill_value=0.0, + config={"read_missing_chunks": False}, + ) + with pytest.raises(ChunkNotFoundError): + arr[:] + + def test_read_missing_chunks_false_sharded_semantics(self, store: Store) -> None: + """read_missing_chunks=False is a STORE-KEY-level promise on sharded arrays. + + The config exists to help consumers distinguish a transport error from a + truly missing chunk. That distinction applies to store keys: a missing + SHARD key raises ChunkNotFoundError. It does not cleanly apply to inner + subchunks of a shard that was fetched successfully — there is no + transport ambiguity there, the shard index simply records the subchunk + as absent — so missing inner subchunks fill with the fill value rather + than raising. This pins that asymmetry as intentional. + """ + arr = zarr.create_array( + store=store, + shape=(100,), + dtype="float64", + chunks=(10,), + shards=(50,), + compressors=None, + fill_value=-1.0, + config={"read_missing_chunks": False}, + ) + # No shard key exists yet: reading is a missing-store-key error. + with pytest.raises(ChunkNotFoundError): + arr[:] + + # Write one inner chunk of the first shard. The shard key now exists, + # but most inner subchunks are absent from its index. + arr[20:30] = np.arange(10, dtype="float64") + + # Reading across written + absent inner subchunks of the EXISTING shard + # fills rather than raises. + out = arr[15:35] + expected = np.full(20, -1.0) + expected[5:15] = np.arange(10, dtype="float64") + np.testing.assert_array_equal(out, expected) + + # Both halves of the asymmetry in ONE read against the SAME partially + # written array: shard 0 exists (absent subchunks fill), shard 1 has no + # store key (raises) — pins that the raise still fires once some shard + # exists, and not only on a fully-empty array. + with pytest.raises(ChunkNotFoundError): + arr[:] + with pytest.raises(ChunkNotFoundError): + arr[45:55] # spans the existing and the missing shard + + @pytest.mark.parametrize("subchunk_write_order", ["morton", "lexicographic", "colexicographic"]) + def test_partial_write_after_reopen_is_correct( + self, store: Store, subchunk_write_order: SubchunkWriteOrder + ) -> None: + """Has an extra step the scenario shape lacks — a REOPEN between writes. + + Reopening a sharded array and partially overwriting it must read back + correctly regardless of the original subchunk_write_order. subchunk_write_ + order is intentionally NOT recoverable on reopen, so chunk locations on a + write to an existing shard must come from the STORED shard index, not the + (now-default) live order. A non-square inner grid makes the orders + physically distinct, so a wrong offset would corrupt data and fail here. + """ + shape, shard, inner = (6, 4), (6, 4), (2, 2) + arr = zarr.create_array( + store=store, + shape=shape, + dtype="int32", + chunks=shard, + fill_value=-1, + compressors=None, + config={"write_empty_chunks": True}, + serializer=ShardingCodec( + chunk_shape=inner, codecs=[BytesCodec()], subchunk_write_order=subchunk_write_order + ), + ) + ref = np.arange(24, dtype="int32").reshape(shape) + arr[:] = ref + + reopened = zarr.open_array(store=store, mode="r+") + reopened[1:5, 0:3] = 777 # partial overwrite into the existing shard + ref[1:5, 0:3] = 777 + np.testing.assert_array_equal(reopened[:], ref) + + def test_empty_shard_deleted_after_overwrite_to_fill(self, store: Store) -> None: + """A shard written with real data and then fully overwritten back to the + fill value must have its store key deleted, not left as a stale blob. + + This has a mid-sequence key assertion (present after write 1, absent + after write 2) that the create/write/read scenario shape can't express. + """ + arr = zarr.create_array( + store=store, + shape=(16,), + chunks=(4,), + shards=(8,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + arr[0:8] = np.arange(8, dtype="float64") + 1 + assert any("c/0" in k for k in self._chunk_keys(store)) + arr[0:8] = 0.0 + assert not any("c/0" in k for k in self._chunk_keys(store)), ( + "shard should be deleted when fully overwritten to fill value" + ) + + def test_read_write_methods_do_not_branch_on_sharding_codec_type(self) -> None: + """Pipeline read/write must dispatch on supports_partial_encode/decode, + not isinstance(ShardingCodec) — a static guard against type-branching. + + Scoped to this pipeline's own read/write methods (other helpers, e.g. + metadata validation, may legitimately isinstance-check ShardingCodec). + """ + import inspect + import re + + from zarr.registry import get_pipeline_class + + # The autouse _use_pipeline fixture has set codec_pipeline.path to this + # subclass's pipeline; resolve the class it points at and guard that. + # reload_config=False so the fixture's config override is honored + # (reload_config=True re-reads the base config, ignoring the override). + cls = get_pipeline_class(reload_config=False) + + pattern = re.compile(r"isinstance\s*\([^)]*ShardingCodec[^)]*\)") + for method_name in ("read", "write", "read_sync", "write_sync"): + method = getattr(cls, method_name, None) + if method is None: + continue + matches = pattern.findall(inspect.getsource(method)) + assert not matches, ( + f"{cls.__name__}.{method_name} contains an isinstance check on " + f"ShardingCodec; use supports_partial_encode/decode instead. " + f"Matches: {matches}" + ) + + +class TestBatchedPipeline(CodecPipelineTests): + pipeline_path = "zarr.core.codec_pipeline.BatchedCodecPipeline" + + +class TestFusedPipeline(CodecPipelineTests): + pipeline_path = "zarr.core.codec_pipeline.FusedCodecPipeline" diff --git a/tests/test_codecs/test_blosc.py b/tests/test_codecs/test_blosc.py index 0201beb8de..e342dba8bb 100644 --- a/tests/test_codecs/test_blosc.py +++ b/tests/test_codecs/test_blosc.py @@ -1,4 +1,7 @@ +import enum import json +import warnings +from typing import Any, cast import numcodecs import numpy as np @@ -8,7 +11,14 @@ import zarr from zarr.abc.codec import SupportsSyncCodec from zarr.codecs import BloscCodec -from zarr.codecs.blosc import BloscShuffle, Shuffle +from zarr.codecs.blosc import ( + BLOSC_CNAME, + BLOSC_SHUFFLE, + BloscCname, + BloscCnameLiteral, + BloscShuffle, + BloscShuffleLiteral, +) from zarr.core.array_spec import ArrayConfig, ArraySpec from zarr.core.buffer import default_buffer_prototype from zarr.core.dtype import UInt16, get_data_type_from_native_dtype @@ -61,16 +71,26 @@ async def test_blosc_evolve(dtype: str) -> None: assert blosc_configuration_json["shuffle"] == "shuffle" -@pytest.mark.parametrize("shuffle", [None, "bitshuffle", BloscShuffle.shuffle]) +@pytest.mark.parametrize("shuffle", [None, "bitshuffle", "legacy-enum"]) @pytest.mark.parametrize("typesize", [None, 1, 2]) -def test_tunable_attrs_param(shuffle: None | Shuffle | BloscShuffle, typesize: None | int) -> None: +def test_tunable_attrs_param( + shuffle: BloscShuffleLiteral | str | None, typesize: int | None +) -> None: """ - Test that the tunable_attrs parameter is set as expected when creating a BloscCodec, + Test that the tunable_attrs parameter is set as expected when creating a BloscCodec. """ - codec = BloscCodec(typesize=typesize, shuffle=shuffle) + # Materialize BloscShuffle.shuffle via the deprecation shim without + # contaminating the BloscCodec construction below with that warning. + if shuffle == "legacy-enum": + with pytest.warns(DeprecationWarning, match="BloscShuffle.shuffle"): + shuffle_arg: BloscShuffleLiteral | str | None = BloscShuffle.shuffle + else: + shuffle_arg = shuffle + + codec = BloscCodec(typesize=typesize, shuffle=cast(BloscShuffleLiteral | None, shuffle_arg)) - if shuffle is None: - assert codec.shuffle == BloscShuffle.bitshuffle # default shuffle + if shuffle_arg is None: + assert codec.shuffle == "bitshuffle" # default shuffle assert "shuffle" in codec._tunable_attrs if typesize is None: assert codec.typesize == 1 # default typesize @@ -82,7 +102,7 @@ def test_tunable_attrs_param(shuffle: None | Shuffle | BloscShuffle, typesize: N dtype=new_dtype, fill_value=1, prototype=default_buffer_prototype(), - config={}, # type: ignore[arg-type] + config=cast(ArrayConfig, {}), ) evolved_codec = codec.evolve_from_array_spec(array_spec=array_spec) @@ -90,8 +110,8 @@ def test_tunable_attrs_param(shuffle: None | Shuffle | BloscShuffle, typesize: N assert evolved_codec.typesize == new_dtype.item_size else: assert evolved_codec.typesize == codec.typesize - if shuffle is None: - assert evolved_codec.shuffle == BloscShuffle.shuffle + if shuffle_arg is None: + assert evolved_codec.shuffle == "shuffle" else: assert evolved_codec.shuffle == codec.shuffle @@ -135,3 +155,121 @@ def test_blosc_codec_sync_roundtrip() -> None: decoded = codec._decode_sync(encoded, spec) result = np.frombuffer(decoded.as_numpy_array(), dtype="float64") np.testing.assert_array_equal(arr, result) + + +@pytest.mark.parametrize("cname", BLOSC_CNAME) +def test_blosc_codec_accepts_all_cnames(cname: BloscCnameLiteral) -> None: + """ + Every compressor name in BLOSC_CNAME is accepted by BloscCodec and round-trips + to the same value on the stored attribute. Adding a new value to the + BloscCnameLiteral type alias without also adding it to BLOSC_CNAME (or vice + versa) is caught here. + """ + codec = BloscCodec(cname=cname) + assert codec.cname == cname + + +@pytest.mark.parametrize("shuffle", BLOSC_SHUFFLE) +def test_blosc_codec_accepts_all_shuffles(shuffle: BloscShuffleLiteral) -> None: + """ + Every shuffle mode in BLOSC_SHUFFLE is accepted by BloscCodec and round-trips + to the same value on the stored attribute. Adding a new value to the + BloscShuffleLiteral type alias without also adding it to BLOSC_SHUFFLE (or + vice versa) is caught here. + """ + codec = BloscCodec(shuffle=shuffle) + assert codec.shuffle == shuffle + + +@pytest.mark.parametrize("shuffle", BLOSC_SHUFFLE) +@pytest.mark.parametrize("cname", BLOSC_CNAME) +def test_blosc_codec_json_roundtrip(cname: BloscCnameLiteral, shuffle: BloscShuffleLiteral) -> None: + """ + JSON serialization (to_dict / from_dict) preserves every (cname, shuffle) + pair drawn from BLOSC_CNAME x BLOSC_SHUFFLE. Guards against drift in the + codec's V3 JSON form for any combination of compressor and shuffle option. + + The non-varied fields are fully specified so the codec has no tunable + attributes; tunability is not part of the JSON form and would otherwise + cause spurious round-trip mismatches. + """ + codec = BloscCodec(typesize=1, cname=cname, clevel=5, shuffle=shuffle, blocksize=0) + restored = BloscCodec.from_dict(codec.to_dict()) + assert restored == codec + + +@pytest.mark.parametrize( + ("enum_cls", "member", "expected"), + [ + (BloscShuffle, "shuffle", "shuffle"), + (BloscCname, "zstd", "zstd"), + ], +) +def test_blosc_enum_member_access_warns(enum_cls: type, member: str, expected: str) -> None: + """ + Accessing a member on the deprecated BloscShuffle / BloscCname classes + emits a DeprecationWarning and resolves to the equivalent literal string. + """ + match = f"{enum_cls.__name__}.{member}" + with pytest.warns(DeprecationWarning, match=match): + value = getattr(enum_cls, member) + assert value == expected + + +def test_blosc_enum_classes_import_silently() -> None: + """ + Importing the deprecated enum classes by name must not emit a warning; + only member access does. This guards against the blosc module accidentally + triggering its own deprecation warnings when it (or zarr) is imported. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + from zarr.codecs.blosc import BloscCname as _BloscCname # noqa: F401 + from zarr.codecs.blosc import BloscShuffle as _BloscShuffle # noqa: F401 + + +def test_blosc_codec_init_with_enum_instance_warns() -> None: + """ + Passing a real `enum.Enum` instance to BloscCodec.__init__ (e.g. an + instance materialized before the deprecation shim was introduced) must + trigger the init-level deprecation warning and still normalize the value + to the corresponding literal string. + """ + + class LegacyShuffle(enum.Enum): + bitshuffle = "bitshuffle" + + class LegacyCname(enum.Enum): + zstd = "zstd" + + with pytest.warns(DeprecationWarning, match="enum"): + codec = BloscCodec( + cname=cast(BloscCname, LegacyCname.zstd), + shuffle=cast(BloscShuffle, LegacyShuffle.bitshuffle), + ) + assert codec.cname == "zstd" + assert codec.shuffle == "bitshuffle" + + +@pytest.mark.parametrize("param", ["cname", "shuffle"]) +def test_blosc_codec_rejects_unknown(param: str) -> None: + """ + BloscCodec.__init__ raises ValueError when given a string outside the + allowed set for `cname` or `shuffle`, and the error message names the + offending parameter. + """ + kwargs: dict[str, Any] = {param: f"not-a-{param}"} + with pytest.raises(ValueError, match=f"{param} must be one of"): + BloscCodec(**kwargs) + + +@pytest.mark.parametrize("enum_cls", [BloscShuffle, BloscCname]) +def test_blosc_enum_attribute_error_for_unknown_member(enum_cls: type) -> None: + """ + Attribute access for a name that is not a known member of the deprecated + enum classes falls through to AttributeError, matching the behavior of a + regular class. + """ + unknown_name = "not_a_member" + with pytest.raises(AttributeError): + getattr(enum_cls, unknown_name) diff --git a/tests/test_codecs/test_bytes.py b/tests/test_codecs/test_bytes.py new file mode 100644 index 0000000000..ead778f526 --- /dev/null +++ b/tests/test_codecs/test_bytes.py @@ -0,0 +1,340 @@ +"""Tests for `BytesCodec` and the deprecation of the `Endian` enum.""" + +from __future__ import annotations + +import enum +import sys +import warnings +from typing import TYPE_CHECKING, Any, Literal, cast + +import numpy as np +import pytest + +import zarr +from tests.conftest import Expect, ExpectFail +from zarr.abc.codec import SupportsSyncCodec +from zarr.codecs.bytes import ( + ENDIAN, + BytesCodec, + Endian, + EndianLiteral, +) +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import NDBuffer, default_buffer_prototype +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.dtype.npy.int import Int8, Int32 +from zarr.core.dtype.npy.structured import Struct +from zarr.storage import StorePath + +from .test_codecs import _AsyncArrayProxy + +if TYPE_CHECKING: + from zarr.abc.store import Store + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize( + "input_dtype", + [ + ">u2", + "f4"), ("mask", ">i4")], + [("flux", " None: + """ + The `bytes` codec stores multi-byte data in the byte order configured on the + codec, regardless of the input array's byte order, and reads it back to the + original values. For structured dtypes this applies to every multi-byte + field, per the `struct` data type spec; the struct cases guard against the + endianness bugs from + https://github.com/zarr-developers/zarr-python/issues/4141, where the + encode path never byte-swapped struct fields (numpy reports byteorder '|' + for void dtypes) and the decode path ignored the codec's endian entirely. + The input-dtype/store-endian cross-product exercises the encode-side + byteswap (input byte order != store byte order) and the no-op case alike. + Compression is disabled so the stored chunk is the codec's raw output and + its byte layout can be asserted directly. + """ + dtype = np.dtype(input_dtype) + if dtype.fields is None: + data = np.arange(0, 256, dtype=dtype).reshape((16, 16)) + else: + data = np.zeros((16, 16), dtype=dtype) + data["flux"] = np.arange(0, 256).reshape((16, 16)) + data["mask"] = np.arange(256, 512).reshape((16, 16)) + path = "endian" + spath = StorePath(store, path) + a = await zarr.api.asynchronous.create_array( + spath, + shape=data.shape, + chunks=(16, 16), + dtype=dtype, + fill_value=0, + compressors=None, + serializer=BytesCodec(endian=store_endian), + ) + + await _AsyncArrayProxy(a)[:, :].set(data) + + # The stored chunk is laid out in the byte order configured on the codec. + stored = await store.get(f"{path}/c/0/0", prototype=default_buffer_prototype()) + assert stored is not None + assert stored.to_bytes() == data.astype(dtype.newbyteorder(store_endian)).tobytes() + + # ... and the data reads back to the original values. + readback_data = await _AsyncArrayProxy(a)[:, :].get() + assert np.array_equal(data, readback_data) + + +def test_bytes_codec_supports_sync() -> None: + assert isinstance(BytesCodec(), SupportsSyncCodec) + + +@pytest.mark.parametrize("endian", ENDIAN) +@pytest.mark.parametrize( + "native_dtype", + [np.dtype("float64"), np.dtype(">u2"), np.dtype([("a", ">f4"), ("b", " None: + """ + The synchronous encode/decode path round-trips data, and the two byte + orders involved are independent: the codec's `endian` configuration governs + only the stored byte layout (every multi-byte value, including struct + fields, is laid out in the codec's byte order regardless of the input + array's byte order), while the decoded buffer's byte order is governed by + the array's data type regardless of the codec's. The mixed-endian struct + case pins that per-field byte order of the in-memory dtype survives a + roundtrip through a single stored byte order. + """ + if native_dtype.fields is None: + arr = np.arange(100, dtype=native_dtype) + else: + arr = np.array([(1.5, 2), (3.5, 4), (5.5, 6), (7.5, 8)], dtype=native_dtype) + zdtype = get_data_type_from_native_dtype(arr.dtype) + spec = ArraySpec( + shape=arr.shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + nd_buf: NDBuffer = default_buffer_prototype().nd_buffer.from_numpy_array(arr) + + codec = BytesCodec(endian=endian).evolve_from_array_spec(spec) + + encoded = codec._encode_sync(nd_buf, spec) + assert encoded is not None + assert encoded.to_bytes() == arr.astype(native_dtype.newbyteorder(endian)).tobytes() + + decoded = codec._decode_sync(encoded, spec) + assert decoded.dtype == zdtype.to_native_dtype() + np.testing.assert_array_equal(arr, decoded.as_numpy_array()) + + +@pytest.mark.parametrize("endian", ENDIAN) +def test_bytes_codec_accepts_all_endians(endian: EndianLiteral) -> None: + """ + Every endian value in ENDIAN is accepted by BytesCodec and round-trips + to the same value on the stored attribute. Catches drift between the + EndianLiteral type alias and the runtime ENDIAN tuple. + """ + codec = BytesCodec(endian=endian) + assert codec.endian == endian + + +@pytest.mark.parametrize("endian", ENDIAN) +def test_bytes_codec_json_roundtrip(endian: EndianLiteral) -> None: + """ + BytesCodec.to_dict produces the spec-defined wire shape and the + round-trip through from_dict preserves equality. Asserting the literal + JSON shape catches drift between BytesCodec's runtime representation and + the codec's V3 on-disk form. + """ + codec = BytesCodec(endian=endian) + assert codec.to_dict() == {"name": "bytes", "configuration": {"endian": endian}} + restored = BytesCodec.from_dict(codec.to_dict()) + assert restored == codec + + +# to_dict and from_dict are inverses over this (endian setting, wire dict) mapping: +# to_dict turns the endian setting into the dict; from_dict recovers it. +_ENDIAN_DICT_CASES: list[Expect[EndianLiteral | None, dict[str, Any]]] = [ + Expect( + input="little", + output={"name": "bytes", "configuration": {"endian": "little"}}, + id="little", + ), + Expect( + input="big", + output={"name": "bytes", "configuration": {"endian": "big"}}, + id="big", + ), + Expect(input=None, output={"name": "bytes"}, id="missing"), +] + + +@pytest.mark.parametrize("case", _ENDIAN_DICT_CASES, ids=lambda c: c.id) +def test_to_dict(case: Expect[EndianLiteral | None, dict[str, Any]]) -> None: + assert BytesCodec(endian=case.input).to_dict() == case.output + + +@pytest.mark.parametrize("case", _ENDIAN_DICT_CASES, ids=lambda c: c.id) +def test_from_dict(case: Expect[EndianLiteral | None, dict[str, Any]]) -> None: + assert BytesCodec.from_dict(case.output).endian == case.input + + +@pytest.mark.parametrize("endian", ["little", "big", pytest.param(None, id="missing")]) +def test_roundtrip(endian: EndianLiteral | None) -> None: + codec = BytesCodec(endian=endian) + + encoded = codec.to_dict() + roundtripped = BytesCodec.from_dict(encoded) + + assert codec == roundtripped + + +@pytest.mark.parametrize( + ("member", "expected"), + [("little", "little"), ("big", "big")], +) +def test_endian_member_access_warns(member: str, expected: str) -> None: + """ + Accessing a member on the deprecated `Endian` class emits a + `DeprecationWarning` and resolves to the equivalent literal string. + """ + with pytest.warns(DeprecationWarning, match=rf"Endian\.{member}"): + value = getattr(Endian, member) + assert value == expected + + +def test_endian_class_imports_silently() -> None: + """ + Importing the deprecated `Endian` class by name must not emit a warning; + only member access does. Guards against `bytes.py` accidentally + triggering its own deprecation warnings at import time. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + from zarr.codecs.bytes import Endian as _Endian # noqa: F401 + + +def test_bytes_codec_init_with_enum_instance_warns() -> None: + """ + Passing a foreign `enum.Enum` instance to `BytesCodec.__init__` triggers + the init-level deprecation warning (from `_coerce_enum_input`) and + normalizes the value to the corresponding literal string. Covers the + case where a downstream package defined its own enum-shaped class to + bridge between zarr's old API and its own. + """ + + class LegacyEndian(enum.Enum): + little = "little" + + with pytest.warns(DeprecationWarning, match=r"Passing an enum to BytesCodec"): + codec = BytesCodec(endian=cast(Endian, LegacyEndian.little)) + assert codec.endian == "little" + + +def test_bytes_codec_init_with_deprecated_class_member() -> None: + """ + The realistic legacy-upgrade idiom: `BytesCodec(endian=Endian.little)`. + Member access on `Endian` emits one `DeprecationWarning` (from the + metaclass) and resolves to the bare string, which `BytesCodec` then + accepts without further warning. No second warning from + `_coerce_enum_input` because the metaclass already produced a string. + + The `cast` is necessary because the metaclass `__getattr__` is typed + as returning `str`, which does not statically match the codec's + `EndianLiteral` parameter even though the runtime value does. + """ + with pytest.warns(DeprecationWarning, match=r"Endian\.little"): + codec = BytesCodec(endian=cast(EndianLiteral, Endian.little)) + assert codec.endian == "little" + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input="north", + exception=ValueError, + id="unknown-string", + msg="endian must be one of", + ), + ], + ids=lambda c: c.id, +) +def test_bytes_codec_rejects_unknown_endian(case: ExpectFail[Any]) -> None: + """ + `BytesCodec.__init__` raises `ValueError` when given a value outside + `ENDIAN`, and the error message names the offending parameter. + """ + with case.raises(): + BytesCodec(endian=case.input) + + +def test_endian_attribute_error_for_unknown_member() -> None: + """ + Attribute access for a name that is not a known member of the + deprecated `Endian` class falls through to `AttributeError`, matching + the behavior of a regular class. + """ + with pytest.raises(AttributeError): + getattr(Endian, "not_a_member") # noqa: B009 + + +def test_bytes_codec_default_endian_matches_system() -> None: + """ + Constructing `BytesCodec()` with no arguments yields a codec whose + `endian` matches `sys.byteorder`. This replaces the previous + `default_system_endian = Endian(sys.byteorder)` module-level binding. + """ + codec = BytesCodec() + assert codec.endian == sys.byteorder + + +def _make_array_spec(dtype: Any) -> ArraySpec: + """Build a minimal ArraySpec around the given dtype for codec.evolve testing.""" + return ArraySpec( + shape=(1,), + dtype=dtype, + fill_value=0, + config=cast(ArrayConfig, {}), + prototype=default_buffer_prototype(), + ) + + +def test_bytes_codec_evolve_structured_multi_byte_fields_warns_and_defaults() -> None: + """ + BytesCodec(endian=None).evolve_from_array_spec(spec) with a structured dtype + whose fields contain multi-byte members emits a UserWarning about the + missing endian and returns a codec with endian set to "little" for legacy + compatibility. + """ + codec = BytesCodec(endian=None) + dtype = Struct(fields=(("a", Int32()), ("b", Int32()))) + spec = _make_array_spec(dtype) + with pytest.warns(UserWarning, match=r"Missing 'endian' for structured dtype"): + evolved = codec.evolve_from_array_spec(spec) + assert evolved.endian == "little" + + +def test_bytes_codec_evolve_structured_single_byte_fields_clears_endian() -> None: + """ + For a structured dtype whose fields are all single-byte, BytesCodec drops + its endian on evolve (endian is meaningless for single-byte content). + """ + codec = BytesCodec(endian="little") + dtype = Struct(fields=(("a", Int8()), ("b", Int8()))) + spec = _make_array_spec(dtype) + evolved = codec.evolve_from_array_spec(spec) + assert evolved.endian is None diff --git a/tests/test_codecs/test_cast_value.py b/tests/test_codecs/test_cast_value.py new file mode 100644 index 0000000000..c2e78770d9 --- /dev/null +++ b/tests/test_codecs/test_cast_value.py @@ -0,0 +1,613 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import zarr +from tests.conftest import Expect, ExpectFail +from zarr.codecs import BytesCodec, TransposeCodec +from zarr.codecs.cast_value import CastValue +from zarr.storage import MemoryStore + +try: + import cast_value_rs # noqa: F401 + + _HAS_CAST_VALUE_RS = True +except ModuleNotFoundError: + _HAS_CAST_VALUE_RS = False + +requires_cast_value_rs = pytest.mark.skipif( + not _HAS_CAST_VALUE_RS, reason="cast-value-rs not installed" +) + + +# --------------------------------------------------------------------------- +# Serialization +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + Expect( + input=CastValue(data_type="uint8"), + output={"name": "cast_value", "configuration": {"data_type": "uint8"}}, + id="minimal", + ), + Expect( + input=CastValue( + data_type="uint8", + rounding="towards-zero", + out_of_range="clamp", + scalar_map={"encode": [("NaN", 0)]}, + ), + output={ + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "rounding": "towards-zero", + "out_of_range": "clamp", + "scalar_map": {"encode": [("NaN", 0)]}, + }, + }, + id="full", + ), + ], + ids=lambda c: c.id, +) +def test_to_dict(case: Expect[CastValue, dict[str, Any]]) -> None: + """to_dict produces the expected JSON structure.""" + assert case.input.to_dict() == case.output + + +@pytest.mark.parametrize( + "case", + [ + Expect( + input={"name": "cast_value", "configuration": {"data_type": "float32"}}, + output=("float32", "nearest-even", None), + id="defaults", + ), + Expect( + input={ + "name": "cast_value", + "configuration": { + "data_type": "int16", + "rounding": "towards-zero", + "out_of_range": "clamp", + }, + }, + output=("int16", "towards-zero", "clamp"), + id="explicit", + ), + ], + ids=lambda c: c.id, +) +def test_from_dict(case: Expect[dict[str, Any], tuple[str, str, str | None]]) -> None: + """from_dict deserializes configuration with correct values and defaults.""" + codec = CastValue.from_dict(case.input) + dtype_name, rounding, out_of_range = case.output + assert codec.dtype.to_native_dtype() == np.dtype(dtype_name) + assert codec.rounding == rounding + assert codec.out_of_range == out_of_range + + +@pytest.mark.parametrize( + "codec", + [ + CastValue(data_type="int16", rounding="towards-zero", out_of_range="clamp"), + CastValue( + data_type="uint8", + out_of_range="clamp", + scalar_map={"encode": [("NaN", 0)], "decode": [(0, "NaN")]}, + ), + ], + ids=["no-scalar-map", "with-scalar-map"], +) +def test_serialization_roundtrip(codec: CastValue) -> None: + """to_dict followed by from_dict produces an equal codec.""" + restored = CastValue.from_dict(codec.to_dict()) + assert codec == restored + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +def test_construction_accepts_zdtype_object() -> None: + """data_type can be a ZDType instance, not just a JSON string.""" + from zarr.core.dtype import UInt8 + + codec = CastValue(data_type=UInt8()) + assert codec.dtype.to_native_dtype() == np.dtype("uint8") + + +def test_construction_rejects_invalid_target_dtype() -> None: + """Construction rejects target dtypes not in PERMITTED_DATA_TYPE_NAMES.""" + with pytest.raises(ValueError, match="Invalid target data type"): + CastValue(data_type="complex64") + + +# --------------------------------------------------------------------------- +# Validation +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"dtype": "complex128", "target": "float64"}, + msg="only supports integer and floating-point", + exception=ValueError, + id="complex-source", + ), + ExpectFail( + input={"dtype": "int32", "target": "float64", "out_of_range": "wrap"}, + msg="only valid for integer", + exception=ValueError, + id="wrap-float-target", + ), + ], + ids=lambda c: c.id, +) +def test_validation_rejects_invalid(case: ExpectFail[dict[str, Any]]) -> None: + """Invalid dtype or out_of_range combinations are rejected at array creation.""" + with case.raises(): + zarr.create_array( + store={}, + shape=(10,), + dtype=case.input["dtype"], + chunks=(10,), + filters=[ + CastValue( + data_type=case.input["target"], + out_of_range=case.input.get("out_of_range"), + ) + ], + compressors=None, + fill_value=0, + ) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + ("source_dtype", "target_dtype"), + [ + ("float16", "int8"), + ("float32", "int32"), + ("float64", "int64"), + ("int32", "uint8"), + ], +) +def test_validation_accepts_wrap_with_integer_target(source_dtype: str, target_dtype: str) -> None: + """Regression for #3936: `out_of_range="wrap"` is permitted when the + cast TARGET (not the source array dtype) is an integer type.""" + zarr.create_array( + store={}, + shape=(1,), + dtype=source_dtype, + chunks=(1,), + filters=[CastValue(data_type=target_dtype, out_of_range="wrap")], + compressors=None, + fill_value=0, + ) + + +def test_zero_itemsize_raises() -> None: + """Variable-length dtypes (itemsize=0) are rejected by compute_encoded_size.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype.npy.string import VariableLengthUTF8 + + codec = CastValue(data_type="uint8") + spec = ArraySpec( + shape=(10,), + dtype=VariableLengthUTF8(), # type: ignore[arg-type] + fill_value="", + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + with pytest.raises(ValueError, match="fixed-size integer and floating-point data types"): + codec.compute_encoded_size(100, spec) + + +# --------------------------------------------------------------------------- +# Encode / decode +# --------------------------------------------------------------------------- + + +@requires_cast_value_rs +@pytest.mark.parametrize( + "case", + [ + Expect(input=("float64", "float32"), output=np.arange(50, dtype="float64"), id="f64→f32"), + Expect(input=("float32", "float64"), output=np.arange(50, dtype="float32"), id="f32→f64"), + Expect(input=("int32", "int64"), output=np.arange(50, dtype="int32"), id="i32→i64"), + Expect(input=("int64", "int16"), output=np.arange(50, dtype="int64"), id="i64→i16"), + Expect(input=("float64", "int32"), output=np.arange(50, dtype="float64"), id="f64→i32"), + Expect(input=("int32", "float64"), output=np.arange(50, dtype="int32"), id="i32→f64"), + ], + ids=lambda c: c.id, +) +def test_encode_decode_roundtrip( + case: Expect[tuple[str, str], np.ndarray[Any, np.dtype[Any]]], +) -> None: + """Small integer data survives encode → decode for each dtype pair.""" + import zarr + + source_dtype, target_dtype = case.input + arr = zarr.create_array( + store={}, + shape=(50,), + dtype=source_dtype, + chunks=(50,), + filters=[CastValue(data_type=target_dtype)], + compressors=None, + fill_value=0, + ) + arr[:] = case.output + np.testing.assert_array_equal(arr[:], case.output) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + "case", + [ + Expect( + input=np.array([1.7, -1.7, 2.5, -2.5], dtype="float64"), + output=np.array([1, -1, 2, -2], dtype="float64"), + id="towards-zero", + ), + ], + ids=lambda c: c.id, +) +def test_float_to_int_rounding( + case: Expect[np.ndarray[Any, np.dtype[Any]], np.ndarray[Any, np.dtype[Any]]], +) -> None: + """Fractional float values are truncated towards zero when cast to int32.""" + import zarr + + arr = zarr.create_array( + store={}, + shape=case.input.shape, + dtype=case.input.dtype, + chunks=case.input.shape, + filters=[CastValue(data_type="int32", rounding="towards-zero", out_of_range="clamp")], + compressors=None, + fill_value=0, + ) + arr[:] = case.input + np.testing.assert_array_equal(arr[:], case.output) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + "case", + [ + Expect( + input=np.array([0, 200, -200], dtype="int32"), + output=np.array([0, 127, -128], dtype="int32"), + id="int32→int8", + ), + ], + ids=lambda c: c.id, +) +def test_out_of_range_clamp( + case: Expect[np.ndarray[Any, np.dtype[Any]], np.ndarray[Any, np.dtype[Any]]], +) -> None: + """Values outside the int8 range are clamped to [-128, 127].""" + import zarr + + arr = zarr.create_array( + store={}, + shape=case.input.shape, + dtype=case.input.dtype, + chunks=case.input.shape, + filters=[CastValue(data_type="int8", out_of_range="clamp")], + compressors=None, + fill_value=0, + ) + arr[:] = case.input + np.testing.assert_array_equal(arr[:], case.output) + + +def test_compute_encoded_size() -> None: + """compute_encoded_size correctly scales byte length by itemsize ratio.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype import get_data_type_from_json + + codec = CastValue(data_type="int16") + spec = ArraySpec( + shape=(10,), + dtype=get_data_type_from_json("float64", zarr_format=3), + fill_value=0, + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + # 10 float64 elements = 80 bytes -> 10 int16 elements = 20 bytes + assert codec.compute_encoded_size(80, spec) == 20 + + +@requires_cast_value_rs +def test_scalar_map_encode_decode_roundtrip() -> None: + """Scalar map entries are applied during encode and decode.""" + import zarr + + data = np.array([1.0, float("nan"), 3.0], dtype="float64") + arr = zarr.create_array( + store={}, + shape=data.shape, + dtype="float64", + chunks=data.shape, + filters=[ + CastValue( + data_type="int32", + rounding="nearest-even", + out_of_range="clamp", + scalar_map={"encode": [("NaN", -999)], "decode": [(-999, "NaN")]}, + ), + ], + compressors=None, + fill_value=1, + ) + arr[:] = data + result = np.asarray(arr[:]) + np.testing.assert_equal(result[0], 1.0) + np.testing.assert_equal(result[2], 3.0) + assert np.isnan(result[1]) + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={ + "dtype": "int32", + "target": "int8", + "scalar_map": {"encode": [("NaN", 0)]}, + }, + msg="not representable in dtype int32", + exception=ValueError, + id="nan-key-for-int-source", + ), + ExpectFail( + input={ + "dtype": "int32", + "target": "float64", + "scalar_map": {"decode": [(0, "NaN")]}, + }, + msg="not representable in dtype int32", + exception=ValueError, + id="nan-value-for-int-decode-target", + ), + ExpectFail( + input={ + "dtype": "float64", + "target": "int8", + "scalar_map": {"encode": [("NaN", 999)]}, + }, + msg="not representable in dtype int8", + exception=ValueError, + id="encode-value-out-of-range", + ), + ExpectFail( + input={ + "dtype": "float64", + "target": "int8", + "scalar_map": {"encode": [("NaN", 1.5)]}, + }, + msg="not representable in dtype int8", + exception=ValueError, + id="encode-value-not-integer", + ), + ], + ids=lambda c: c.id, +) +def test_scalar_map_validation_rejects_invalid(case: ExpectFail[dict[str, Any]]) -> None: + """Invalid scalar_map entries are rejected at array creation.""" + import zarr + + with case.raises(): + zarr.create_array( + store={}, + shape=(10,), + dtype=case.input["dtype"], + chunks=(10,), + filters=[ + CastValue( + data_type=case.input["target"], + out_of_range="clamp", + scalar_map=case.input["scalar_map"], + ) + ], + compressors=None, + fill_value=0, + ) + + +@requires_cast_value_rs +def test_combined_with_scale_offset() -> None: + """scale_offset followed by cast_value compresses float64 into int16 and round-trips.""" + import zarr + from zarr.codecs.scale_offset import ScaleOffset + + arr = zarr.create_array( + store={}, + shape=(100,), + dtype="float64", + chunks=(100,), + filters=[ + ScaleOffset(offset=0, scale=10), + CastValue(data_type="int16", rounding="nearest-even", out_of_range="clamp"), + ], + compressors=None, + fill_value=0, + ) + data = np.arange(100, dtype="float64") * 0.1 + arr[:] = data + result = arr[:] + np.testing.assert_array_almost_equal(result, data, decimal=1) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "case", + [ + Expect( + input={"encode": [("NaN", 0)]}, + output={"encode": {"NaN": 0}}, + id="encode-only", + ), + Expect( + input={"encode": [("NaN", 0)], "decode": [(0, "NaN")]}, + output={"encode": {"NaN": 0}, "decode": {0: "NaN"}}, + id="both-directions", + ), + Expect( + input={"encode": {"NaN": 0}}, + output={"encode": {"NaN": 0}}, + id="already-normalized", + ), + ], + ids=lambda c: c.id, +) +def test_parse_scalar_map(case: Expect[Any, Any]) -> None: + from zarr.codecs.cast_value import parse_scalar_map + + assert parse_scalar_map(case.input) == case.output + + +# --------------------------------------------------------------------------- +# Backend version guard +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + Expect(input="0.4.2", output=None, id="exactly-minimum"), + Expect(input="0.4.3", output=None, id="newer-patch"), + Expect(input="0.5.0", output=None, id="newer-minor"), + Expect(input="1.0.0", output=None, id="newer-major"), + Expect(input="0.4.2.post1", output=None, id="post-release"), + Expect(input="0.4.0", output="0.4.0", id="known-corrupting"), + Expect(input="0.4.1", output="0.4.1", id="one-patch-below"), + Expect(input="0.3.0", output="0.3.0", id="older-minor"), + Expect(input="0.4.2.dev1", output="0.4.2.dev1", id="pre-release-of-minimum"), + ], + ids=lambda c: c.id, +) +def test_check_backend_version( + case: Expect[str, str | None], monkeypatch: pytest.MonkeyPatch +) -> None: + """Versions at or above the minimum pass; older ones report the installed version.""" + from zarr.codecs import cast_value as mod + + monkeypatch.setattr(mod, "version", lambda _: case.input) + result = mod._check_backend_version() + + if case.output is None: + assert result is None + else: + assert result is not None + assert case.output in result + assert mod.CAST_VALUE_RS_MIN_VERSION in result + + +def test_check_backend_version_allows_missing_metadata(monkeypatch: pytest.MonkeyPatch) -> None: + """A backend without distribution metadata is allowed: there is no version to compare.""" + from importlib.metadata import PackageNotFoundError + + from zarr.codecs import cast_value as mod + + def raise_not_found(_: str) -> str: + raise PackageNotFoundError + + monkeypatch.setattr(mod, "version", raise_not_found) + assert mod._check_backend_version() is None + + +def test_encode_rejects_outdated_backend(monkeypatch: pytest.MonkeyPatch) -> None: + """Using the codec with an outdated backend raises instead of corrupting data.""" + from zarr.codecs import cast_value as mod + + monkeypatch.setattr(mod, "_BACKEND_ERROR", "outdated backend") + codec = CastValue(data_type="uint16") + + with pytest.raises(ImportError, match="outdated backend"): + codec._do_cast( + np.arange(4, dtype=np.float32), target_dtype=np.dtype("uint16"), scalar_map=None + ) + + +def test_min_version_matches_pyproject() -> None: + """The runtime floor and the packaging floor must not drift apart.""" + import re + import tomllib + from pathlib import Path + + from zarr.codecs.cast_value import CAST_VALUE_RS_MIN_VERSION + + pyproject = Path(__file__).parents[2] / "pyproject.toml" + if not pyproject.is_file(): + pytest.skip("pyproject.toml is not available in an installed checkout") + + with pyproject.open("rb") as f: + extras = tomllib.load(f)["project"]["optional-dependencies"] + + (requirement,) = extras["cast-value-rs"] + match = re.fullmatch(r"cast-value-rs>=(?P[\w.]+)", requirement) + assert match is not None, f"unexpected requirement form: {requirement!r}" + assert match.group("version") == CAST_VALUE_RS_MIN_VERSION + + +# --------------------------------------------------------------------------- +# Non-contiguous input (regression for #4237) +# --------------------------------------------------------------------------- + + +@requires_cast_value_rs +def test_enforce_contiguous_arrays() -> None: + """ + Transpose codec produces non-contiguous arrays. + Ensure cast_value makes them contiguous before processing. + """ + data = np.arange(20, dtype=np.float32).reshape(5, 2, 2) + + def make_array(filters: list[Any]) -> Any: + return zarr.create_array( + store=MemoryStore(), + shape=data.shape, + dtype=data.dtype, + chunks=data.shape, + filters=filters, + serializer=BytesCodec(endian="little"), + compressors=None, + zarr_format=3, + ) + + # Cast before transpose + array = make_array( + [ + CastValue(data_type="uint16"), + TransposeCodec(order=(1, 2, 0)), + ] + ) + array[:] = data + assert_array_equal(array[:], data) + + # Cast after transpose + array = make_array( + [ + TransposeCodec(order=(1, 2, 0)), + CastValue(data_type="uint16"), + ] + ) + + array[:] = data + assert_array_equal(array[:], data) diff --git a/tests/test_codecs/test_codecs.py b/tests/test_codecs/test_codecs.py index fa2017876e..8b4585503c 100644 --- a/tests/test_codecs/test_codecs.py +++ b/tests/test_codecs/test_codecs.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import warnings from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -18,11 +19,11 @@ TransposeCodec, ) from zarr.core.buffer import default_buffer_prototype -from zarr.core.indexing import BasicSelection, decode_morton, morton_order_iter +from zarr.core.indexing import BasicSelection, decode_morton, morton_order_coords from zarr.core.metadata.v3 import ArrayV3Metadata from zarr.dtype import UInt8 from zarr.errors import ZarrUserWarning -from zarr.storage import StorePath +from zarr.storage import MemoryStore, StorePath if TYPE_CHECKING: from zarr.abc.codec import Codec @@ -173,8 +174,8 @@ def test_open(store: Store) -> None: def test_morton_exact_order() -> None: """Test exact morton ordering for power-of-2 shapes.""" - assert list(morton_order_iter((2, 2))) == [(0, 0), (1, 0), (0, 1), (1, 1)] - assert list(morton_order_iter((2, 2, 2))) == [ + assert list(morton_order_coords((2, 2))) == [(0, 0), (1, 0), (0, 1), (1, 1)] + assert list(morton_order_coords((2, 2, 2))) == [ (0, 0, 0), (1, 0, 0), (0, 1, 0), @@ -184,7 +185,7 @@ def test_morton_exact_order() -> None: (0, 1, 1), (1, 1, 1), ] - assert list(morton_order_iter((2, 2, 2, 2))) == [ + assert list(morton_order_coords((2, 2, 2, 2))) == [ (0, 0, 0, 0), (1, 0, 0, 0), (0, 1, 0, 0), @@ -219,15 +220,16 @@ def test_morton_exact_order() -> None: (1, 1), (5, 1, 3), (1, 4, 1, 2), + (5, 5, 5), # triggers argsort strategy (n_z/n_total > 4) ], ) def test_morton_is_permutation(shape: tuple[int, ...]) -> None: - """Test that morton_order_iter produces every valid coordinate exactly once.""" + """Test that morton_order_coords produces every valid coordinate exactly once.""" import itertools from zarr.core.common import product - order = list(morton_order_iter(shape)) + order = list(morton_order_coords(shape)) expected_len = product(shape) # completeness: every valid coordinate is present assert len(order) == expected_len @@ -256,7 +258,7 @@ def test_morton_ordering(shape: tuple[int, ...]) -> None: so the ordering should be exactly decode_morton(0), decode_morton(1), ... """ - order = list(morton_order_iter(shape)) + order = list(morton_order_coords(shape)) for i, coord in enumerate(order): assert coord == decode_morton(i, shape) @@ -374,6 +376,49 @@ def test_invalid_metadata_create_array() -> None: ) +@pytest.mark.parametrize( + "pipeline_path", + [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", + ], +) +def test_sharding_warning_fires_once_per_open(pipeline_path: str) -> None: + """Construction-time codec warnings (e.g. sharding's partial-reads warning) + must fire exactly once per array open, not once per internal codec-chain + reconstruction. + + `create_codec_pipeline` builds a throwaway pipeline via `from_codecs` (which + warns) and then calls `evolve_from_array_spec` on it, which re-splits the + (already-warned-about) codec chain against the evolved spec. That re-split + goes through `codecs_from_list_unchecked` rather than `codecs_from_list`, so + it does not re-emit the warning. `FusedCodecPipeline` additionally builds a + `ChunkTransform` (and, on the async fallback path, an `AsyncChunkTransform` + per call) from the same evolved codec chain, which must use the same quiet + variant. + """ + with config.set({"codec_pipeline.path": pipeline_path}): + store = MemoryStore() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + zarr.create_array( + store, + shape=(16, 16), + chunks=(16, 16), + dtype=np.dtype("uint8"), + fill_value=0, + serializer=ShardingCodec(chunk_shape=(8, 8)), + compressors=[GzipCodec()], + ) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + zarr.open_array(store, mode="r") + + matches = [w for w in caught if "disables partial reads" in str(w.message)] + assert len(matches) == 1 + + @pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) async def test_resize(store: Store) -> None: data = np.zeros((16, 18), dtype="uint16") @@ -401,3 +446,41 @@ async def test_resize(store: Store) -> None: assert await store.get(f"{path}/0.1", prototype=default_buffer_prototype()) is not None assert await store.get(f"{path}/1.0", prototype=default_buffer_prototype()) is None assert await store.get(f"{path}/1.1", prototype=default_buffer_prototype()) is None + + +def _resolve_metadata_codecs() -> list[Codec]: + from zarr.codecs.crc32c_ import Crc32cCodec + from zarr.codecs.zstd import ZstdCodec + + return [ + BytesCodec(), + GzipCodec(level=1), + TransposeCodec(order=(0,)), + Crc32cCodec(), + ZstdCodec(level=1), + ] + + +@pytest.mark.parametrize("codec", _resolve_metadata_codecs(), ids=lambda c: type(c).__name__) +def test_resolve_metadata_only_mutates_shape(codec: Codec) -> None: + """A codec's resolve_metadata may change a chunk's `shape` but must leave the + prototype, dtype, fill_value, and config untouched -- the pipeline relies on + those being stable across the codec chain. + """ + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.dtype import get_data_type_from_native_dtype + + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec_in = ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0.0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + spec_out = codec.resolve_metadata(spec_in) + name = type(codec).__name__ + assert spec_out.prototype is spec_in.prototype, f"{name} changed prototype" + assert spec_out.dtype == spec_in.dtype, f"{name} changed dtype" + assert spec_out.fill_value == spec_in.fill_value, f"{name} changed fill_value" + assert spec_out.config == spec_in.config, f"{name} changed config" diff --git a/tests/test_codecs/test_endian.py b/tests/test_codecs/test_endian.py deleted file mode 100644 index c505cee828..0000000000 --- a/tests/test_codecs/test_endian.py +++ /dev/null @@ -1,89 +0,0 @@ -from typing import Literal - -import numpy as np -import pytest - -import zarr -from zarr.abc.codec import SupportsSyncCodec -from zarr.abc.store import Store -from zarr.codecs import BytesCodec -from zarr.core.array_spec import ArrayConfig, ArraySpec -from zarr.core.buffer import NDBuffer, default_buffer_prototype -from zarr.core.dtype import get_data_type_from_native_dtype -from zarr.storage import StorePath - -from .test_codecs import _AsyncArrayProxy - - -@pytest.mark.filterwarnings("ignore:The endianness of the requested serializer") -@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) -@pytest.mark.parametrize("endian", ["big", "little"]) -async def test_endian(store: Store, endian: Literal["big", "little"]) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - path = "endian" - spath = StorePath(store, path) - a = await zarr.api.asynchronous.create_array( - spath, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - chunk_key_encoding={"name": "v2", "separator": "."}, - serializer=BytesCodec(endian=endian), - ) - - await _AsyncArrayProxy(a)[:, :].set(data) - readback_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, readback_data) - - -def test_bytes_codec_supports_sync() -> None: - assert isinstance(BytesCodec(), SupportsSyncCodec) - - -def test_bytes_codec_sync_roundtrip() -> None: - codec = BytesCodec() - arr = np.arange(100, dtype="float64") - zdtype = get_data_type_from_native_dtype(arr.dtype) - spec = ArraySpec( - shape=arr.shape, - dtype=zdtype, - fill_value=zdtype.cast_scalar(0), - config=ArrayConfig(order="C", write_empty_chunks=True), - prototype=default_buffer_prototype(), - ) - nd_buf: NDBuffer = default_buffer_prototype().nd_buffer.from_numpy_array(arr) - - codec = codec.evolve_from_array_spec(spec) - - encoded = codec._encode_sync(nd_buf, spec) - assert encoded is not None - decoded = codec._decode_sync(encoded, spec) - np.testing.assert_array_equal(arr, decoded.as_numpy_array()) - - -@pytest.mark.filterwarnings("ignore:The endianness of the requested serializer") -@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) -@pytest.mark.parametrize("dtype_input_endian", [">u2", "u2", " None: - data = np.arange(0, 256, dtype=dtype_input_endian).reshape((16, 16)) - path = "endian" - spath = StorePath(store, path) - a = await zarr.api.asynchronous.create_array( - spath, - shape=data.shape, - chunks=(16, 16), - dtype="uint16", - fill_value=0, - chunk_key_encoding={"name": "v2", "separator": "."}, - serializer=BytesCodec(endian=dtype_store_endian), - ) - - await _AsyncArrayProxy(a)[:, :].set(data) - readback_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, readback_data) diff --git a/tests/test_codecs/test_numcodecs.py b/tests/test_codecs/test_numcodecs.py index ddfca71294..99cd89492f 100644 --- a/tests/test_codecs/test_numcodecs.py +++ b/tests/test_codecs/test_numcodecs.py @@ -17,7 +17,6 @@ from zarr import config, create_array, open_array from zarr.abc.numcodec import _is_numcodec, _is_numcodec_cls from zarr.codecs import numcodecs as _numcodecs -from zarr.errors import ZarrUserWarning from zarr.registry import get_codec_class, get_numcodec if TYPE_CHECKING: @@ -76,8 +75,6 @@ def test_is_numcodec_cls() -> None: assert _is_numcodec_cls(GZip) -EXPECTED_WARNING_STR = "Numcodecs codecs are not in the Zarr version 3.*" - ALL_CODECS = tuple( filter( lambda v: issubclass(v, _numcodecs._NumcodecsCodec) and hasattr(v, "codec_name"), @@ -88,7 +85,7 @@ def test_is_numcodec_cls() -> None: @pytest.mark.parametrize("codec_cls", ALL_CODECS) def test_get_codec_class(codec_cls: type[_numcodecs._NumcodecsCodec]) -> None: - assert get_codec_class(codec_cls.codec_name) == codec_cls # type: ignore[comparison-overlap] + assert get_codec_class(codec_cls.codec_name) == codec_cls # type: ignore[comparison-overlap,misc] @pytest.mark.parametrize("codec_class", ALL_CODECS) @@ -115,15 +112,14 @@ def test_docstring(codec_class: type[_numcodecs._NumcodecsCodec]) -> None: def test_generic_compressor(codec_class: type[_numcodecs._NumcodecsBytesBytesCodec]) -> None: data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - compressors=[codec_class()], - ) + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + compressors=[codec_class()], + ) a[:, :] = data.copy() np.testing.assert_array_equal(data, a[:, :]) @@ -150,60 +146,88 @@ def test_generic_filter( ) -> None: data = np.linspace(0, 10, 256, dtype="float32").reshape((16, 16)) - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - filters=[ - codec_class(**codec_config), - ], - ) + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[ + codec_class(**codec_config), + ], + ) a[:, :] = data.copy() with codec_conf(): - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - b = open_array(a.store, mode="r") + b = open_array(a.store, mode="r") np.testing.assert_array_equal(data, b[:, :]) +@pytest.mark.parametrize( + ("codec_class", "codec_config", "dtype"), + [ + (_numcodecs.Delta, {"dtype": "int64"}, "int64"), + (_numcodecs.FixedScaleOffset, {"offset": 0, "scale": 1}, "int64"), + (_numcodecs.PackBits, {}, "bool"), + ], + ids=["delta", "fixedscaleoffset", "packbits"], +) +def test_generic_filter_f_contiguous( + codec_class: type[_numcodecs._NumcodecsArrayArrayCodec], + codec_config: dict[str, JSON], + dtype: str, +) -> None: + # gh-3558: F-contiguous chunks were handed to numcodecs filters as is, and + # numcodecs flattens in memory order, so the elements came back transposed + if dtype == "bool": + data = np.asfortranarray(np.tril(np.ones((16, 16), dtype=bool))) + else: + data = np.asfortranarray(np.arange(256, dtype=dtype).reshape(16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[codec_class(**codec_config)], + ) + + a[:, :] = data + np.testing.assert_array_equal(data, a[:, :]) + + def test_generic_filter_bitround() -> None: data = np.linspace(0, 1, 256, dtype="float32").reshape((16, 16)) - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - filters=[_numcodecs.BitRound(keepbits=3)], - ) + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[_numcodecs.BitRound(keepbits=3)], + ) a[:, :] = data.copy() - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - b = open_array(a.store, mode="r") + b = open_array(a.store, mode="r") assert np.allclose(data, b[:, :], atol=0.1) def test_generic_filter_quantize() -> None: data = np.linspace(0, 10, 256, dtype="float32").reshape((16, 16)) - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - filters=[_numcodecs.Quantize(digits=3)], - ) + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[_numcodecs.Quantize(digits=3)], + ) a[:, :] = data.copy() - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - b = open_array(a.store, mode="r") + b = open_array(a.store, mode="r") assert np.allclose(data, b[:, :], atol=0.001) @@ -211,32 +235,29 @@ def test_generic_filter_packbits() -> None: data = np.zeros((16, 16), dtype="bool") data[0:4, :] = True - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[_numcodecs.PackBits()], + ) + + a[:, :] = data.copy() + b = open_array(a.store, mode="r") + np.testing.assert_array_equal(data, b[:, :]) + + with pytest.raises(ValueError, match=".*requires bool dtype.*"): + create_array( {}, shape=data.shape, chunks=(16, 16), - dtype=data.dtype, + dtype="uint32", fill_value=0, filters=[_numcodecs.PackBits()], ) - a[:, :] = data.copy() - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - b = open_array(a.store, mode="r") - np.testing.assert_array_equal(data, b[:, :]) - - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - with pytest.raises(ValueError, match=".*requires bool dtype.*"): - create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype="uint32", - fill_value=0, - filters=[_numcodecs.PackBits()], - ) - @pytest.mark.parametrize( "codec_class", @@ -251,54 +272,49 @@ def test_generic_filter_packbits() -> None: def test_generic_checksum(codec_class: type[_numcodecs._NumcodecsBytesBytesCodec]) -> None: # Check if the codec is available in numcodecs try: - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - codec_class()._codec # noqa: B018 + codec_class()._codec # noqa: B018 except UnknownCodecError as e: # pragma: no cover - pytest.skip(f"{codec_class.codec_name} is not available in numcodecs: {e}") + pytest.skip(f"{codec_class.codec_name} is not available in numcodecs: {e}") # type: ignore[misc] data = np.linspace(0, 10, 256, dtype="float32").reshape((16, 16)) - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - compressors=[codec_class()], - ) + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + compressors=[codec_class()], + ) a[:, :] = data.copy() with codec_conf(): - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - b = open_array(a.store, mode="r") + b = open_array(a.store, mode="r") np.testing.assert_array_equal(data, b[:, :]) @pytest.mark.parametrize("codec_class", [_numcodecs.PCodec, _numcodecs.ZFPY]) def test_generic_bytes_codec(codec_class: type[_numcodecs._NumcodecsArrayBytesCodec]) -> None: try: - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - codec_class()._codec # noqa: B018 + codec_class()._codec # noqa: B018 except ValueError as e: # pragma: no cover if "codec not available" in str(e): - pytest.xfail(f"{codec_class.codec_name} is not available: {e}") + pytest.xfail(f"{codec_class.codec_name} is not available: {e}") # type: ignore[misc] else: raise except ImportError as e: # pragma: no cover - pytest.xfail(f"{codec_class.codec_name} is not available: {e}") + pytest.xfail(f"{codec_class.codec_name} is not available: {e}") # type: ignore[misc] data = np.arange(0, 256, dtype="float32").reshape((16, 16)) - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - serializer=codec_class(), - ) + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + serializer=codec_class(), + ) a[:, :] = data.copy() np.testing.assert_array_equal(data, a[:, :]) @@ -307,34 +323,30 @@ def test_generic_bytes_codec(codec_class: type[_numcodecs._NumcodecsArrayBytesCo def test_delta_astype() -> None: data = np.linspace(0, 10, 256, dtype="i8").reshape((16, 16)) - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - a = create_array( - {}, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - filters=[ - _numcodecs.Delta(dtype="i8", astype="i2"), - ], - ) + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[ + _numcodecs.Delta(dtype="i8", astype="i2"), + ], + ) a[:, :] = data.copy() with codec_conf(): - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - b = open_array(a.store, mode="r") + b = open_array(a.store, mode="r") np.testing.assert_array_equal(data, b[:, :]) def test_repr() -> None: - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - codec = _numcodecs.LZ4(level=5) + codec = _numcodecs.LZ4(level=5) assert repr(codec) == "LZ4(codec_name='numcodecs.lz4', codec_config={'level': 5})" def test_to_dict() -> None: - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - codec = _numcodecs.LZ4(level=5) + codec = _numcodecs.LZ4(level=5) assert codec.to_dict() == {"name": "numcodecs.lz4", "configuration": {"level": 5}} @@ -367,10 +379,9 @@ def test_to_dict() -> None: def test_codecs_pickleable(codec_cls: type[_numcodecs._NumcodecsCodec]) -> None: # Check if the codec is available in numcodecs try: - with pytest.warns(ZarrUserWarning, match=EXPECTED_WARNING_STR): - codec = codec_cls() + codec = codec_cls() except UnknownCodecError as e: # pragma: no cover - pytest.skip(f"{codec_cls.codec_name} is not available in numcodecs: {e}") + pytest.skip(f"{codec_cls.codec_name} is not available in numcodecs: {e}") # type: ignore[misc] expected = codec diff --git a/tests/test_codecs/test_scale_offset.py b/tests/test_codecs/test_scale_offset.py new file mode 100644 index 0000000000..0081bb1901 --- /dev/null +++ b/tests/test_codecs/test_scale_offset.py @@ -0,0 +1,483 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest + +import zarr +from tests.conftest import Expect, ExpectFail +from zarr.codecs.scale_offset import ( + ScaleOffset, + _decode, + _decode_fits_natively, + _encode, +) +from zarr.core.buffer.core import default_buffer_prototype +from zarr.storage._memory import MemoryStore + +# --------------------------------------------------------------------------- +# Serialization +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + Expect(input=ScaleOffset(), output={"name": "scale_offset"}, id="default"), + Expect( + input=ScaleOffset(offset=5), + output={"name": "scale_offset", "configuration": {"offset": 5}}, + id="offset-only", + ), + Expect( + input=ScaleOffset(scale=0.1), + output={"name": "scale_offset", "configuration": {"scale": 0.1}}, + id="scale-only", + ), + Expect( + input=ScaleOffset(offset=5, scale=0.1), + output={"name": "scale_offset", "configuration": {"offset": 5, "scale": 0.1}}, + id="both", + ), + ], + ids=lambda c: c.id, +) +def test_to_dict(case: Expect[ScaleOffset, dict[str, Any]]) -> None: + """to_dict produces the expected JSON structure.""" + assert case.input.to_dict() == case.output + + +@pytest.mark.parametrize( + "case", + [ + Expect(input={"name": "scale_offset"}, output=(0, 1), id="no-config"), + Expect( + input={"name": "scale_offset", "configuration": {"offset": 3, "scale": 2}}, + output=(3, 2), + id="with-config", + ), + ], + ids=lambda c: c.id, +) +def test_from_dict(case: Expect[dict[str, Any], tuple[int | float, int | float]]) -> None: + """from_dict deserializes configuration with correct values and defaults.""" + codec = ScaleOffset.from_dict(case.input) + expected_offset, expected_scale = case.output + assert codec.offset == expected_offset + assert codec.scale == expected_scale + + +def test_serialization_roundtrip() -> None: + """to_dict followed by from_dict produces an equal codec.""" + original = ScaleOffset(offset=7, scale=0.5) + restored = ScaleOffset.from_dict(original.to_dict()) + assert original == restored + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"offset": [1, 2]}, + exception=TypeError, + id="list-offset", + msg="offset must be a number or string", + ), + ExpectFail( + input={"scale": [1, 2]}, + exception=TypeError, + id="list-scale", + msg="scale must be a number or string", + ), + ], + ids=lambda c: c.id, +) +def test_construction_rejects_non_numeric(case: ExpectFail[dict[str, Any]]) -> None: + """Non-numeric offset or scale is rejected at construction time.""" + with case.raises(): + ScaleOffset(**case.input) + + +@pytest.mark.parametrize( + "case", + [ + Expect(input={"offset": 5, "scale": 2}, output=(5, 2), id="int"), + Expect(input={"offset": 0.5, "scale": 0.1}, output=(0.5, 0.1), id="float"), + ], + ids=lambda c: c.id, +) +def test_construction_accepts_numeric( + case: Expect[dict[str, Any], tuple[int | float, int | float]], +) -> None: + """Integer and float values are accepted for both parameters.""" + codec = ScaleOffset(**case.input) + assert codec.offset == case.output[0] + assert codec.scale == case.output[1] + + +# --------------------------------------------------------------------------- +# Encode / decode +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("dtype", "offset", "scale"), + [ + ("float64", 10.0, 0.1), + ("float32", 5.0, 2.0), + ("int32", 0, 1), + ], + ids=["float64", "float32", "int32-identity"], +) +def test_encode_decode_roundtrip(dtype: str, offset: float, scale: float) -> None: + """Data survives encode → decode.""" + + arr = zarr.create_array( + store={}, + shape=(100,), + dtype=dtype, + chunks=(100,), + filters=[ScaleOffset(offset=offset, scale=scale)], + compressors=None, + fill_value=0, + ) + data = np.arange(100, dtype=dtype) + arr[:] = data + np.testing.assert_array_almost_equal(arr[:], data) # type: ignore[arg-type] + + +def test_fill_value_transformed() -> None: + """Fill value is transformed through the encode formula and read back correctly.""" + arr = zarr.create_array( + store={}, + shape=(10,), + dtype="float64", + chunks=(10,), + filters=[ScaleOffset(offset=5, scale=2)], + compressors=None, + fill_value=10.0, + ) + # fill_value=10.0, encode: (10 - 5) * 2 = 10.0 stored + # Reading back without writing should return the original fill value + np.testing.assert_array_equal(arr[:], np.full(10, 10.0)) + + +def test_identity_is_noop() -> None: + """Default codec (offset=0, scale=1) is a no-op.""" + import zarr + + arr = zarr.create_array( + store={}, + shape=(50,), + dtype="float64", + chunks=(50,), + filters=[ScaleOffset()], + compressors=None, + fill_value=0, + ) + data = np.arange(50, dtype="float64") + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + + +def test_rejects_complex_dtype() -> None: + """Complex dtypes are rejected at array creation time.""" + + with pytest.raises(ValueError, match="only supports integer and floating-point"): + zarr.create_array( + store={}, + shape=(10,), + dtype="complex128", + chunks=(10,), + filters=[ScaleOffset(offset=1, scale=2)], + compressors=None, + fill_value=0, + ) + + +def test_uint64_large_value_roundtrip() -> None: + """uint64 values above 2**63 must survive encode+decode (spec requires uint64 support).""" + + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="uint64", + chunks=(3,), + filters=[ScaleOffset(offset=0, scale=1)], + compressors=None, + fill_value=0, + ) + # Value above int64.max (2**63 - 1) — would wrap if we used int64 as wide dtype. + data = np.array([0, 2**63, 2**64 - 1], dtype="uint64") + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + + +def test_float_nan_inf_preserved() -> None: + """NaN and Inf are representable in float dtypes per IEEE 754 and must pass through.""" + + arr = np.array([1.0, np.nan, np.inf, -np.inf], dtype="float64") + encoded = _encode(arr, np.float64(0.0), np.float64(2.0)) + np.testing.assert_array_equal(encoded[[0]], np.array([2.0])) + assert np.isnan(encoded[1]) + assert encoded[2] == np.inf + assert encoded[3] == -np.inf + decoded = _decode(encoded, np.float64(0.0), np.float64(2.0), scale_repr=2.0) + np.testing.assert_array_equal(decoded[[0]], np.array([1.0])) + assert np.isnan(decoded[1]) + + +def test_uint64_encode_rejects_underflow() -> None: + """uint64 underflow during encode raises rather than silently wrapping.""" + + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="uint64", + chunks=(3,), + filters=[ScaleOffset(offset=100, scale=1)], + compressors=None, + fill_value=100, + ) + with pytest.raises(ValueError, match="outside the range of dtype uint64"): + arr[:] = np.array([100, 50, 200], dtype="uint64") + + +@pytest.mark.parametrize( + ("dtype", "scale"), + [ + ("int32", 0), + ("int32", "0"), + ("float64", 0.0), + ("float64", "0.0"), + ("float64", "0x0000000000000000"), + ], + ids=["int-numeric", "int-string", "float-numeric", "float-string", "float-hex"], +) +def test_rejects_zero_scale(dtype: str, scale: object) -> None: + """scale=0 is rejected (destroys data and breaks decode division). + + A string ``scale`` is a documented input, so every spelling of zero has to be + rejected the same way as the numeric one. + """ + + with pytest.raises(ValueError, match="scale must be non-zero"): + zarr.create_array( + store={}, + shape=(10,), + dtype=dtype, + chunks=(10,), + filters=[ScaleOffset(offset=0, scale=scale)], + compressors=None, + fill_value=0, + ) + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"dtype": "int32", "offset": 1.5, "scale": 1}, + exception=ValueError, + id="float-offset-for-int", + msg="offset value 1.5 is not representable", + ), + ExpectFail( + input={"dtype": "int32", "offset": 0, "scale": 0.5}, + exception=ValueError, + id="float-scale-for-int", + msg="scale value 0.5 is not representable", + ), + ExpectFail( + input={"dtype": "int16", "offset": "NaN", "scale": 1}, + exception=ValueError, + id="nan-offset-for-int", + msg="offset value 'NaN' is not representable", + ), + ], + ids=lambda c: c.id, +) +def test_rejects_unrepresentable_scale_offset(case: ExpectFail[dict[str, Any]]) -> None: + """Scale/offset values that can't be represented in the array dtype are rejected.""" + + with case.raises(): + zarr.create_array( + store={}, + shape=(10,), + dtype=case.input["dtype"], + chunks=(10,), + filters=[ScaleOffset(offset=case.input["offset"], scale=case.input["scale"])], + compressors=None, + fill_value=0, + ) + + +def test_dtype_preservation() -> None: + """Integer scale/offset arithmetic preserves the array dtype when division is exact.""" + + arr = zarr.create_array( + store={}, + shape=(10,), + dtype="int8", + chunks=(10,), + filters=[ScaleOffset(offset=1, scale=2)], + compressors=None, + fill_value=0, + ) + data = np.arange(10, dtype="int8") + arr[:] = data + # encode=(x-1)*2 is always divisible by scale=2, so decode is exact + np.testing.assert_array_equal(arr[:], data) + + +async def test_integer_decode_rejects_non_exact_division() -> None: + """Decoding an integer array raises when the stored value isn't divisible by scale.""" + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(3,), + dtype="int8", + chunks=(3,), + filters=[ScaleOffset(offset=0, scale=2)], + compressors=None, + fill_value=0, + ) + # Write raw encoded bytes directly so we can inject a value that isn't divisible by scale. + # Array layout: int8 [2, 3, 4]; 3 % 2 != 0, so decode must fail. + + buf = default_buffer_prototype().buffer.from_bytes(np.array([2, 3, 4], dtype="int8").tobytes()) + await arr.store_path.store.set("c/0", buf) + with pytest.raises(ValueError, match="non-zero remainder"): + arr[:] + + +def test_encode_rejects_signed_integer_overflow() -> None: + """Encoding raises when (value - offset) * scale exceeds the target integer range.""" + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="int8", + chunks=(3,), + filters=[ScaleOffset(offset=0, scale=100)], + compressors=None, + fill_value=0, + ) + # 2 * 100 = 200, outside int8 range [-128, 127] + with pytest.raises(ValueError, match="outside the range of dtype int8"): + arr[:] = np.array([0, 1, 2], dtype="int8") + + +def test_encode_rejects_unsigned_integer_underflow() -> None: + """Encoding raises when value - offset underflows an unsigned dtype.""" + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="uint8", + chunks=(3,), + filters=[ScaleOffset(offset=10, scale=1)], + compressors=None, + fill_value=10, + ) + # 5 - 10 = -5, outside uint8 range [0, 255] + with pytest.raises(ValueError, match="outside the range of dtype uint8"): + arr[:] = np.array([10, 5, 20], dtype="uint8") + + +def test_float32_dtype_preserved() -> None: + """float32 arrays survive encode+decode without being promoted to float64.""" + arr = np.arange(100, dtype="float32") + offset = np.float32(5.0) + scale = np.float32(0.25) + encoded = _encode(arr, offset, scale) + assert encoded.dtype == np.dtype("float32") + decoded = _decode(encoded, offset, scale, scale_repr=0.25) + assert decoded.dtype == np.dtype("float32") + + +def test_float_encode_rejects_wider_scalar() -> None: + """A float64 scalar passed with a float32 array must not silently widen the result.""" + arr = np.arange(10, dtype="float32") + # A numpy float64 scalar (not a Python float — NEP 50 exempts those) mixed with a + # float32 ndarray promotes to float64. The codec must reject that. + with pytest.raises(ValueError, match="changed dtype from float32 to float64"): + _encode(arr, np.float64(5.0), np.float64(0.25)) + + +def test_float_decode_rejects_wider_scalar() -> None: + """A float64 scalar passed with a float32 array must not silently widen on decode.""" + arr = np.arange(10, dtype="float32") + with pytest.raises(ValueError, match="changed dtype from float32 to float64"): + _decode(arr, np.float64(5.0), np.float64(0.25), scale_repr=0.25) + + +async def test_decode_rejects_integer_overflow_on_offset_add() -> None: + """Decoding raises when quotient + offset overflows the target integer dtype.""" + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(3,), + dtype="int8", + chunks=(3,), + filters=[ScaleOffset(offset=100, scale=1)], + compressors=None, + fill_value=0, + ) + # encoded=100 → decoded = 100/1 + 100 = 200, outside int8 range + buf = default_buffer_prototype().buffer.from_bytes( + np.array([0, 50, 100], dtype="int8").tobytes() + ) + await arr.store_path.store.set("c/0", buf) + with pytest.raises(ValueError, match="outside the range of dtype int8"): + arr[:] + + +def test_decode_fits_natively_negative_scale() -> None: + """_decode_fits_natively handles negative scale by swapping bounds.""" + # For a negative scale, x // scale flips the relationship between min/max. + # The function should use info.max // scale as the lower bound and info.min // scale + # as the upper bound. + dtype = np.dtype("int16") + # scale=-2 inverts; offset=0 means range is just q_lo..q_hi + assert _decode_fits_natively(dtype, offset=0, scale=-2) is True + # An offset that pushes the range out of bounds returns False + assert _decode_fits_natively(dtype, offset=100000, scale=-2) is False + + +async def test_decode_int_widened_path() -> None: + """When _decode_fits_natively returns False, decode falls through to the widened path.""" + # For uint32 with offset near max, q_hi + offset can exceed uint32 if computed in target dtype. + # The widened path uses int64 arithmetic and range-checks the result. + # We bypass encode by writing raw bytes directly to the store. + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(3,), + dtype="uint32", + chunks=(3,), + # offset large enough that _decode_fits_natively returns False + filters=[ScaleOffset(offset=2**31, scale=1)], + compressors=None, + # fill_value must be >= offset to avoid uint32 underflow during encode + fill_value=2**31, + ) + # Encoded values that, when added to offset, stay within uint32 + buf = default_buffer_prototype().buffer.from_bytes( + np.array([0, 100, 1000], dtype="uint32").tobytes() + ) + await arr.store_path.store.set("c/0", buf) + expected = np.array([2**31, 2**31 + 100, 2**31 + 1000], dtype="uint32") + np.testing.assert_array_equal(arr[:], expected) + + +def test_compute_encoded_size() -> None: + """compute_encoded_size returns the input byte length unchanged (codec is fixed-size).""" + codec = ScaleOffset(offset=0, scale=1) + # The chunk_spec argument is unused; pass any sentinel + assert codec.compute_encoded_size(input_byte_length=100, _chunk_spec=None) == 100 # type: ignore[arg-type] + assert codec.compute_encoded_size(input_byte_length=0, _chunk_spec=None) == 0 # type: ignore[arg-type] diff --git a/tests/test_codecs/test_sharding.py b/tests/test_codecs/test_sharding.py index d7cbeb5bdb..de576dbef5 100644 --- a/tests/test_codecs/test_sharding.py +++ b/tests/test_codecs/test_sharding.py @@ -1,6 +1,8 @@ +import enum import pickle -import re -from typing import Any +import warnings +from typing import Any, cast, get_args +from unittest.mock import AsyncMock import numpy as np import numpy.typing as npt @@ -13,17 +15,87 @@ from zarr.abc.store import Store from zarr.codecs import ( BloscCodec, + BytesCodec, + Crc32cCodec, ShardingCodec, - ShardingCodecIndexLocation, TransposeCodec, ) +from zarr.codecs.sharding import ( + INDEX_LOCATION, + MAX_UINT_64, + IndexLocation, + ShardingCodecIndexLocation, + SubchunkWriteOrder, + _ShardIndex, + _ShardReader, +) from zarr.core.buffer import NDArrayLike, default_buffer_prototype -from zarr.storage import StorePath, ZipStore +from zarr.core.indexing import lexicographic_order_coords +from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.storage import MemoryStore, StorePath, ZipStore from ..conftest import ArrayRequest from .test_codecs import _AsyncArrayProxy, order_from_dim +def _reads_are_sync(store_mock: AsyncMock) -> bool: + """True when the partial-shard read for this store+pipeline goes through the + synchronous methods (get_sync / get_ranges_sync). That requires BOTH the + configured pipeline to be the sync (Fused) one AND the store to support sync + reads — a Fused read against a non-sync store (e.g. ZipStore) falls back to + the async path. Lets the partial-shard-read tests assert the same intent + against whichever method family is actually exercised.""" + from zarr.abc.store import SupportsGetSync + from zarr.core.config import config + + pipeline_is_sync = "Fused" in config.get("codec_pipeline.path") + # store_mock wraps the real store; check the wrapped class for sync support. + wrapped = getattr(store_mock, "_mock_wraps", store_mock) + return pipeline_is_sync and isinstance(wrapped, SupportsGetSync) + + +def _index_read_count(store_mock: AsyncMock) -> int: + """Number of shard-index reads, regardless of sync/async pipeline.""" + method = store_mock.get_sync if _reads_are_sync(store_mock) else store_mock.get + return int(method.call_count) + + +def _range_read_count(store_mock: AsyncMock) -> int: + """Number of coalesced chunk-data reads, regardless of sync/async pipeline.""" + method = store_mock.get_ranges_sync if _reads_are_sync(store_mock) else store_mock.get_ranges + return int(method.call_count) + + +def _fail_index_read(store_mock: AsyncMock) -> None: + """Simulate the shard-index load returning nothing, for the active path.""" + if _reads_are_sync(store_mock): + store_mock.get_sync.return_value = None + else: + store_mock.get.return_value = None + + +def _fail_chunk_reads( + store_mock: AsyncMock, key_absent_exc: type[Exception] = FileNotFoundError +) -> None: + """Simulate chunk-data loads failing (key absent), for the active path. + + Async get_ranges raises a BaseExceptionGroup; the sync get_ranges_sync mirrors + that contract, so both inject a FileNotFoundError-bearing group.""" + if _reads_are_sync(store_mock): + + def fail_sync(key: str, byte_ranges: Any, **kwargs: Any) -> Any: + raise BaseExceptionGroup("chunk read failed", [key_absent_exc(key)]) + + store_mock.get_ranges_sync = fail_sync + else: + + async def fail_async(key: str, byte_ranges: Any, **kwargs: Any) -> Any: + raise BaseExceptionGroup("chunk read failed", [key_absent_exc(key)]) + yield # type: ignore[unreachable] # marks this as an async generator + + store_mock.get_ranges = fail_async + + @pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) @pytest.mark.parametrize("index_location", ["start", "end"]) @pytest.mark.parametrize( @@ -39,7 +111,7 @@ def test_sharding( store: Store, array_fixture: npt.NDArray[Any], - index_location: ShardingCodecIndexLocation, + index_location: IndexLocation, offset: int, ) -> None: """ @@ -77,7 +149,7 @@ def test_sharding( @pytest.mark.parametrize("offset", [0, 10]) def test_sharding_scalar( store: Store, - index_location: ShardingCodecIndexLocation, + index_location: IndexLocation, offset: int, ) -> None: """ @@ -111,7 +183,7 @@ def test_sharding_scalar( indirect=["array_fixture"], ) def test_sharding_partial( - store: Store, array_fixture: npt.NDArray[Any], index_location: ShardingCodecIndexLocation + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation ) -> None: data = array_fixture spath = StorePath(store) @@ -147,7 +219,7 @@ def test_sharding_partial( indirect=["array_fixture"], ) def test_sharding_partial_readwrite( - store: Store, array_fixture: npt.NDArray[Any], index_location: ShardingCodecIndexLocation + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation ) -> None: data = array_fixture spath = StorePath(store) @@ -179,7 +251,7 @@ def test_sharding_partial_readwrite( @pytest.mark.parametrize("index_location", ["start", "end"]) @pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) def test_sharding_partial_read( - store: Store, array_fixture: npt.NDArray[Any], index_location: ShardingCodecIndexLocation + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation ) -> None: data = array_fixture spath = StorePath(store) @@ -198,6 +270,267 @@ def test_sharding_partial_read( assert np.all(read_data == 1) +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_multiple_chunks_partial_shard_read( + store: Store, + index_location: IndexLocation, +) -> None: + array_shape = (16, 64) + shard_shape = (8, 32) + chunk_shape = (2, 4) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=1, + ) + a[:] = data + + store_mock.reset_mock() # ignore store calls during array creation + + # Reads 3 (2 full, 1 partial) chunks each from 2 shards (a subset of both shards) + # for a total of 6 chunks accessed + assert np.allclose(a[0, 22:42], np.arange(22, 42, dtype="float32")) + + # 2 shard index reads + 2 coalesced chunk-data reads (one per shard) + assert _index_read_count(store_mock) == 2 + assert _range_read_count(store_mock) == 2 + + store_mock.reset_mock() + + # Reads 4 chunks from both shards along dimension 0 for a total of 8 chunks accessed + assert np.allclose(a[:, 0], np.arange(0, data.size, array_shape[1], dtype="float32")) + + # 2 shard index reads + 2 coalesced chunk-data reads (one per shard) + assert _index_read_count(store_mock) == 2 + assert _range_read_count(store_mock) == 2 + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_duplicate_read_indexes( + store: Store, + index_location: IndexLocation, +) -> None: + """ + Check that duplicate index reads are handled correctly when + using get_ranges for chunk data. + """ + array_shape = (15,) + shard_shape = (8,) + chunk_shape = (2,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=-1, + ) + a[:] = data + + store_mock.reset_mock() # ignore store calls during array creation + + # Read the same index multiple times from two chunks + indexer = [8, 8, 12, 12] + assert np.array_equal(a[indexer], data[indexer]) + + # 1 shard index read + 1 coalesced chunk-data read + assert _index_read_count(store_mock) == 1 + assert _range_read_count(store_mock) == 1 + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_read_empty_chunks_within_non_empty_shard_write_empty_false( + store: Store, index_location: IndexLocation +) -> None: + """ + Case where + - some, but not all, chunks in the last shard are empty + - the last shard is not complete (array length is not a multiple of shard shape), + this takes us down the partial shard read path + - write_empty_chunks=False so the shard index will have fewer entries than chunks in the shard + """ + # array with mixed empty and non-empty chunks in second shard + data = np.array([ + # shard 0. full 8 elements, all chunks have some non-fill data + 0, 1, 2, 3, 4, 5, 6, 7, + # shard 1. 6 elements (< shard shape) + 2, 0, # chunk 0, written + -9, -9, # chunk 1, all fill, not written + 4, 5 # chunk 2, written + ], dtype="int32") # fmt: off + + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=(14,), + chunks=(2,), + shards={"shape": (8,), "index_location": index_location}, + dtype="int32", + fill_value=-9, + filters=None, + compressors=None, + config={"write_empty_chunks": False}, + ) + a[:] = data + + assert np.array_equal(a[:], data) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_read_empty_chunks_within_empty_shard_write_empty_false( + store: Store, index_location: IndexLocation +) -> None: + """ + Case where + - all chunks in last shard are empty + - the last shard is not complete (array length is not a multiple of shard shape), + this takes us down the partial shard read path + - write_empty_chunks=False so the shard index will have no entries + """ + fill_value = -99 + shard_size = 8 + data = np.arange(14, dtype="int32") + data[shard_size:] = fill_value # 2nd shard is all fill value + + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=(14,), + chunks=(2,), + shards={"shape": (shard_size,), "index_location": index_location}, + dtype="int32", + fill_value=fill_value, + filters=None, + compressors=None, + config={"write_empty_chunks": False}, + ) + a[:] = data + + assert np.array_equal(a[:], data) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_shard_read__index_load_fails( + store: Store, index_location: IndexLocation +) -> None: + """Test fill value is returned when the call to the store to load the bytes of the shard's chunk index fails.""" + array_shape = (16,) + shard_shape = (16,) + chunk_shape = (8,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + fill_value = -999 + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=fill_value, + ) + a[:] = data + + # Loading the index returns None -> simulate an index load failure, on + # whichever read method the active pipeline uses (get / get_sync). + _fail_index_read(store_mock) + + # Read from one of two chunks in a shard to test the partial shard read path + assert a[0] == fill_value + assert a[0] != data[0] + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_shard_read__index_chunk_slice_fails( + store: Store, + index_location: IndexLocation, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Test fill value is returned when looking up a chunk's byte slice within a shard fails.""" + array_shape = (16,) + shard_shape = (16,) + chunk_shape = (8,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + fill_value = -999 + + monkeypatch.setattr( + "zarr.codecs.sharding._ShardIndex.get_chunk_slice", + lambda self, chunk_coords: None, + ) + + a = zarr.create_array( + StorePath(store), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=fill_value, + ) + a[:] = data + + # Read from one of two chunks in a shard to test the partial shard read path + assert a[0] == fill_value + assert a[0] != data[0] + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_shard_read__chunk_load_fails( + store: Store, index_location: IndexLocation +) -> None: + """Test fill value is returned when the call to the store to load a chunk's bytes fails.""" + array_shape = (16,) + shard_shape = (16,) + chunk_shape = (8,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + fill_value = -999 + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=fill_value, + ) + a[:] = data + + # Set up store mock after array creation to simulate chunk load failure. + # Index loads still succeed, but chunk-byte loads fail (the coalesced range + # read raises a BaseExceptionGroup containing FileNotFoundError — the same + # shape produced when a key is absent), on whichever read method the active + # pipeline uses (get_ranges / get_ranges_sync). + store_mock.reset_mock() + _fail_chunk_reads(store_mock) + + # Read from one of two chunks in a shard to test the partial shard read path + assert a[0] == fill_value + assert a[0] != data[0] + + @pytest.mark.parametrize( "array_fixture", [ @@ -208,7 +541,7 @@ def test_sharding_partial_read( @pytest.mark.parametrize("index_location", ["start", "end"]) @pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) def test_sharding_partial_overwrite( - store: Store, array_fixture: npt.NDArray[Any], index_location: ShardingCodecIndexLocation + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation ) -> None: data = array_fixture[:10, :10, :10] spath = StorePath(store) @@ -259,8 +592,8 @@ def test_sharding_partial_overwrite( def test_nested_sharding( store: Store, array_fixture: npt.NDArray[Any], - outer_index_location: ShardingCodecIndexLocation, - inner_index_location: ShardingCodecIndexLocation, + outer_index_location: IndexLocation, + inner_index_location: IndexLocation, ) -> None: data = array_fixture spath = StorePath(store) @@ -307,8 +640,8 @@ def test_nested_sharding( def test_nested_sharding_create_array( store: Store, array_fixture: npt.NDArray[Any], - outer_index_location: ShardingCodecIndexLocation, - inner_index_location: ShardingCodecIndexLocation, + outer_index_location: IndexLocation, + inner_index_location: IndexLocation, ) -> None: data = array_fixture spath = StorePath(store) @@ -401,18 +734,45 @@ async def test_delete_empty_shards(store: Store) -> None: assert len(chunk_bytes) == 16 * 2 + 8 * 8 * 2 + 4 +def test_structured_dtype_fill_value() -> None: + """Sharded arrays with a structured dtype are writable and readable even though + the fill value is an (unhashable) ``np.void`` scalar: the sharding codec's + chunk-spec caches key on ``ArraySpec``, whose hash must handle void fills + (see https://github.com/zarr-developers/zarr-python/issues/3054).""" + dtype = np.dtype([("a", "i4"), ("b", "f4")]) + arr = zarr.create_array( + MemoryStore(), + shape=(8,), + chunks=(2,), + shards=(4,), + dtype=dtype, + fill_value=(1, 2.0), + ) + data = np.array([(i, i / 2) for i in range(8)], dtype=dtype) + arr[:4] = data[:4] + + expected = np.zeros(8, dtype=dtype) + expected[:4] = data[:4] + expected[4:] = (1, 2.0) # untouched shard reads back as the fill value + assert np.array_equal(arr[:], expected) + + def test_pickle() -> None: + """ShardingCodec round-trips through pickle, including the non-serialized + ``subchunk_write_order`` (which ``to_dict`` omits and which must not silently + revert to the ``morton`` default).""" codec = ShardingCodec(chunk_shape=(8, 8)) assert pickle.loads(pickle.dumps(codec)) == codec + ordered = ShardingCodec(chunk_shape=(8, 8), subchunk_write_order="lexicographic") + restored = pickle.loads(pickle.dumps(ordered)) + assert restored == ordered + assert restored.subchunk_write_order == "lexicographic" + @pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) -@pytest.mark.parametrize( - "index_location", [ShardingCodecIndexLocation.start, ShardingCodecIndexLocation.end] -) -async def test_sharding_with_empty_inner_chunk( - store: Store, index_location: ShardingCodecIndexLocation -) -> None: +@pytest.mark.parametrize("index_location", ["start", "end"]) +async def test_sharding_with_empty_inner_chunk(store: Store, index_location: IndexLocation) -> None: data = np.arange(0, 16 * 16, dtype="uint32").reshape((16, 16)) fill_value = 1 @@ -434,13 +794,10 @@ async def test_sharding_with_empty_inner_chunk( @pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) -@pytest.mark.parametrize( - "index_location", - [ShardingCodecIndexLocation.start, ShardingCodecIndexLocation.end], -) +@pytest.mark.parametrize("index_location", ["start", "end"]) @pytest.mark.parametrize("chunks_per_shard", [(5, 2), (2, 5), (5, 5)]) async def test_sharding_with_chunks_per_shard( - store: Store, index_location: ShardingCodecIndexLocation, chunks_per_shard: tuple[int] + store: Store, index_location: IndexLocation, chunks_per_shard: tuple[int] ) -> None: chunk_shape = (2, 1) shape = tuple(x * y for x, y in zip(chunks_per_shard, chunk_shape, strict=False)) @@ -489,16 +846,16 @@ def test_invalid_metadata(store: Store) -> None: def test_invalid_shard_shape() -> None: with pytest.raises( ValueError, - match=re.escape( - "The array's `chunk_shape` (got (16, 16)) needs to be divisible " - "by the shard's inner `chunk_shape` (got (9,))." + match=( + f"Chunk edge length {16} in dimension {0} is not " + f"divisible by the shard's inner chunk size {9}\\." ), ): zarr.create_array( {}, shape=(16, 16), shards=(16, 16), - chunks=(9,), + chunks=(9, 9), dtype=np.dtype("uint8"), fill_value=0, ) @@ -555,3 +912,353 @@ def test_sharding_mixed_integer_list_indexing(store: Store) -> None: s3 = sharded[0:5, 1, 0:3] assert c3.shape == s3.shape == (5, 3) # type: ignore[union-attr] np.testing.assert_array_equal(c3, s3) + + +async def stored_data_and_get_order( + codec: ShardingCodec, chunks_per_shard: tuple[int, ...] +) -> list[tuple[int, ...]]: + shard_shape = tuple(c * s for c, s in zip(chunks_per_shard, codec.chunk_shape, strict=True)) + store = MemoryStore() + arr = zarr.create_array( + StorePath(store), + shape=shard_shape, + dtype="uint8", + chunks=shard_shape, + serializer=codec, + filters=None, + compressors=None, + fill_value=0, + ) + + arr[:] = np.arange(np.prod(shard_shape), dtype="uint8").reshape(shard_shape) + + shard_buf = await store.get("c/0/0", prototype=default_buffer_prototype()) + if shard_buf is None: + raise RuntimeError("data write failed") + index = (await _ShardReader.from_bytes(shard_buf, codec, chunks_per_shard)).index + offset_to_coord: dict[int, tuple[int, ...]] = dict( + zip( + index.get_chunk_slices_vectorized(np.array(list(np.ndindex(chunks_per_shard))))[ + 0 + ], # start + list(np.ndindex(chunks_per_shard)), # coord + strict=True, + ) + ) + + # The physical write order is recovered by sorting coordinates by start offset. + return [coord for _, coord in sorted(offset_to_coord.items())] + + +@pytest.mark.parametrize( + "subchunk_write_order", + get_args(SubchunkWriteOrder), +) +async def test_encoded_subchunk_write_order(subchunk_write_order: SubchunkWriteOrder) -> None: + """Subchunks must be physically laid out in the shard in the order specified by + ``subchunk_write_order``. We verify this by decoding the shard index and sorting + the chunk coordinates by their byte offset. ``unordered`` makes no stable-order + promise, but is deterministic in this implementation, so it is checked the same way.""" + # Use a non-square chunks_per_shard so all orderings are distinguishable. + chunks_per_shard = (3, 2) + chunk_shape = (4, 4) + codec = ShardingCodec( + chunk_shape=chunk_shape, + codecs=[BytesCodec()], + index_codecs=[BytesCodec(), Crc32cCodec()], + index_location="end", + subchunk_write_order=subchunk_write_order, + ) + + actual_order = await stored_data_and_get_order(codec, chunks_per_shard) + expected_order = list(codec._subchunk_order_iter(chunks_per_shard, subchunk_write_order)) + assert actual_order == expected_order + + +@pytest.mark.parametrize( + "subchunk_write_order", + get_args(SubchunkWriteOrder), +) +@pytest.mark.parametrize("do_partial", [True, False], ids=["partial", "complete"]) +def test_subchunk_write_order_roundtrip( + subchunk_write_order: SubchunkWriteOrder, do_partial: bool +) -> None: + """Data written with any ``subchunk_write_order`` must round-trip correctly.""" + chunks_per_shard = (3, 2) + chunk_shape = (4, 4) + shard_shape = tuple(c * s for c, s in zip(chunks_per_shard, chunk_shape, strict=True)) + data = np.arange(np.prod(shard_shape), dtype="uint16").reshape(shard_shape) + arr = zarr.create_array( + StorePath(MemoryStore()), + shape=shard_shape, + dtype=data.dtype, + chunks=shard_shape, + serializer=ShardingCodec( + chunk_shape=chunk_shape, + codecs=[BytesCodec()], + subchunk_write_order=subchunk_write_order, + ), + filters=None, + compressors=None, + fill_value=0, + ) + if do_partial: + sub_data = data[: (shard_shape[0] // 2)] + arr[: (shard_shape[0] // 2)] = data[: (shard_shape[0] // 2)] + data = np.vstack([sub_data, np.zeros_like(sub_data)]) + else: + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + + +# --- Tests for ShardingCodecIndexLocation deprecation --- + + +@pytest.mark.parametrize("location", INDEX_LOCATION) +def test_sharding_codec_accepts_all_index_locations(location: IndexLocation) -> None: + """ + Every value in INDEX_LOCATION is accepted by ShardingCodec and round-trips + to the same value on the stored attribute. Catches drift between the + IndexLocation type alias and the runtime INDEX_LOCATION tuple. + """ + codec = ShardingCodec(chunk_shape=(1,), index_location=location) + assert codec.index_location == location + + +@pytest.mark.parametrize("location", INDEX_LOCATION) +def test_sharding_codec_json_roundtrip_index_location( + location: IndexLocation, +) -> None: + """ + ShardingCodec.to_dict writes index_location as the bare literal string, + and the round-trip through from_dict preserves equality. Asserting the + on-disk index_location value (not just the round-trip) catches drift + between ShardingCodec's runtime representation and the V3 wire form. + """ + codec = ShardingCodec(chunk_shape=(1,), index_location=location) + serialized = codec.to_dict() + assert serialized["configuration"]["index_location"] == location # type: ignore[index, call-overload] + restored = ShardingCodec.from_dict(serialized) + assert restored == codec + + +@pytest.mark.parametrize( + ("member", "expected"), + [("start", "start"), ("end", "end")], +) +def test_sharding_index_location_member_access_warns(member: str, expected: str) -> None: + """ + Accessing a member on the deprecated ShardingCodecIndexLocation class + emits a DeprecationWarning and resolves to the equivalent literal string. + """ + with pytest.warns(DeprecationWarning, match=rf"ShardingCodecIndexLocation\.{member}"): + value = getattr(ShardingCodecIndexLocation, member) + assert value == expected + + +def test_sharding_index_location_class_imports_silently() -> None: + """ + Importing the deprecated ShardingCodecIndexLocation class by name must not + emit a warning; only member access does. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + from zarr.codecs.sharding import ( # noqa: F401 + ShardingCodecIndexLocation as _SCIL, + ) + + +def test_sharding_codec_init_with_enum_instance_warns() -> None: + """ + Passing a foreign enum.Enum instance to ShardingCodec.__init__ triggers + the init-level deprecation warning (from _coerce_enum_input) and + normalizes the value to the corresponding literal string. Covers the + case where a downstream package defined its own enum-shaped class to + bridge between zarr's old API and its own. + """ + + class LegacyIndexLocation(enum.Enum): + end = "end" + + with pytest.warns(DeprecationWarning, match=r"Passing an enum to ShardingCodec"): + codec = ShardingCodec( + chunk_shape=(1,), + index_location=cast(ShardingCodecIndexLocation, LegacyIndexLocation.end), + ) + assert codec.index_location == "end" + + +def test_sharding_codec_init_with_deprecated_class_member() -> None: + """ + The realistic legacy-upgrade idiom: ShardingCodec(index_location=ShardingCodecIndexLocation.end). + Member access on ShardingCodecIndexLocation emits one DeprecationWarning + (from the metaclass) and resolves to the bare string, which ShardingCodec + then accepts without further warning. No second warning from + _coerce_enum_input because the metaclass already produced a string. + + The cast is necessary because the metaclass __getattr__ is typed as + returning str, which does not statically match the codec's + IndexLocation parameter even though the runtime value does. + """ + with pytest.warns(DeprecationWarning, match=r"ShardingCodecIndexLocation\.end"): + codec = ShardingCodec( + chunk_shape=(1,), + index_location=cast(IndexLocation, ShardingCodecIndexLocation.end), + ) + assert codec.index_location == "end" + + +def test_sharding_codec_rejects_unknown_index_location() -> None: + """ + ShardingCodec.__init__ raises ValueError when index_location is outside + INDEX_LOCATION, and the error message names the offending parameter. + """ + kwargs: dict[str, Any] = {"chunk_shape": (1,), "index_location": "middle"} + with pytest.raises(ValueError, match="index_location must be one of"): + ShardingCodec(**kwargs) + + +def test_sharding_index_location_attribute_error_for_unknown_member() -> None: + """ + Attribute access for a name that is not a known member of the deprecated + ShardingCodecIndexLocation class falls through to AttributeError. + """ + with pytest.raises(AttributeError): + getattr(ShardingCodecIndexLocation, "not_a_member") # noqa: B009 + + +@pytest.mark.parametrize("index_location", INDEX_LOCATION) +def test_create_array_with_dict_shards_index_location( + index_location: IndexLocation, +) -> None: + """ + zarr.create_array accepts a `ShardsConfigParam`-shaped dict for `shards` + with an explicit `index_location`, and the resulting sharding codec + stores that value. Covers the `isinstance(shards, dict)` branch in + init_array that the tuple-shaped `shards` form doesn't reach. + """ + arr = zarr.create_array( + store={}, + shape=(8,), + chunks=(2,), + shards={"shape": (4,), "index_location": index_location}, + dtype="uint8", + ) + assert isinstance(arr.metadata, ArrayV3Metadata) # needed for mypy + sharding = arr.metadata.codecs[0] + assert isinstance(sharding, ShardingCodec) + assert sharding.index_location == index_location + + +def test_sharding_zero_dimensional() -> None: + """Regression test for https://github.com/zarr-developers/zarr-python/issues/3751""" + arr = zarr.create_array({}, shape=(), dtype="f4", chunks=(), shards=()) + arr[()] = 42.0 + assert arr[()] == pytest.approx(42.0) + # Overwriting should also work + arr[()] = 43.0 + assert arr[()] == pytest.approx(43.0) + + +def test_shard_index_stores_chunks_per_shard_explicitly() -> None: + """_ShardIndex stores the chunk grid shape as an explicit field.""" + index = _ShardIndex.create_empty((2, 3)) + assert index.chunks_per_shard == (2, 3) + + # 0-D: chunks_per_shard is the empty tuple, distinct from the array's rank + index_0d = _ShardIndex.create_empty(()) + assert index_0d.chunks_per_shard == () + + +@pytest.mark.parametrize("chunks_per_shard", [(), (3,), (2, 3)]) +def test_shard_index_get_chunk_slices_vectorized(chunks_per_shard: tuple[int, ...]) -> None: + """get_chunk_slices_vectorized works uniformly across chunk grid ranks, including 0-D.""" + index = _ShardIndex.create_empty(chunks_per_shard) + # Write the first chunk; leave the rest (if any) empty. + all_coords = list(lexicographic_order_coords(chunks_per_shard)) + index.set_chunk_slice(all_coords[0], slice(10, 14)) + + coords_array = np.array(all_coords, dtype=np.uint64).reshape( + len(all_coords), len(chunks_per_shard) + ) + starts, ends, valid = index.get_chunk_slices_vectorized(coords_array) + + expected_valid = np.zeros(len(all_coords), dtype=bool) + expected_valid[0] = True + np.testing.assert_array_equal(valid, expected_valid) + assert starts[0] == 10 + assert ends[0] == 14 + np.testing.assert_array_equal(starts[~expected_valid], MAX_UINT_64) + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize( + "pipeline_path", + [ + "zarr.core.codec_pipeline.FusedCodecPipeline", + "zarr.core.codec_pipeline.BatchedCodecPipeline", + ], +) +def test_sharding_vlen_inner_codec_roundtrip(pipeline_path: str) -> None: + """A sharded array whose inner codec chain is a variable-length codec + (VLenUTF8) must round-trip under either pipeline. + + Regression: the Fused pipeline's bulk-decode gate calls `c.is_fixed_size` + on every inner codec. `is_fixed_size` is declared on the Codec ABC but had + no default, so codecs that don't set it (VLenUTF8/VLenBytes, numcodecs + wrappers) raised AttributeError on read — crashing every sharded read whose + inner chain included such a codec. + """ + # The variable-length StringDType resolves to a VLenUTF8Codec inner chain + # (a fixed-width None: + """to_dict_vectorized derives its own coords and maps present chunks to buffers, empty to None. + + The reader is given the full per-shard chunk grid implicitly (it reads + ``chunks_per_shard`` off its own index), so the result must contain every + lexicographic coordinate as a key, with the stored bytes for present chunks + and ``None`` for empty ones. + """ + all_coords = list(lexicographic_order_coords(chunks_per_shard)) + # Lay two chunks back-to-back in the buffer; leave the rest (if any) empty. + payload = b"abcdXY" + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice(all_coords[0], slice(0, 4)) + present = {all_coords[0]: payload[0:4]} + if len(all_coords) > 1: + index.set_chunk_slice(all_coords[1], slice(4, 6)) + present[all_coords[1]] = payload[4:6] + + reader = _ShardReader() + reader.index = index + reader.buf = default_buffer_prototype().buffer.from_bytes(payload) + + result = reader.to_dict_vectorized() + + # Every lexicographic coordinate is present as a key, in order. + assert list(result.keys()) == all_coords + for coords in all_coords: + buf = result[coords] + if coords in present: + assert buf is not None + assert buf.to_bytes() == present[coords] + else: + assert buf is None diff --git a/tests/test_codecs/test_sharding_unit.py b/tests/test_codecs/test_sharding_unit.py new file mode 100644 index 0000000000..d8b8242a28 --- /dev/null +++ b/tests/test_codecs/test_sharding_unit.py @@ -0,0 +1,1144 @@ +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, replace +from typing import TYPE_CHECKING, Any, Literal, cast +from unittest.mock import AsyncMock + +import numpy as np +import numpy.typing as npt +import pytest + +import zarr +from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.sharding import ( + MAX_UINT_64, + ShardingCodec, + _ShardIndex, + _ShardingByteGetter, + _ShardReader, +) +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import Buffer as ABCBuffer +from zarr.core.buffer import NDBuffer, default_buffer_prototype +from zarr.core.buffer.cpu import Buffer +from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer +from zarr.core.chunk_grids import ChunkGrid +from zarr.core.config import config +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.indexing import BasicIndexer +from zarr.storage._common import StorePath +from zarr.storage._memory import MemoryStore + +if TYPE_CHECKING: + from zarr.core.array import ShardsConfigParam + from zarr.core.array_spec import ArrayConfigParams + +# ============================================================================ +# _ShardIndex tests +# ============================================================================ + + +def test_shard_index_create_empty() -> None: + """Test that create_empty creates an index filled with MAX_UINT_64.""" + chunks_per_shard = (2, 3) + index = _ShardIndex.create_empty(chunks_per_shard) + + assert index.chunks_per_shard == chunks_per_shard + assert index.offsets_and_lengths.shape == (2, 3, 2) + assert index.offsets_and_lengths.dtype == np.dtype(" None: + """Test create_empty with 1D chunks_per_shard.""" + chunks_per_shard = (4,) + index = _ShardIndex.create_empty(chunks_per_shard) + + assert index.chunks_per_shard == chunks_per_shard + assert index.offsets_and_lengths.shape == (4, 2) + + +def test_shard_index_is_all_empty_true() -> None: + """Test is_all_empty returns True for a freshly created empty index.""" + index = _ShardIndex.create_empty((2, 2)) + assert index.is_all_empty() is True + + +def test_shard_index_is_all_empty_false() -> None: + """Test is_all_empty returns False when at least one chunk is set.""" + index = _ShardIndex.create_empty((2, 2)) + index.set_chunk_slice((0, 0), slice(0, 100)) + assert index.is_all_empty() is False + + +def test_shard_index_get_chunk_slice_empty() -> None: + """Test get_chunk_slice returns None for empty chunks.""" + index = _ShardIndex.create_empty((2, 2)) + assert index.get_chunk_slice((0, 0)) is None + assert index.get_chunk_slice((1, 1)) is None + + +def test_shard_index_get_chunk_slice_set() -> None: + """Test get_chunk_slice returns correct (start, end) tuple after setting.""" + index = _ShardIndex.create_empty((2, 2)) + index.set_chunk_slice((0, 1), slice(100, 200)) + + result = index.get_chunk_slice((0, 1)) + assert result == (100, 200) + + +def test_shard_index_set_chunk_slice() -> None: + """Test set_chunk_slice correctly sets offset and length.""" + index = _ShardIndex.create_empty((3, 3)) + + # Set a chunk slice + index.set_chunk_slice((1, 2), slice(50, 150)) + + # Verify the underlying array + assert index.offsets_and_lengths[1, 2, 0] == 50 # offset + assert index.offsets_and_lengths[1, 2, 1] == 100 # length (150 - 50) + + +def test_shard_index_set_chunk_slice_none() -> None: + """Test set_chunk_slice with None marks chunk as empty.""" + index = _ShardIndex.create_empty((2, 2)) + + # First set a value + index.set_chunk_slice((0, 0), slice(0, 100)) + assert index.get_chunk_slice((0, 0)) == (0, 100) + + # Then clear it + index.set_chunk_slice((0, 0), None) + assert index.get_chunk_slice((0, 0)) is None + assert index.offsets_and_lengths[0, 0, 0] == MAX_UINT_64 + assert index.offsets_and_lengths[0, 0, 1] == MAX_UINT_64 + + +def test_shard_index_get_full_chunk_map() -> None: + """Test get_full_chunk_map returns correct boolean array.""" + index = _ShardIndex.create_empty((2, 3)) + + # Set some chunks + index.set_chunk_slice((0, 0), slice(0, 10)) + index.set_chunk_slice((1, 2), slice(10, 20)) + + chunk_map = index.get_full_chunk_map() + + assert chunk_map.shape == (2, 3) + assert chunk_map.dtype == np.bool_ + assert chunk_map[0, 0] is np.True_ + assert chunk_map[0, 1] is np.False_ + assert chunk_map[0, 2] is np.False_ + assert chunk_map[1, 0] is np.False_ + assert chunk_map[1, 1] is np.False_ + assert chunk_map[1, 2] is np.True_ + + +def test_shard_index_localize_chunk() -> None: + """Test _localize_chunk maps global coords to local shard coords via modulo.""" + index = _ShardIndex.create_empty((2, 3)) + + # Within bounds - should return same coords + assert index._localize_chunk((0, 0)) == (0, 0) + assert index._localize_chunk((1, 2)) == (1, 2) + + # Out of bounds - should wrap via modulo + assert index._localize_chunk((2, 0)) == (0, 0) # 2 % 2 = 0 + assert index._localize_chunk((3, 5)) == (1, 2) # 3 % 2 = 1, 5 % 3 = 2 + assert index._localize_chunk((4, 6)) == (0, 0) # 4 % 2 = 0, 6 % 3 = 0 + + +# ============================================================================ +# _load_partial_shard_maybe tests +# +# These exercise the partial-shard read path against a real MemoryStore wrapped +# in a StorePath (the external-store branch in `_load_partial_shard_maybe`), +# plus one test against a real `_ShardingByteGetter` (the in-memory branch used +# by nested sharding). +# ============================================================================ + + +async def _store_path_with_blob(key: str, blob: bytes) -> StorePath: + """Build a `StorePath` over a fresh `MemoryStore` containing `blob` at `key`.""" + store = MemoryStore() + await store.set(key, Buffer.from_bytes(blob)) + return StorePath(store, key) + + +async def test_load_partial_shard_maybe_index_load_fails() -> None: + """Returns None when the shard key is absent (index load fails).""" + codec = ShardingCodec(chunk_shape=(8,)) + byte_getter = StorePath(MemoryStore(), "missing") + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=(2,), + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is None + + +async def test_load_partial_shard_maybe_with_empty_chunks( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Chunks whose index entry is empty are silently skipped.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + # Index where chunk (1,) is empty; the others point into the stored blob. + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((2,), slice(100, 200)) + index.set_chunk_slice((3,), slice(200, 300)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + byte_getter = await _store_path_with_blob("shard", b"x" * 300) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,), (2,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is not None + assert (0,) in result + assert (1,) not in result # empty in index + assert (2,) in result + + +async def test_load_partial_shard_maybe_all_chunks_empty( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Returns an empty dict when all requested chunks are empty (no I/O issued).""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + # Fully-empty index — `get_chunk_slice` returns None for every coord. + index = _ShardIndex.create_empty(chunks_per_shard) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Empty store is fine — we never reach the chunk-read path when all are empty. + byte_getter = StorePath(MemoryStore(), "shard") + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,), (2,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result == {} + + +async def test_load_partial_shard_returns_chunk_contents( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Returns the correct bytes for each requested chunk.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((1,), slice(100, 200)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + blob = b"A" * 100 + b"B" * 100 + byte_getter = await _store_path_with_blob("shard", blob) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is not None + buf_0, buf_1 = result[(0,)], result[(1,)] + assert buf_0 is not None + assert buf_1 is not None + assert buf_0.to_bytes() == b"A" * 100 + assert buf_1.to_bytes() == b"B" * 100 + + +async def test_load_partial_shard_shard_disappears_returns_none( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """If the shard key is missing when chunk reads run, returns None. + + This models a race: the index loaded successfully, but the shard was deleted + before the chunk-byte fetches landed. `Store.get_ranges` surfaces this as a + `BaseExceptionGroup` containing `FileNotFoundError`, which the codec catches + and converts to None to match the index-missing branch's behavior. + """ + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Store has no value for "shard" — `get_ranges` will raise FileNotFoundError. + byte_getter = StorePath(MemoryStore(), "shard") + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is None + + +async def test_load_partial_shard_non_fnf_error_propagates( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Non-FileNotFoundError errors from get_ranges are re-raised, not swallowed. + + Our `BaseExceptionGroup.split(FileNotFoundError)` keeps the "shard gone" + behavior for FNF only; anything else (e.g. an OSError from the underlying + fetch) must bubble up. + """ + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Make the underlying store.get raise OSError. The default Store.get_ranges + # impl routes through self.get; coalesced_get wraps the failure in a + # BaseExceptionGroup, which our code re-raises (minus FNF leaves, of which + # there are none here). + async def boom(*args: object, **kwargs: object) -> Buffer | None: + raise OSError("injected disk error") + + store = MemoryStore() + monkeypatch.setattr(store, "get", boom) + byte_getter = StorePath(store, "shard") + + with pytest.RaisesGroup(pytest.RaisesExc(OSError, match="injected disk error")): + await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + +async def test_load_partial_shard_nested_sharding_path( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Nested sharding: byte_getter is a `_ShardingByteGetter` over an in-memory dict.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((1,), slice(100, 200)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: _ShardingByteGetter, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # The "store" for an inner shard is a dict keyed by outer-chunk coords; the + # byte_getter reads ranges out of one entry of that dict. + blob = b"A" * 100 + b"B" * 100 + shard_dict: dict[tuple[int, ...], Buffer | None] = {(0,): Buffer.from_bytes(blob)} + byte_getter = _ShardingByteGetter(shard_dict, (0,)) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is not None + buf_0, buf_1 = result[(0,)], result[(1,)] + assert buf_0 is not None + assert buf_1 is not None + assert buf_0.to_bytes() == b"A" * 100 + assert buf_1.to_bytes() == b"B" * 100 + + +async def test_load_partial_shard_nested_sharding_missing_outer_chunk( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Nested sharding: outer chunk absent → `_ShardingByteGetter.get` returns None + → chunks are silently skipped, yielding an empty shard_dict.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: _ShardingByteGetter, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Empty outer dict — _ShardingByteGetter.get(...) returns None for any range. + shard_dict: dict[tuple[int, ...], Buffer | None] = {} + byte_getter = _ShardingByteGetter(shard_dict, (0,)) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result == {} + + +# ============================================================================ +# Supporting class tests (_ShardReader, _is_total_shard) +# ============================================================================ + + +def test_shard_reader_create_empty() -> None: + """Test _ShardReader.create_empty creates reader with empty index.""" + chunks_per_shard = (2, 3) + reader = _ShardReader.create_empty(chunks_per_shard) + + assert reader.index.is_all_empty() + assert len(reader.buf) == 0 + assert len(reader) == 2 * 3 + + +def test_shard_reader_iteration() -> None: + """Test _ShardReader iteration yields all chunk coordinates.""" + chunks_per_shard = (2, 2) + reader = _ShardReader.create_empty(chunks_per_shard) + + coords = list(reader) + + assert len(coords) == 4 + assert (0, 0) in coords + assert (0, 1) in coords + assert (1, 0) in coords + assert (1, 1) in coords + + +def test_shard_reader_getitem_raises_for_empty() -> None: + """Test _ShardReader.__getitem__ raises KeyError for empty chunks.""" + chunks_per_shard = (2,) + reader = _ShardReader.create_empty(chunks_per_shard) + + with pytest.raises(KeyError): + _ = reader[(0,)] + + +def test_is_total_shard_full() -> None: + """Test _is_total_shard returns True when all chunk coords are present.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (2, 2) + all_chunk_coords: set[tuple[int, ...]] = {(0, 0), (0, 1), (1, 0), (1, 1)} + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is True + + +def test_is_total_shard_partial() -> None: + """Test _is_total_shard returns False for partial chunk coords.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (2, 2) + all_chunk_coords: set[tuple[int, ...]] = {(0, 0), (1, 1)} # Missing (0, 1) and (1, 0) + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is False + + +def test_is_total_shard_empty() -> None: + """Test _is_total_shard returns False for empty chunk coords.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (2, 2) + all_chunk_coords: set[tuple[int, ...]] = set() + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is False + + +def test_is_total_shard_1d() -> None: + """Test _is_total_shard works with 1D shards.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + all_chunk_coords: set[tuple[int, ...]] = {(0,), (1,), (2,), (3,)} + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is True + + # Partial + partial_coords: set[tuple[int, ...]] = {(0,), (2,)} + assert codec._is_total_shard(partial_coords, chunks_per_shard) is False + + +# ============================================================================ +# _inner_codecs_fixed_size tests +# ============================================================================ + + +def test_inner_codecs_fixed_size_no_compression() -> None: + """Inner codecs without compression should be fixed-size.""" + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + assert codec._inner_codecs_fixed_size is True + + +def test_inner_codecs_fixed_size_with_compression() -> None: + """Inner codecs with compression should NOT be fixed-size.""" + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec(), GzipCodec()]) + assert codec._inner_codecs_fixed_size is False + + +# ============================================================================ +# inner-chain spec threading +# ============================================================================ + + +@dataclass(frozen=True) +class _WidenToInt16(ArrayArrayCodec): + """Test-only sync-capable AA codec that reports its output dtype as int16.""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "_widen_to_int16"} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _WidenToInt16: + return cls() + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + return replace(chunk_spec, dtype=get_data_type_from_native_dtype(np.dtype("int16"))) + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + def _encode_sync(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + def _decode_sync(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + async def _encode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + +def _int8_spec(shape: tuple[int, ...]) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(np.dtype("int8")) # single-byte source + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + + +def test_inner_chunk_transform_threads_spec() -> None: + """The inner codec chain must be evolved with the spec threaded forward. + + A dtype-widening inner array->array codec means the BytesCodec serializer + is evolved against the WIDENED dtype, not the single-byte source — + otherwise it strips its `endian` to None and fails to decode multi-byte + inner chunks. Same contract as the pipeline-level `evolve_codecs` + regression test, applied to `_get_inner_chunk_transform`. + """ + codec = ShardingCodec(chunk_shape=(4,), codecs=[_WidenToInt16(), BytesCodec(endian="little")]) + shard_spec = _int8_spec((8,)) + + transform = codec._get_inner_chunk_transform(shard_spec) + serializer = transform._ab_codec + assert isinstance(serializer, BytesCodec) + assert serializer.endian is not None, ( + "inner BytesCodec lost its `endian` — _get_inner_chunk_transform did not " + "thread the dtype-widening codec's spec into the serializer" + ) + + +def test_evolve_from_array_spec_threads_spec() -> None: + """`ShardingCodec.evolve_from_array_spec` must thread the spec through the + inner chain, like `_get_inner_chunk_transform` does. + + This method runs EARLIER, on the real array-creation path (the outer + pipeline evolves the sharding codec itself), so an unthreaded evolve here + bakes an endian-stripped BytesCodec into the evolved instance's `codecs` + before the transform builders ever run — and the later threaded evolve then + raises instead of recovering. Calling `_get_inner_chunk_transform` on the + EVOLVED instance pins the full real path. + """ + codec = ShardingCodec(chunk_shape=(4,), codecs=[_WidenToInt16(), BytesCodec(endian="little")]) + # the array spec the OUTER pipeline evolves the sharding codec against + array_spec = _int8_spec((8,)) + + evolved = codec.evolve_from_array_spec(array_spec) + inner_serializer = next(c for c in evolved.codecs if isinstance(c, BytesCodec)) + assert inner_serializer.endian is not None, ( + "evolve_from_array_spec evolved the inner BytesCodec against the " + "un-widened spec, stripping its `endian`" + ) + + # and the evolved instance must still build a working inner transform + transform = evolved._get_inner_chunk_transform(array_spec) + serializer = transform._ab_codec + assert isinstance(serializer, BytesCodec) + assert serializer.endian is not None + + +# ============================================================================ +# async whole-shard codec methods +# +# `ShardingCodec` advertises partial decode/encode, so the codec pipeline +# always routes sharded reads/writes through `_decode_partial_single` / +# `_encode_partial_single`. The whole-shard async methods `_decode_single` / +# `_encode_single` are reached only via the direct `ArrayBytesCodec` API (e.g. +# a consumer that calls the codec outside a pipeline), so they get no coverage +# from end-to-end array tests. Pin them with a direct round-trip. +# ============================================================================ + + +@pytest.mark.parametrize("write_empty_chunks", [True, False]) +def test_decode_single_encode_single_roundtrip(write_empty_chunks: bool) -> None: + """`ShardingCodec._encode_single` then `_decode_single` round-trips a whole + shard. Covers the async whole-shard path the pipeline bypasses in favor of + the partial methods.""" + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(50,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=write_empty_chunks), + prototype=default_buffer_prototype(), + ) + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + data = np.arange(50, dtype="float64") + value = CPUNDBuffer.from_numpy_array(data) + + encoded = asyncio.run(codec._encode_single(value, spec)) + assert encoded is not None # data is non-empty -> a shard is always produced + decoded = asyncio.run(codec._decode_single(encoded, spec)) + np.testing.assert_array_equal(decoded.as_numpy_array(), data) + + +def test_encode_single_all_empty_returns_none() -> None: + """`_encode_single` of an all-fill shard under write_empty_chunks=False + elides every inner chunk and returns None (the all-empty branch).""" + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(50,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + fill = CPUNDBuffer.from_numpy_array(np.zeros(50, dtype="float64")) + + assert asyncio.run(codec._encode_single(fill, spec)) is None + + +def test_decode_single_all_empty_fills() -> None: + """`_decode_single` of a shard whose index is all-empty fills the output + with the fill value (the is_all_empty fast path).""" + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(50,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(-1.0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + # an empty shard is just the encoded empty index + empty_index = asyncio.run(codec._encode_shard_index(_ShardIndex.create_empty((5,)))) + decoded = asyncio.run(codec._decode_single(empty_index, spec)) + np.testing.assert_array_equal(decoded.as_numpy_array(), np.full(50, -1.0)) + + +# ============================================================================ +# async-only index codec fallback (#269) +# +# `_decode_shard_index` / `_encode_shard_index` delegate to their sync twins +# when every index codec is sync-capable, and otherwise fall back to the async +# pipeline. The default index chain (bytes + crc32c) is sync-capable, so the +# fallback is exercised only by an async-only index codec. +# ============================================================================ + + +class _AsyncOnlyBytesCodec(ArrayBytesCodec): + """An array<->bytes codec that implements ONLY the async per-chunk methods. + + Wraps a real `BytesCodec` for the actual conversion but deliberately omits + `_encode_sync`/`_decode_sync`, so it is NOT a `SupportsSyncCodec`. Used as + an index codec to force the async-pipeline fallback in + `_decode_shard_index`/`_encode_shard_index`. + """ + + _inner = BytesCodec() + + def to_dict(self) -> dict[str, Any]: + return {"name": "_async_only_bytes"} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _AsyncOnlyBytesCodec: + return cls() + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> _AsyncOnlyBytesCodec: + return self + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + async def _decode_single(self, chunk_bytes: ABCBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return await self._inner._decode_single(chunk_bytes, chunk_spec) + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> ABCBuffer: + result = await self._inner._encode_single(chunk_array, chunk_spec) + assert result is not None + return result + + +def test_shard_index_async_fallback_for_async_only_index_codec() -> None: + """An async-only index codec is not sync-capable, so `_encode_shard_index` + and `_decode_shard_index` must take the async-pipeline fallback (#269) + instead of the sync twins — and still round-trip.""" + from zarr.abc.codec import SupportsSyncCodec + + codec = ShardingCodec( + chunk_shape=(10,), + codecs=[BytesCodec()], + index_codecs=[_AsyncOnlyBytesCodec(), Crc32cCodec()], + ) + assert not codec._index_codecs_sync_capable() + assert not isinstance(_AsyncOnlyBytesCodec(), SupportsSyncCodec) + + chunks_per_shard = (5,) + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 42)) + + encoded = asyncio.run(codec._encode_shard_index(index)) + decoded = asyncio.run(codec._decode_shard_index(encoded, chunks_per_shard)) + np.testing.assert_array_equal(decoded.offsets_and_lengths, index.offsets_and_lengths) + + +# ============================================================================ +# Coalescing config option tests +# +# Assert that the `array.sharding_coalesce_max_gap_bytes` and +# `array.sharding_coalesce_max_bytes` global config keys flow through +# `ArrayConfig` to `Store.get_ranges` as `max_gap_bytes` / +# `max_coalesced_bytes` kwargs, and that per-array `config={...}` overrides +# the global default. +# ============================================================================ + + +def _trigger_partial_shard_read(array_config: ArrayConfigParams | None = None) -> AsyncMock: + """Build a sharded array on a mocked `MemoryStore`, trigger a partial-shard + read via the public read path, and return the `get_ranges` mock. + """ + import zarr + + chunk_shape = (2,) + shard_shape = (8,) + data = np.arange(8, dtype="int32") + + store = MemoryStore() + store_mock = AsyncMock(wraps=store, spec=store.__class__) + + shards: ShardsConfigParam = { + "shape": shard_shape, + "index_location": "end", + } + a = zarr.create_array( + StorePath(store_mock), + shape=(8,), + chunks=chunk_shape, + shards=shards, + dtype=data.dtype, + fill_value=-1, + config=array_config, + ) + a[:] = data + + store_mock.reset_mock() + + # Read a strict subset of chunks to take the partial-shard read path. + _ = a[0:4] + + return cast(AsyncMock, store_mock.get_ranges) + + +def test_load_partial_shard_forwards_global_config_to_get_ranges() -> None: + """Global `array.sharding_coalesce_*` values flow into ArrayConfig at + array-creation time and are forwarded to `Store.get_ranges`.""" + with config.set( + { + "array.sharding_coalesce_max_gap_bytes": 4242, + "array.sharding_coalesce_max_bytes": 424242, + } + ): + get_ranges_mock = _trigger_partial_shard_read() + + assert get_ranges_mock.call_count >= 1 + for call in get_ranges_mock.call_args_list: + kwargs = call.kwargs + assert kwargs["max_gap_bytes"] == 4242 + assert kwargs["max_coalesced_bytes"] == 424242 + + +def test_load_partial_shard_per_array_config_overrides_global() -> None: + """Per-array `config={...}` passed to `create_array` takes precedence over + the global config and is forwarded to `Store.get_ranges`.""" + with config.set( + { + "array.sharding_coalesce_max_gap_bytes": 4242, + "array.sharding_coalesce_max_bytes": 424242, + } + ): + get_ranges_mock = _trigger_partial_shard_read( + array_config={ + "sharding_coalesce_max_gap_bytes": 99, + "sharding_coalesce_max_bytes": 9999, + }, + ) + + assert get_ranges_mock.call_count >= 1 + for call in get_ranges_mock.call_args_list: + kwargs = call.kwargs + assert kwargs["max_gap_bytes"] == 99 + assert kwargs["max_coalesced_bytes"] == 9999 + + +def test_load_partial_shard_uses_config_defaults() -> None: + """Without explicit config, defaults from `zarr.config` are forwarded.""" + get_ranges_mock = _trigger_partial_shard_read() + + assert get_ranges_mock.call_count >= 1 + for call in get_ranges_mock.call_args_list: + kwargs = call.kwargs + assert kwargs["max_gap_bytes"] == config.get("array.sharding_coalesce_max_gap_bytes") + assert kwargs["max_coalesced_bytes"] == config.get("array.sharding_coalesce_max_bytes") + + +async def test_load_partial_shard_explicit_kwargs_passthrough( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """`_load_partial_shard_maybe` forwards its explicit kwargs to `get_ranges`.""" + codec = ShardingCodec(chunk_shape=(2,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((2,), slice(200, 300)) + + store = MemoryStore() + await store.set("shard", Buffer.from_bytes(b"x" * 300)) + store_mock = AsyncMock(wraps=store, spec=store.__class__) + byte_getter = StorePath(store_mock, "shard") + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (2,)}, + max_gap_bytes=12345, + max_coalesced_bytes=67890, + ) + + store_mock.get_ranges.assert_called_once() + kwargs = store_mock.get_ranges.call_args.kwargs + assert kwargs["max_gap_bytes"] == 12345 + assert kwargs["max_coalesced_bytes"] == 67890 + + +# ============================================================================ +# Bulk full-shard decode: identity-read gating and dtype gating +# ============================================================================ + +_FUSED_PIPELINE = "zarr.core.codec_pipeline.FusedCodecPipeline" + + +def _fused_uncompressed_array( + index_location: Literal["start", "end"], +) -> tuple[Any, npt.NDArray[np.int32]]: + """Sharded `(8, 8)` array whose inner chain is a bare BytesCodec (no crc), + one shard covering the whole array, filled with `arange` data. Callers must + be inside a config context selecting the fused pipeline.""" + shards: ShardsConfigParam = {"shape": (8, 8), "index_location": index_location} + arr = zarr.create_array( + store=MemoryStore(), + shape=(8, 8), + chunks=(2, 2), + shards=shards, + dtype="int32", + compressors=None, + filters=None, + fill_value=0, + config={"write_empty_chunks": True}, + ) + ref = np.arange(64, dtype="int32").reshape(8, 8) + arr[:] = ref + return arr, ref + + +def _spy_on_bulk_decode(monkeypatch: pytest.MonkeyPatch) -> list[bool]: + """Record, per call, whether `_decode_full_shard_bulk_if_uncompressed` + engaged (returned non-None).""" + engaged: list[bool] = [] + orig = ShardingCodec._decode_full_shard_bulk_if_uncompressed + + def spy(self: ShardingCodec, shard_bytes: Any, shard_spec: Any, indexer: Any) -> Any: + result = orig(self, shard_bytes, shard_spec, indexer) + engaged.append(result is not None) + return result + + monkeypatch.setattr(ShardingCodec, "_decode_full_shard_bulk_if_uncompressed", spy) + return engaged + + +_PERM_8 = np.array([7, 2, 5, 0, 3, 6, 1, 4]) +_DUP_8 = np.array([0, 0, 1, 2, 3, 4, 5, 6]) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize( + ("read", "expected", "expect_bulk"), + [ + pytest.param(lambda a: a[:], lambda r: r, True, id="full-slice"), + pytest.param(lambda a: a[...], lambda r: r, True, id="ellipsis"), + pytest.param( + lambda a: a[_PERM_8, :], lambda r: r[_PERM_8, :], False, id="fancy-permutation" + ), + pytest.param(lambda a: a[_DUP_8, :], lambda r: r[_DUP_8, :], False, id="fancy-duplicates"), + pytest.param( + lambda a: a.oindex[_PERM_8, :], + lambda r: r[_PERM_8, :], + False, + id="oindex-permutation", + ), + pytest.param( + lambda a: a.oindex[_DUP_8, :], lambda r: r[_DUP_8, :], False, id="oindex-duplicates" + ), + pytest.param(lambda a: a[1:7, :], lambda r: r[1:7, :], False, id="subset-slice"), + ], +) +def test_bulk_decode_engagement_and_correctness( + monkeypatch: pytest.MonkeyPatch, + index_location: Literal["start", "end"], + read: Any, + expected: Any, + expect_bulk: bool, +) -> None: + """Under the fused pipeline on an uncompressed crc-free shard, the bulk + whole-shard decode fires exactly for identity full reads — and every read + returns what numpy returns. The engagement assertions keep the correctness + half non-vacuous: a gate that simply disabled the fast path would pass the + value checks but fail here.""" + engaged = _spy_on_bulk_decode(monkeypatch) + with config.set({"codec_pipeline.path": _FUSED_PIPELINE}): + arr, ref = _fused_uncompressed_array(index_location) + engaged.clear() + np.testing.assert_array_equal(read(arr), expected(ref)) + if expect_bulk: + assert len(engaged) > 0, "bulk fast path was never reached for a full read" + assert all(engaged), "bulk fast path did not engage for a full read" + else: + assert not any(engaged), "bulk fast path engaged for a non-identity selection" + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +def test_multi_shard_permutation_read(index_location: Literal["start", "end"]) -> None: + """A row permutation crossing shard boundaries must return permuted data + under the fused pipeline (each shard sees a gather selection whose shape + coincides with the shard shape).""" + shards: ShardsConfigParam = {"shape": (8, 8), "index_location": index_location} + with config.set({"codec_pipeline.path": _FUSED_PIPELINE}): + arr = zarr.create_array( + store=MemoryStore(), + shape=(16, 16), + chunks=(2, 2), + shards=shards, + dtype="int32", + compressors=None, + filters=None, + fill_value=0, + config={"write_empty_chunks": True}, + ) + ref = np.arange(256, dtype="int32").reshape(16, 16) + arr[:] = ref + perm = np.array([9, 3, 12, 0, 15, 6, 10, 1, 14, 5, 8, 2, 13, 7, 11, 4]) + np.testing.assert_array_equal(arr[perm, :8], ref[perm, :8]) + np.testing.assert_array_equal(arr.oindex[perm, :8], ref[perm, :8]) + + +def _dense_shard_blob( + codec: ShardingCodec, data: np.ndarray[Any, np.dtype[Any]], chunk_len: int +) -> Buffer: + """Hand-assemble a dense `index_location="end"` shard blob for 1-D `data`: + natural-order chunk payloads followed by the encoded index.""" + n_chunks = data.shape[0] // chunk_len + chunk_nbytes = chunk_len * data.dtype.itemsize + index = _ShardIndex.create_empty((n_chunks,)) + for i in range(n_chunks): + index.set_chunk_slice((i,), slice(i * chunk_nbytes, (i + 1) * chunk_nbytes)) + index_bytes = codec._encode_shard_index_sync(index) + return Buffer.from_bytes(data.tobytes() + index_bytes.to_bytes()) + + +def _identity_indexer(shape: tuple[int, ...], chunk_shape: tuple[int, ...]) -> BasicIndexer: + return BasicIndexer( + tuple(slice(0, s) for s in shape), + shape=shape, + chunk_grid=ChunkGrid.from_sizes(shape, chunk_shape), + ) + + +def _spec_for(data: np.ndarray[Any, np.dtype[Any]]) -> ArraySpec: + zdt = get_data_type_from_native_dtype(data.dtype) + return ArraySpec( + shape=data.shape, + dtype=zdt, + fill_value=zdt.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + +def test_bulk_decode_declines_structured_dtype() -> None: + """The bulk path has no structured-dtype byte-order handling (the `Struct` + branch of `BytesCodec._decode_sync`), so it must decline structured specs. + The plain-dtype control on an identically constructed blob proves the + decline comes from the dtype gate, not from a malformed blob.""" + codec = ShardingCodec(chunk_shape=(2,), codecs=[BytesCodec(endian="little")]) + + # control: same construction with a plain dtype engages the bulk path + plain = np.arange(4, dtype=" None: + """`is_dense` accepts every layout whose fixed-size payloads exactly tile + the data section, wherever that section starts and in whatever order the + chunks were laid out.""" + chunk_len = 24 + n = int(np.prod(chunks_per_shard)) + slots = np.arange(n) + if layout_order == "reversed": + slots = slots[::-1] + offsets = data_section_start + slots * chunk_len + index = _ShardIndex.create_empty(chunks_per_shard) + for coord, off in zip(np.ndindex(chunks_per_shard), offsets, strict=True): + index.set_chunk_slice(tuple(coord), slice(int(off), int(off) + chunk_len)) + assert index.is_dense(chunk_len, data_section_start=data_section_start) is True + + +def test_shard_index_is_dense_rejects_overlapping_offsets() -> None: + """Unique but overlapping offsets (second payload starts inside the first) + are not dense.""" + chunk_len = 24 + index = _ShardIndex.create_empty((2,)) + index.set_chunk_slice((0,), slice(0, chunk_len)) + index.set_chunk_slice((1,), slice(12, 12 + chunk_len)) + assert index.is_dense(chunk_len, data_section_start=0) is False + + +def test_shard_index_is_dense_rejects_out_of_range_offsets() -> None: + """An offset outside the data section (here: chunk 0 pointing into an + `index_location="start"` index region) is not dense, even though offsets + are unique and non-overlapping.""" + chunk_len = 24 + data_section_start = 16 + index = _ShardIndex.create_empty((2,)) + index.set_chunk_slice((0,), slice(0, chunk_len)) + index.set_chunk_slice( + (1,), slice(data_section_start + chunk_len, data_section_start + 2 * chunk_len) + ) + assert index.is_dense(chunk_len, data_section_start=data_section_start) is False diff --git a/tests/test_codecs/test_vlen.py b/tests/test_codecs/test_vlen.py index f3445824b3..b90ad88ddc 100644 --- a/tests/test_codecs/test_vlen.py +++ b/tests/test_codecs/test_vlen.py @@ -10,17 +10,21 @@ from zarr.codecs import ZstdCodec from zarr.codecs.vlen_utf8 import VLenBytesCodec, VLenUTF8Codec from zarr.core.dtype import get_data_type_from_native_dtype -from zarr.core.dtype.npy.string import _NUMPY_SUPPORTS_VLEN_STRING from zarr.core.metadata.v3 import ArrayV3Metadata from zarr.storage import StorePath -numpy_str_dtypes: list[type | str | None] = [None, str, "str", np.dtypes.StrDType, "S", "U"] -expected_array_string_dtype: np.dtype[Any] -if _NUMPY_SUPPORTS_VLEN_STRING: - numpy_str_dtypes.append(np.dtypes.StringDType) - expected_array_string_dtype = np.dtypes.StringDType() -else: - expected_array_string_dtype = np.dtype("O") +# The explicit id for the "str" literal avoids colliding with the auto-generated id for +# the `str` builtin. +numpy_str_dtypes: list[Any] = [ + None, + str, + pytest.param("str", id="str-literal"), + np.dtypes.StrDType, + "S", + "U", + np.dtypes.StringDType, +] +expected_array_string_dtype: np.dtype[Any] = np.dtypes.StringDType() @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") @@ -65,6 +69,34 @@ def test_vlen_string( assert a.dtype == data.dtype +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize( + ("dtype", "fill_value", "elements"), + [ + pytest.param("string", "", [f"S{i:05}" for i in range(9)], id="string"), + pytest.param("variable_length_bytes", b"", [b"%05d" % i for i in range(9)], id="bytes"), + ], +) +def test_vlen_f_contiguous( + store: Store, dtype: str, fill_value: str | bytes, elements: list[str] | list[bytes] +) -> None: + """An F-contiguous chunk written through a vlen codec round-trips in the original + element order rather than the transposed memory order (gh-3558).""" + # reshape(order="F") gives an F-contiguous view directly, so the whole-array write + # below hands an F-contiguous chunk to the codec; assert it to guard the precondition. + data = np.array(elements, dtype=object).reshape((3, 3), order="F") + assert data.flags.f_contiguous + sp = StorePath(store, path="vlen-f-contiguous") + # chunks == shape so the write is a single complete chunk, which the codec pipeline + # forwards to the codec untouched; a partial-chunk layout would be recopied to C order. + a = zarr.create_array( + sp, shape=data.shape, chunks=data.shape, dtype=dtype, fill_value=fill_value + ) + a[:, :] = data + assert np.array_equal(data, np.asarray(a[:, :], dtype=object)) + + def test_vlen_utf8_codec_supports_sync() -> None: assert isinstance(VLenUTF8Codec(), SupportsSyncCodec) diff --git a/tests/test_common.py b/tests/test_common.py index 0dedde1d6b..846dcbbad9 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio from collections.abc import Iterable from typing import TYPE_CHECKING, get_args @@ -9,7 +10,11 @@ from zarr.core.common import ( ANY_ACCESS_MODE, AccessModeLiteral, + concurrent_iter, + parse_bool, + parse_int, parse_name, + parse_order, parse_shapelike, product, ) @@ -31,6 +36,32 @@ def test_access_modes() -> None: assert set(ANY_ACCESS_MODE) == set(get_args(AccessModeLiteral)) +async def test_concurrent_iter_schedules_eagerly() -> None: + """`concurrent_iter` must return already-scheduled tasks, not a lazy generator. + + Its docstring promises `func(*item)` is launched concurrently for every + item up front; a caller that awaits the returned tasks one at a time + (rather than via `gather`/`as_completed`, which force iteration) relies + on that eager scheduling to get any overlap at all. + """ + started = [False, False, False] + + async def mark(i: int) -> int: + started[i] = True + return i + + tasks = concurrent_iter([(0,), (1,), (2,)], mark) + + # Give the event loop one chance to run before awaiting anything + # individually. If `concurrent_iter` were lazy, nothing would have been + # scheduled yet and `started` would still be all-False here. + await asyncio.sleep(0) + assert started == [True, True, True] + + results = [await t for t in tasks] + assert results == [0, 1, 2] + + # todo: test def test_concurrent_map() -> None: ... @@ -68,10 +99,40 @@ def test_parse_name_valid(data: tuple[Any, Any]) -> None: @pytest.mark.parametrize("data", [0, 1, "hello", "f"]) def test_parse_indexing_order_invalid(data: Any) -> None: - with pytest.raises(ValueError, match="Expected one of"): + with pytest.raises(ValueError, match="Failed to parse input for 'order'"): parse_indexing_order(data) +@pytest.mark.parametrize("data", [0, 1, "hello", "f"]) +def test_parse_order_invalid(data: Any) -> None: + with pytest.raises(ValueError, match="Failed to parse input for 'order'"): + parse_order(data) + + +@pytest.mark.parametrize("data", [0, 1, "true", None, [True]]) +def test_parse_bool_invalid(data: Any) -> None: + """Non-bool values are rejected with a ValueError.""" + with pytest.raises(ValueError, match="Expected instance of bool"): + parse_bool(data) + + +@pytest.mark.parametrize("data", [True, False]) +def test_parse_bool_valid(data: bool) -> None: + assert parse_bool(data) is data + + +@pytest.mark.parametrize("data", ["1", 1.0, True, False, None, [1], (1,)]) +def test_parse_int_invalid(data: Any) -> None: + """Non-int values (including bools, which are int subclasses) are rejected.""" + with pytest.raises(ValueError, match="Expected int"): + parse_int(data) + + +@pytest.mark.parametrize("data", [0, 1, -1, 2**63]) +def test_parse_int_valid(data: int) -> None: + assert parse_int(data) == data + + @pytest.mark.parametrize("data", ["C", "F"]) def parse_indexing_order_valid(data: Literal["C", "F"]) -> None: assert parse_indexing_order(data) == data diff --git a/tests/test_config.py b/tests/test_config.py index c3102e8efe..47f71a798e 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,3 +1,4 @@ +import inspect import os from collections.abc import Iterable from typing import Any @@ -17,13 +18,13 @@ Crc32cCodec, ShardingCodec, ) -from zarr.core.array_spec import ArraySpec +from zarr.core.array_spec import ArrayConfig, ArraySpec from zarr.core.buffer import NDBuffer from zarr.core.buffer.core import Buffer from zarr.core.codec_pipeline import BatchedCodecPipeline from zarr.core.config import BadConfigError, config from zarr.core.indexing import SelectorTuple -from zarr.errors import ZarrUserWarning +from zarr.errors import ChunkNotFoundError, ZarrUserWarning from zarr.registry import ( fully_qualified_name, get_buffer_class, @@ -53,7 +54,11 @@ def test_config_defaults_set() -> None: "array": { "order": "C", "write_empty_chunks": False, + "read_missing_chunks": True, "target_shard_size_bytes": None, + "rectilinear_chunks": False, + "sharding_coalesce_max_gap_bytes": 1 << 20, + "sharding_coalesce_max_bytes": 16 << 20, }, "async": {"concurrency": 10, "timeout": None}, "threading": {"max_workers": None}, @@ -61,6 +66,7 @@ def test_config_defaults_set() -> None: "codec_pipeline": { "path": "zarr.core.codec_pipeline.BatchedCodecPipeline", "batch_size": 1, + "max_workers": None, }, "codecs": { "blosc": "zarr.codecs.blosc.BloscCodec", @@ -107,6 +113,25 @@ def test_config_defaults_set() -> None: assert config.get("json_indent") == 2 +def test_array_config_init_defaults_match_global_config() -> None: + """Each `ArrayConfig.__init__` parameter that has a default must match the + value of `array.` in the global config. Catches drift between + the two sources of truth.""" + params = inspect.signature(ArrayConfig.__init__).parameters + has_defaults = { + name: p.default + for name, p in params.items() + if name != "self" and p.default is not inspect.Parameter.empty + } + assert has_defaults, "expected at least one default to check" + for name, default in has_defaults.items(): + assert default == config.get(f"array.{name}"), ( + f"ArrayConfig.__init__ default for {name!r} ({default!r}) does not " + f"match global config value for 'array.{name}' " + f"({config.get(f'array.{name}')!r})" + ) + + @pytest.mark.parametrize( ("key", "old_val", "new_val"), [("array.order", "C", "F"), ("async.concurrency", 10, 128), ("json_indent", 2, 0)], @@ -132,7 +157,7 @@ def test_config_codec_pipeline_class(store: Store) -> None: # has default value assert get_pipeline_class().__name__ != "" - config.set({"codec_pipeline.name": "zarr.core.codec_pipeline.BatchedCodecPipeline"}) + config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"}) assert get_pipeline_class() == zarr.core.codec_pipeline.BatchedCodecPipeline _mock = Mock() @@ -187,10 +212,19 @@ def test_config_codec_implementation(store: Store) -> None: _mock = Mock() class MockBloscCodec(BloscCodec): + # Record a call from whichever encode entry point the active codec + # pipeline uses: the async `_encode_single` (BatchedCodecPipeline, the + # default) or the synchronous `_encode_sync` (FusedCodecPipeline). + # Overriding both keeps this test ("the configured codec is actually + # used") independent of which pipeline is the default. async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: _mock.call() return None + def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: + _mock.call() + return None + register_codec("blosc", MockBloscCodec) with config.set({"codecs.blosc": fully_qualified_name(MockBloscCodec)}): assert get_codec_class("blosc") == MockBloscCodec @@ -319,6 +353,108 @@ class NewCodec2(BytesCodec): get_codec_class("new_codec") +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize( + "kwargs", + [ + {"shards": (4, 4)}, + {"compressors": None}, + ], + ids=["partial_decode", "full_decode"], +) +def test_config_read_missing_chunks(store: Store, kwargs: dict[str, Any]) -> None: + arr = zarr.create_array( + store=store, + shape=(4, 4), + chunks=(2, 2), + dtype="int32", + fill_value=42, + **kwargs, + ) + + # default behavior: missing chunks are filled with the fill value + result = zarr.open_array(store)[:] + assert np.array_equal(result, np.full((4, 4), 42, dtype="int32")) + + # with read_missing_chunks=False, reading missing chunks raises an error + with config.set({"array.read_missing_chunks": False}): + with pytest.raises(ChunkNotFoundError): + zarr.open_array(store)[:] + + # after writing data, all chunks exist and no error is raised + arr[:] = np.arange(16, dtype="int32").reshape(4, 4) + with config.set({"array.read_missing_chunks": False}): + result = zarr.open_array(store)[:] + assert np.array_equal(result, np.arange(16, dtype="int32").reshape(4, 4)) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_config_read_missing_chunks_sharded_inner(store: Store) -> None: + """Because the shard index and inner chunks should be stored + together in a single storage object (read: a file or blob), + we delegate to the shard index the responsibility of determining + what chunks should be present. + + Thus, `read_missing_chunks` raises an error only if the entire *shard* + is missing. Missing inner chunks are filled with the array's fill value + and do not raise an error, even if `read_missing_chunks=False` at the + array level. + """ + arr = zarr.create_array( + store=store, + shape=(8, 4), + chunks=(2, 2), + shards=(4, 4), + dtype="int32", + fill_value=42, + ) + + # write only one inner chunk in the first shard, leaving the second shard empty + arr[0:2, 0:2] = np.ones((2, 2), dtype="int32") + + with config.set({"array.read_missing_chunks": False}): + a = zarr.open_array(store) + + # first shard exists: missing inner chunks are filled, no error + result = a[:4] + expected = np.full((4, 4), 42, dtype="int32") + expected[0:2, 0:2] = 1 + assert np.array_equal(result, expected) + + # second shard is entirely missing: raises an error + with pytest.raises(ChunkNotFoundError): + a[4:] + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_config_read_missing_chunks_write_empty_chunks(store: Store) -> None: + """write_empty_chunks=False drops chunks equal to fill_value, which then + appear missing to read_missing_chunks=False.""" + arr = zarr.create_array( + store=store, + shape=(4,), + chunks=(2,), + dtype="int32", + fill_value=0, + config={"write_empty_chunks": False, "read_missing_chunks": False}, + ) + + # write non-fill-value data: chunks are stored + arr[:] = [1, 2, 3, 4] + assert np.array_equal(arr[:], [1, 2, 3, 4]) + + # overwrite with fill_value: chunks are dropped by write_empty_chunks=False + arr[:] = 0 + with pytest.raises(ChunkNotFoundError): + arr[:] + + # with write_empty_chunks=True, chunks are kept and no error is raised + with config.set({"array.write_empty_chunks": True}): + arr = zarr.open_array(store) + arr[:] = 0 + assert np.array_equal(arr[:], [0, 0, 0, 0]) + + @pytest.mark.parametrize( "key", [ diff --git a/tests/test_docs.py b/tests/test_docs.py index d467e478e8..0ed429f173 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -1,95 +1,237 @@ """ Tests for executable code blocks in markdown documentation. -This module uses pytest-examples to validate that all Python code examples -with exec="true" in the documentation execute successfully. +This module uses pytest-examples to validate Python code examples in the docs. A block is +validated if it renders output at build (exec="true") or is explicitly marked for testing +(test="true"). The two flags are separate on purpose: exec= drives markdown-exec's +build-time rendering, while test= lets a block be validated without being run at build +(e.g. gpu/s3 examples the build environment cannot run). The test_no_unvalidated_blocks +guard ensures every python block declares one of those, or an explicit exec="false" opt-out +with a reason, so a block can never silently skip validation. """ from __future__ import annotations from collections import defaultdict from pathlib import Path +from typing import TYPE_CHECKING, Any import pytest pytest.importorskip("pytest_examples") from pytest_examples import CodeExample, EvalExample, find_examples -# Find all markdown files with executable code blocks +if TYPE_CHECKING: + from collections.abc import Generator + DOCS_ROOT = Path(__file__).parent.parent / "docs" SOURCES_ROOT = Path(__file__).parent.parent / "src" / "zarr" -def find_markdown_files_with_exec() -> list[Path]: - """Find all markdown files containing exec="true" code blocks.""" - markdown_files = [] +def name_example(path: str, session: str) -> str: + """Generate a readable name for a test case from file path and session.""" + file = Path(path) + try: + file = file.relative_to(DOCS_ROOT) + except ValueError: + # Path is outside DOCS_ROOT (e.g. a tmp_path fixture in unit tests); use the + # bare file name rather than an absolute path for a stable, readable id. + file = Path(file.name) + return f"{file}:{session}" + + +def _marker_names(settings: dict[str, str]) -> list[str]: + """Parse a block's markers="a b" attribute into a list of marker names.""" + return [name for name in settings.get("markers", "").split() if name] + + +def _is_tested(settings: dict[str, str]) -> bool: + """A block is validated by our pytest harness if it is run at build to render output + (exec="true") OR explicitly marked for testing (test="true"). The two flags are + separate on purpose: exec= drives markdown-exec's build-time rendering, while test= + lets a block be validated without being run at build (e.g. gpu/s3 blocks, which the + build environment cannot run).""" + return settings.get("exec") == "true" or settings.get("test") == "true" + - for md_file in DOCS_ROOT.rglob("*.md"): - try: - content = md_file.read_text(encoding="utf-8") - if 'exec="true"' in content: - markdown_files.append(md_file) - except Exception: - # Skip files that can't be read +def _session_params(root: Path) -> list[Any]: + """Group tested examples (exec="true" or test="true") by (file, session) and emit one + pytest.param per session, carrying the union of markers declared by that session's + blocks.""" + sessions: defaultdict[tuple[str, str], list[CodeExample]] = defaultdict(list) + marks_by_session: defaultdict[tuple[str, str], set[str]] = defaultdict(set) + + for example in find_examples(str(root)): + settings = example.prefix_settings() + if not _is_tested(settings): continue + session_name = settings.get("session", "_default") + key = (str(example.path), session_name) + sessions[key].append(example) + marks_by_session[key].update(_marker_names(settings)) - return sorted(markdown_files) + params = [] + for key in sorted(sessions.keys(), key=lambda x: (x[0], x[1])): + marks = tuple(getattr(pytest.mark, name) for name in sorted(marks_by_session[key])) + params.append(pytest.param(key, marks=marks, id=name_example(key[0], key[1]))) + return params -def group_examples_by_session() -> list[tuple[str, str]]: - """ - Group examples by their session and file, maintaining order. +S3_BUCKET = "example-bucket" - Returns a list of session_key tuples where session_key is - (file_path, session_name). - """ - all_examples = list(find_examples(DOCS_ROOT)) - # Group by file and session - sessions = defaultdict(list) +@pytest.fixture +def docs_s3_backend( + moto_server: str, monkeypatch: pytest.MonkeyPatch +) -> Generator[None, None, None]: + """Point docs S3 examples at the shared moto server (tests/conftest.py) via a + process-wide AWS_ENDPOINT_URL, so a block can use a bare s3:// URL with no + storage_options (see spike in the design notes). The server lifecycle belongs to the + session-scoped `moto_server` fixture; this fixture only adds the docs-specific + endpoint env var and a fresh bucket, and restores both on teardown.""" + s3fs = pytest.importorskip("s3fs") + botocore = pytest.importorskip("botocore") + requests = pytest.importorskip("requests") - for example in all_examples: + monkeypatch.setenv("AWS_ENDPOINT_URL", moto_server) + + session = botocore.session.Session() + client = session.create_client("s3", endpoint_url=moto_server, region_name="us-east-1") + client.create_bucket(Bucket=S3_BUCKET) + client.close() + s3fs.S3FileSystem.clear_instance_cache() + try: + yield + finally: + # Reset moto state; AWS_ENDPOINT_URL is restored automatically by monkeypatch. + # The shared server keeps running (the moto_server fixture stops it at session end). + requests.post(f"{moto_server}moto-api/reset") + + +def test_markers_attribute_is_parsed(tmp_path: Path) -> None: + """A test="true" block tagged markers="s3" must surface that marker on its + parametrized case, so pytest can gate/bind it (e.g. attach the moto fixture). + Uses test="true" (not exec="true") because marker-bound blocks are validated by the + harness without being run at build time.""" + md = tmp_path / "ex.md" + md.write_text( + '```python test="true" session="demo" markers="s3"\nimport zarr\n```\n', + encoding="utf-8", + ) + params = _session_params(md.parent) + assert len(params) == 1 + marks = params[0].marks + assert any(m.name == "s3" for m in marks) + + +def test_no_unvalidated_blocks() -> None: + """Every python code block in docs/ must declare its validation state: exec="true" + (run at build to render output), test="true" (validated by this harness without being + run at build), or exec="false" with a reason (explicit, documented opt-out). A bare or + mistyped fence (e.g. exec="on") fails here, so a block can never silently opt out of + validation -- the gap that hid the invalid create_array(mode="w") example in #4016. + + A separate placement constraint is enforced by test_test_only_blocks_come_last.""" + offenders: list[str] = [] + for example in find_examples(str(DOCS_ROOT)): + rel = Path(example.path).relative_to(DOCS_ROOT) settings = example.prefix_settings() - if settings.get("exec") != "true": + exec_val = settings.get("exec") + loc = f"{rel}:{example.start_line}" + # Validated either by build-render (exec="true") or by the test harness + # (test="true"). + if _is_tested(settings): continue + # Explicit, documented opt-out from execution. + if exec_val == "false" and settings.get("reason", "").strip(): + continue + offenders.append( + f"{loc} (exec={exec_val!r}, test={settings.get('test')!r}, " + f"reason={settings.get('reason')!r})" + ) - # Use file path and session name as key - file_path = example.path - session_name = settings.get("session", "_default") - session_key = (str(file_path), session_name) + assert not offenders, ( + 'Docs python blocks must be exec="true", test="true", or exec="false" with a ' + "reason:\n" + "\n".join(offenders) + ) - sessions[session_key].append(example) - # Return sorted list of session keys for consistent test ordering - return sorted(sessions.keys(), key=lambda x: (x[0], x[1])) +def test_test_only_blocks_come_last() -> None: + """A conservative placement convention: a test="true"-only block must come after every + exec="true" block in the same file. + Mechanism (established by experiment + markdown-exec's SuperFences integration): a + python fence that markdown-exec does not execute -- i.e. one lacking exec="true", + whether test="true" or exec="false" -- placed before an exec="true" block disrupts + markdown-exec's build-time execution of a *later, state-dependent* block. Observed: a + non-exec python fence inserted before the quickstart ZipStore write/read pair made the + read block fail with FileNotFoundError (the write never took effect), aborting + `mkdocs build --strict`. The effect needs a cross-block dependency to surface, so it + does not affect the standalone exec="true" blocks in e.g. data_types.md/performance.md + that already have exec="false" opt-out blocks above them. -def name_example(path: str, session: str) -> str: - """Generate a readable name for a test case from file path and session.""" - return f"{Path(path).relative_to(DOCS_ROOT)}:{session}" + Because we cannot statically tell which later blocks are state-dependent, this guard + enforces the simple, safe convention only for the blocks we author this way + (test="true" marker-bound examples like s3/gpu). It is NOT a complete build-hazard + check -- the authoritative check is `mkdocs build --strict` (the docs:check CI job), + which catches the exec="false" case too. This guard just turns the common test-only + case into a fast, local failure.""" + # Collect, per published-docs file, the start lines of test-only and exec blocks. + test_only: defaultdict[str, list[int]] = defaultdict(list) + exec_lines: defaultdict[str, list[int]] = defaultdict(list) + for example in find_examples(str(DOCS_ROOT)): + settings = example.prefix_settings() + path = str(example.path) + if settings.get("exec") == "true": + exec_lines[path].append(example.start_line) + elif settings.get("test") == "true": + test_only[path].append(example.start_line) + + offenders: list[str] = [] + for path, only_lines in test_only.items(): + rel = Path(path).relative_to(DOCS_ROOT) + last_exec = max(exec_lines.get(path, [0])) + offenders.extend( + f'{rel}:{line} (test="true" block precedes an exec="true" block at line {last_exec})' + for line in only_lines + if line < last_exec + ) + + assert not offenders, ( + 'A test="true"-only block must come after every exec="true" block in the same ' + 'file: a non-executed python fence before an exec="true" block can disrupt ' + "markdown-exec's build-time execution of a later state-dependent block (see this " + "test's docstring):\n" + "\n".join(offenders) + ) # Get all example sessions -@pytest.mark.parametrize( - "session_key", group_examples_by_session(), ids=lambda v: name_example(v[0], v[1]) -) +@pytest.mark.parametrize("session_key", _session_params(DOCS_ROOT)) def test_documentation_examples( session_key: tuple[str, str], eval_example: EvalExample, + request: pytest.FixtureRequest, ) -> None: """ - Test that all exec="true" code examples in documentation execute successfully. + Test that all validated code examples (exec="true" or test="true") in documentation + execute successfully. This test groups examples by session (file + session name) and runs them sequentially in the same execution context, allowing code to build on previous examples. This test uses pytest-examples to: - - Find all code examples with exec="true" in markdown files + - Find all code examples marked exec="true" or test="true" in markdown files - Group them by session - Execute them in order within the same context - Verify no exceptions are raised """ + if request.node.get_closest_marker("gpu") is not None: + pytest.importorskip("cupy") + + if request.node.get_closest_marker("s3") is not None: + request.getfixturevalue("docs_s3_backend") + file_path, session_name = session_key # Get examples for this session @@ -97,7 +239,7 @@ def test_documentation_examples( examples = [] for example in all_examples: settings = example.prefix_settings() - if settings.get("exec") != "true": + if not _is_tested(settings): continue if str(example.path) == file_path and settings.get("session", "_default") == session_name: examples.append(example) @@ -112,7 +254,7 @@ def test_documentation_examples( module_globals.update(result) -@pytest.mark.parametrize("example", find_examples(str(SOURCES_ROOT)), ids=str) +@pytest.mark.parametrize("example", list(find_examples(str(SOURCES_ROOT))), ids=str) def test_docstrings(example: CodeExample, eval_example: EvalExample) -> None: """Test our docstring examples.""" if example.path.name == "config.py" and "your.module" in example.source: diff --git a/tests/test_dtype/conftest.py b/tests/test_dtype/conftest.py index 0650d143c6..100b9df226 100644 --- a/tests/test_dtype/conftest.py +++ b/tests/test_dtype/conftest.py @@ -1,19 +1,19 @@ # Generate a collection of zdtype instances for use in testing. import warnings +from collections import Counter from typing import Any import numpy as np from zarr.core.dtype import data_type_registry from zarr.core.dtype.common import HasLength -from zarr.core.dtype.npy.structured import Structured +from zarr.core.dtype.npy.structured import Struct from zarr.core.dtype.npy.time import DateTime64, TimeDelta64 from zarr.core.dtype.wrapper import ZDType zdtype_examples: tuple[ZDType[Any, Any], ...] = () for wrapper_cls in data_type_registry.contents.values(): - # The Structured dtype has to be constructed with some actual fields - if wrapper_cls is Structured: + if wrapper_cls is Struct: with warnings.catch_warnings(): warnings.simplefilter("ignore") zdtype_examples += ( @@ -65,4 +65,19 @@ class TestB(TestExample): for fixture_name in metafunc.fixturenames: if hasattr(metafunc.cls, fixture_name): params = getattr(metafunc.cls, fixture_name) - metafunc.parametrize(fixture_name, params, scope="class", ids=str) + metafunc.parametrize( + fixture_name, params, scope="class", ids=_unique_ids([str(p) for p in params]) + ) + + +def _unique_ids(ids: list[str]) -> list[str]: + """Suffix repeated ids with their positional index so every id is unique. + + Distinct parameters can stringify identically: for example `np.dtype("i")` and + `np.dtype(" 1 else id_ for idx, id_ in enumerate(ids)] diff --git a/tests/test_dtype/test_npy/test_common.py b/tests/test_dtype/test_npy/test_common.py index d8912a70ec..b7e4e875ad 100644 --- a/tests/test_dtype/test_npy/test_common.py +++ b/tests/test_dtype/test_npy/test_common.py @@ -36,14 +36,17 @@ from zarr.core.common import JSON, ZarrFormat -json_float_v2_roundtrip_cases: tuple[tuple[JSONFloatV2, float | np.floating[Any]], ...] = ( - ("Infinity", float("inf")), - ("Infinity", np.inf), - ("-Infinity", float("-inf")), - ("-Infinity", -np.inf), - ("NaN", float("nan")), - ("NaN", np.nan), - (1.0, 1.0), +# Each special value is tested as both a Python float and a numpy scalar. The explicit +# ids are load-bearing: np.float64("inf") stringifies identically to float("inf"), so +# without them these parameter sets would produce duplicate test ids. +json_float_v2_roundtrip_cases: tuple[Any, ...] = ( + pytest.param("Infinity", float("inf"), id="Infinity-float"), + pytest.param("Infinity", np.float64("inf"), id="Infinity-float64"), + pytest.param("-Infinity", float("-inf"), id="-Infinity-float"), + pytest.param("-Infinity", np.float64("-inf"), id="-Infinity-float64"), + pytest.param("NaN", float("nan"), id="NaN-float"), + pytest.param("NaN", np.float64("nan"), id="NaN-float64"), + pytest.param(1.0, 1.0, id="1.0-1.0"), ) json_float_v3_cases = json_float_v2_roundtrip_cases diff --git a/tests/test_dtype/test_npy/test_int.py b/tests/test_dtype/test_npy/test_int.py index f53ec7f5ae..9eab053080 100644 --- a/tests/test_dtype/test_npy/test_int.py +++ b/tests/test_dtype/test_npy/test_int.py @@ -216,7 +216,16 @@ class TestUInt16(BaseTestZDType): class TestUInt32(BaseTestZDType): test_cls = UInt32 scalar_type = np.uint32 - valid_dtype = (np.dtype(">u4"), np.dtype("u4"), np.dtype(" None: - """ - Test that we get a warning when serializing a dtype without a zarr v3 spec to json - when zarr_format is 3 - """ - with pytest.warns(UnstableSpecificationWarning): - zdtype.to_json(zarr_format=3) - - def test_invalid_size() -> None: """ Test that it's impossible to create a data type that has no length diff --git a/tests/test_dtype/test_npy/test_structured.py b/tests/test_dtype/test_npy/test_structured.py index e2cd2a6dfe..554c3b4e41 100644 --- a/tests/test_dtype/test_npy/test_structured.py +++ b/tests/test_dtype/test_npy/test_structured.py @@ -11,12 +11,16 @@ Float64, Int32, Int64, + Struct, Structured, + UInt8, ) -class TestStructured(BaseTestZDType): - test_cls = Structured +class TestStruct(BaseTestZDType): + """Test the canonical 'struct' dtype format.""" + + test_cls = Struct valid_dtype = ( np.dtype([("field1", np.int32), ("field2", np.float64)]), np.dtype([("field1", np.int64), ("field2", np.int32)]), @@ -32,29 +36,32 @@ class TestStructured(BaseTestZDType): ) valid_json_v3 = ( { - "name": "structured", + "name": "struct", "configuration": { "fields": [ - ["field1", "int32"], - ["field2", "float64"], + {"name": "field1", "data_type": "int32"}, + {"name": "field2", "data_type": "float64"}, ] }, }, { - "name": "structured", + "name": "struct", "configuration": { "fields": [ - [ - "field1", - { + { + "name": "field1", + "data_type": { "name": "numpy.datetime64", "configuration": {"unit": "s", "scale_factor": 1}, }, - ], - [ - "field2", - {"name": "fixed_length_utf32", "configuration": {"length_bytes": 32}}, - ], + }, + { + "name": "field2", + "data_type": { + "name": "fixed_length_utf32", + "configuration": {"length_bytes": 32}, + }, + }, ] }, }, @@ -65,7 +72,7 @@ class TestStructured(BaseTestZDType): ) invalid_json_v3 = ( { - "name": "structured", + "name": "struct", "configuration": { "fields": [ ("field1", {"name": "int32", "configuration": {"endianness": "invalid"}}), @@ -77,35 +84,38 @@ class TestStructured(BaseTestZDType): ) scalar_v2_params = ( - (Structured(fields=(("field1", Int32()), ("field2", Float64()))), "AQAAAAAAAAAAAPA/"), - (Structured(fields=(("field1", Float16()), ("field2", Int32()))), "AQAAAAAA"), + (Struct(fields=(("field1", Int32()), ("field2", Float64()))), "AQAAAAAAAAAAAPA/"), + (Struct(fields=(("field1", Float16()), ("field2", Int32()))), "AQAAAAAA"), ) scalar_v3_params = ( - (Structured(fields=(("field1", Int32()), ("field2", Float64()))), "AQAAAAAAAAAAAPA/"), - (Structured(fields=(("field1", Int64()), ("field2", Int32()))), "AQAAAAAAAAAAAPA/"), + ( + Struct(fields=(("field1", Int32()), ("field2", Float64()))), + {"field1": 1, "field2": 1.0}, + ), + (Struct(fields=(("field1", Int64()), ("field2", Int32()))), {"field1": 1, "field2": 1}), ) cast_value_params = ( ( - Structured(fields=(("field1", Int32()), ("field2", Float64()))), + Struct(fields=(("field1", Int32()), ("field2", Float64()))), (1, 2.0), np.array((1, 2.0), dtype=[("field1", np.int32), ("field2", np.float64)]), ), ( - Structured(fields=(("field1", Int64()), ("field2", Int32()))), + Struct(fields=(("field1", Int64()), ("field2", Int32()))), (3, 4.5), np.array((3, 4.5), dtype=[("field1", np.int64), ("field2", np.int32)]), ), ) item_size_params = ( - Structured(fields=(("field1", Int32()), ("field2", Float64()))), - Structured(fields=(("field1", Int64()), ("field2", Int32()))), + Struct(fields=(("field1", Int32()), ("field2", Float64()))), + Struct(fields=(("field1", Int64()), ("field2", Int32()))), ) invalid_scalar_params = ( - (Structured(fields=(("field1", Int32()), ("field2", Float64()))), "i am a string"), - (Structured(fields=(("field1", Int32()), ("field2", Float64()))), {"type": "dict"}), + (Struct(fields=(("field1", Int32()), ("field2", Float64()))), "i am a string"), + (Struct(fields=(("field1", Int32()), ("field2", Float64()))), {"type": "dict"}), ) def scalar_equals(self, scalar1: Any, scalar2: Any) -> bool: @@ -114,11 +124,139 @@ def scalar_equals(self, scalar1: Any, scalar2: Any) -> bool: return super().scalar_equals(scalar1, scalar2) +class TestStructured: + """Test the legacy 'structured' dtype format.""" + + def test_invalid_size(self) -> None: + """Test that it's impossible to create a data type that has no fields.""" + fields = () + msg = f"must have at least one field. Got {fields!r}" + with pytest.raises(ValueError, match=msg): + Structured(fields=fields) + + def test_structured_legacy_name_with_tuple_format(self) -> None: + """Test that the legacy 'structured' name with tuple field format is accepted.""" + json_v3 = { + "name": "structured", + "configuration": { + "fields": [ + ["field1", "int32"], + ["field2", "float64"], + ] + }, + } + dtype = Structured.from_json(json_v3, zarr_format=3) + assert dtype.fields[0][0] == "field1" + assert dtype.fields[1][0] == "field2" + + @pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") + def test_structured_writes_tuple_format(self) -> None: + """Test that 'structured' writes the tuple field format.""" + dtype = Structured(fields=(("field1", Int32()), ("field2", Float64()))) + json_v3 = dtype.to_json(zarr_format=3) + assert json_v3["name"] == "structured" + assert json_v3["configuration"]["fields"][0] == ["field1", "int32"] + + def test_invalid_size() -> None: - """ - Test that it's impossible to create a data type that has no fields - """ + """Test that it's impossible to create a data type that has no fields.""" fields = () msg = f"must have at least one field. Got {fields!r}" with pytest.raises(ValueError, match=msg): - Structured(fields=fields) + Struct(fields=fields) + + +@pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") +def test_struct_name_is_primary() -> None: + """Test that 'struct' is the primary name written to JSON.""" + dtype = Struct(fields=(("field1", Int32()), ("field2", Float64()))) + json_v3 = dtype.to_json(zarr_format=3) + assert json_v3["name"] == "struct" + + +def test_struct_reads_legacy_tuple_format() -> None: + """Test that 'struct' dtype reads the legacy tuple field format.""" + json_v3 = { + "name": "struct", + "configuration": { + "fields": [ + ["field1", "int32"], + ["field2", "float64"], + ] + }, + } + dtype = Struct.from_json(json_v3, zarr_format=3) + assert isinstance(dtype, Struct) + assert dtype.fields[0][0] == "field1" + assert dtype.fields[1][0] == "field2" + + +def test_struct_reads_canonical_object_format() -> None: + """Test that 'struct' dtype reads the new object field format.""" + json_v3 = { + "name": "struct", + "configuration": { + "fields": [ + {"name": "field1", "data_type": "int32"}, + {"name": "field2", "data_type": "float64"}, + ] + }, + } + dtype = Struct.from_json(json_v3, zarr_format=3) + assert isinstance(dtype, Struct) + assert dtype.fields[0][0] == "field1" + assert dtype.fields[1][0] == "field2" + + +def test_fill_value_dict_form() -> None: + """Test that dict form fill values are properly parsed.""" + dtype = Struct(fields=(("x", Int32()), ("y", Float64()))) + fill_value = dtype.from_json_scalar({"x": 42, "y": 3.14}, zarr_format=3) + assert fill_value["x"] == 42 + assert fill_value["y"] == 3.14 + + +def test_fill_value_dict_form_missing_fields() -> None: + """Test that missing fields in dict form fill values use defaults.""" + dtype = Struct(fields=(("x", Int32()), ("y", Float64()))) + fill_value = dtype.from_json_scalar({"x": 42}, zarr_format=3) + assert fill_value["x"] == 42 + assert fill_value["y"] == 0.0 + + +def test_fill_value_legacy_base64() -> None: + """Test that legacy base64-encoded fill values are still readable.""" + dtype = Struct(fields=(("field1", Int32()), ("field2", Float64()))) + fill_value = dtype.from_json_scalar("AQAAAAAAAAAAAPA/", zarr_format=3) + assert fill_value["field1"] == 1 + assert fill_value["field2"] == 1.0 + + +def test_fill_value_to_json_dict_form() -> None: + """Test that fill values are serialized as dict form.""" + dtype = Struct(fields=(("x", Int32()), ("y", Float64()))) + scalar = np.array((42, 3.14), dtype=[("x", np.int32), ("y", np.float64)])[()] + json_val = dtype.to_json_scalar(scalar, zarr_format=3) + assert isinstance(json_val, dict) + assert json_val["x"] == 42 + assert json_val["y"] == 3.14 + + +def test_has_multi_byte_fields_true() -> None: + """Test that has_multi_byte_fields returns True for dtypes with multi-byte fields.""" + dtype = Struct(fields=(("field1", Int32()), ("field2", Float64()))) + assert dtype.has_multi_byte_fields() is True + + +def test_has_multi_byte_fields_false() -> None: + """Test that has_multi_byte_fields returns False for dtypes with only single-byte fields.""" + dtype = Struct(fields=(("field1", UInt8()), ("field2", UInt8()))) + assert dtype.has_multi_byte_fields() is False + + +def test_struct_from_native_dtype() -> None: + """Test that Struct can be created from native numpy dtype.""" + dtype = np.dtype([("field1", np.int32), ("field2", np.float64)]) + struct = Struct.from_native_dtype(dtype) + assert struct.fields[0][0] == "field1" + assert struct.fields[1][0] == "field2" diff --git a/tests/test_dtype/test_npy/test_time.py b/tests/test_dtype/test_npy/test_time.py index b94b600cbf..67ba3bd130 100644 --- a/tests/test_dtype/test_npy/test_time.py +++ b/tests/test_dtype/test_npy/test_time.py @@ -66,7 +66,7 @@ class TestDateTime64(_TestTimeBase): cast_value_params = ( (DateTime64(unit="Y", scale_factor=1), "1", np.datetime64("1", "Y")), (DateTime64(unit="s", scale_factor=1), "2005-02-25", np.datetime64("2005-02-25", "s")), - (DateTime64(unit="ns", scale_factor=1), "NaT", np.datetime64("NaT")), + (DateTime64(unit="ns", scale_factor=1), "NaT", np.datetime64("NaT", "ns")), ) invalid_scalar_params = ( (DateTime64(unit="Y", scale_factor=1), 1.3), @@ -115,7 +115,7 @@ class TestTimeDelta64(_TestTimeBase): cast_value_params = ( (TimeDelta64(unit="ns", scale_factor=1), "1", np.timedelta64(1, "ns")), - (TimeDelta64(unit="ns", scale_factor=1), "NaT", np.timedelta64("NaT")), + (TimeDelta64(unit="ns", scale_factor=1), "NaT", np.timedelta64("NaT", "ns")), ) invalid_scalar_params = ( (TimeDelta64(unit="Y", scale_factor=1), 1.3), @@ -148,6 +148,12 @@ def test_time_scale_factor_too_low() -> None: TimeDelta64(scale_factor=scale_factor) +def test_default_is_NaT() -> None: + np.testing.assert_equal( + TimeDelta64(unit="ns", scale_factor=1).default_scalar(), np.timedelta64("NaT", "ns") + ) + + def test_time_scale_factor_too_high() -> None: """ Test that an invalid unit raises a ValueError. diff --git a/tests/test_dtype_registry.py b/tests/test_dtype_registry.py index b7ceb502b7..40239c1132 100644 --- a/tests/test_dtype_registry.py +++ b/tests/test_dtype_registry.py @@ -15,7 +15,6 @@ get_data_type_from_json, ) from zarr.core.dtype.common import unpack_dtype_json -from zarr.core.dtype.npy.string import _NUMPY_SUPPORTS_VLEN_STRING from zarr.dtype import ( # type: ignore[attr-defined] Bool, FixedLengthUTF32, @@ -76,13 +75,12 @@ def test_match_dtype( data_type_registry_fixture.register(wrapper_cls._zarr_v3_name, wrapper_cls) assert isinstance(data_type_registry_fixture.match_dtype(np.dtype(dtype_str)), wrapper_cls) - @pytest.mark.skipif(not _NUMPY_SUPPORTS_VLEN_STRING, reason="requires numpy with T dtype") @staticmethod def test_match_dtype_string_na_object_error( data_type_registry_fixture: DataTypeRegistry, ) -> None: data_type_registry_fixture.register(VariableLengthUTF8._zarr_v3_name, VariableLengthUTF8) # type: ignore[arg-type] - dtype: np.dtype[Any] = np.dtypes.StringDType(na_object=None) # type: ignore[call-arg] + dtype: np.dtype[Any] = np.dtypes.StringDType(na_object=None) with pytest.raises(ValueError, match=r"Zarr data type resolution from StringDType.*failed"): data_type_registry_fixture.match_dtype(dtype) @@ -172,7 +170,7 @@ def test_entrypoint_dtype(zarr_format: ZarrFormat) -> None: ) def test_parse_data_type( data_type: ZDType[Any, Any], - json_style: tuple[ZarrFormat, None | Literal["internal", "metadata"]], + json_style: tuple[ZarrFormat, Literal["internal", "metadata"] | None], dtype_parser_func: Any, ) -> None: """ diff --git a/tests/test_errors.py b/tests/test_errors.py index ccc9e597bb..17dbada9f4 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -1,13 +1,17 @@ """Test errors""" +import pytest + from zarr.errors import ( ArrayNotFoundError, ContainsArrayAndGroupError, ContainsArrayError, ContainsGroupError, + DataTypeValidationError, GroupNotFoundError, MetadataValidationError, NodeTypeValidationError, + ZarrDeprecationWarning, ) @@ -76,3 +80,22 @@ def test_node_type_validation_error() -> None: """ err = NodeTypeValidationError("a", "b", "c") assert str(err) == "Invalid value for 'a'. Expected 'b'. Got 'c'." + + +@pytest.mark.parametrize( + "module_name", + [ + "zarr.core.dtype.common", + "zarr.core.dtype", + "zarr.dtype", + ], +) +def test_data_type_validation_error_deprecated_import(module_name: str) -> None: + import importlib + + module = importlib.import_module(module_name) + + with pytest.warns(ZarrDeprecationWarning, match=f"{module_name}"): + cls = module.DataTypeValidationError + + assert cls is DataTypeValidationError diff --git a/tests/test_examples.py b/tests/test_examples.py index 9f8085e8c2..a6634e8cc6 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -80,7 +80,7 @@ def test_scripts_can_run(script_path: Path, tmp_path: Path) -> None: # This allows the example to be useful to users who don't have Zarr installed, but also testable. resave_script(script_path, dest_path) result = subprocess.run( - ["uv", "run", "--refresh", str(dest_path)], capture_output=True, text=True + ["uv", "run", "--refresh", str(dest_path)], capture_output=True, text=True, check=False ) assert result.returncode == 0, ( f"Script at {script_path} failed to run. Output: {result.stdout} Error: {result.stderr}" diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index fc17ccd5e1..f688a6ca02 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -131,21 +131,14 @@ async def test_cache_expiration(self) -> None: test_data = CPUBuffer.from_bytes(b"expiring data") await cached_store.set("expire_key", test_data) - # Should be fresh initially (if _is_key_fresh method exists) - if hasattr(cached_store, "_is_key_fresh"): - assert cached_store._is_key_fresh("expire_key") - - # Wait for expiration - await asyncio.sleep(1.1) - - # Should now be stale - assert not cached_store._is_key_fresh("expire_key") - else: - # Skip freshness check if method doesn't exist - await asyncio.sleep(1.1) - # Just verify the data is still accessible - result = await cached_store.get("expire_key", default_buffer_prototype()) - assert result is not None + # Should be fresh initially + assert cached_store._is_key_fresh("expire_key") + + # Wait for expiration + await asyncio.sleep(1.1) + + # Should now be stale + assert not cached_store._is_key_fresh("expire_key") async def test_cache_set_data_false(self, source_store: Store, cache_store: Store) -> None: """Test behavior when cache_set_data=False.""" @@ -225,10 +218,6 @@ async def test_stale_cache_refresh(self) -> None: async def test_infinity_max_age(self, cached_store: CacheStore) -> None: """Test that 'infinity' max_age means cache never expires.""" - # Skip test if _is_key_fresh method doesn't exist - if not hasattr(cached_store, "_is_key_fresh"): - pytest.skip("_is_key_fresh method not implemented") - test_data = CPUBuffer.from_bytes(b"eternal data") await cached_store.set("eternal_key", test_data) @@ -1047,3 +1036,40 @@ async def test_delete_invalidates_cached_byte_ranges(self) -> None: # Key is gone from source result = await cached_store.get("key", proto) assert result is None + + +def test_cache_store_opts_out_of_sync_io() -> None: + """`CacheStore` must not advertise sync IO capability. + + Its caching logic lives only in the async `get`/`set`/`delete` overrides, + while the inherited `WrapperStore` sync methods delegate straight to the + source store. If the fused codec pipeline took the sync fast path, writes + and deletes would bypass the cache and later async reads would serve stale + entries. The opt-out forces sync-capable consumers onto the async path, + which keeps the cache coherent. + """ + from zarr.abc.store import _store_supports_sync_io + from zarr.storage import MemoryStore + + cached = CacheStore(MemoryStore(), cache_store=MemoryStore()) + assert _store_supports_sync_io(cached) is False + + +async def test_cache_coherent_after_fused_pipeline_write() -> None: + """Writing through the fused pipeline must not leave stale cache entries.""" + import numpy as np + + import zarr + from zarr.core.config import config as zarr_config + from zarr.storage import MemoryStore + + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array(cached, shape=(8,), chunks=(8,), dtype="int32", fill_value=0) + arr[:] = np.arange(8, dtype="int32") + np.testing.assert_array_equal(arr[:], np.arange(8)) + # Overwrite, then read back through the same cached handle: the read + # must observe the overwrite, not a cached copy of the first write. + arr[:] = np.arange(100, 108, dtype="int32") + np.testing.assert_array_equal(arr[:], np.arange(100, 108)) diff --git a/tests/test_fastpath_equivalence.py b/tests/test_fastpath_equivalence.py new file mode 100644 index 0000000000..9a2f782d13 --- /dev/null +++ b/tests/test_fastpath_equivalence.py @@ -0,0 +1,402 @@ +"""Property tests: every fast path must equal the general path. + +The codec pipelines contain fast paths that skip work whose result is known — +the complete-chunk merge view, the vectorized whole-shard bulk decode, the +scalar-broadcast write memoization, byte-range coalescing. Each is only safe if +it produces results identical to the general path it bypasses. These tests pin +that equivalence on randomized inputs, so a fast path that silently diverges +(the bug class behind the bulk-decode endianness fix) fails here instead of +corrupting data downstream. + +Convention for new fast paths: a fast path is "skip work whose result is +known", never "a different algorithm" — and it ships with a property test in +this module asserting equality with the general path. +""" + +from __future__ import annotations + +from typing import Any + +import hypothesis.extra.numpy as npst +import hypothesis.strategies as st +import numpy as np +from hypothesis import given, settings + +import zarr +from zarr.abc.store import OffsetByteRequest, RangeByteRequest, SuffixByteRequest +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.sharding import ShardingCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import default_buffer_prototype +from zarr.core.buffer.cpu import Buffer as CPUBuffer +from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer +from zarr.core.chunk_grids import ChunkGrid +from zarr.core.chunk_utils import _merge_chunk_array +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.indexing import BasicIndexer +from zarr.storage import MemoryStore + +_DTYPES = st.sampled_from(["uint8", "int16", "float32"]) + + +def _spec(shape: tuple[int, ...], dtype: str, *, write_empty_chunks: bool = True) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(np.dtype(dtype)) + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=write_empty_chunks), + prototype=default_buffer_prototype(), + ) + + +# --------------------------------------------------------------------------- +# _merge_chunk_array: the complete-chunk early return (a view of +# value[out_selection]) must equal the general create/copy + setitem path. +# --------------------------------------------------------------------------- + + +@st.composite +def _merge_cases(draw: st.DrawFn) -> tuple[np.ndarray, tuple[int, ...], tuple[slice, ...]]: + ndim = draw(st.integers(1, 3)) + chunk_shape = tuple(draw(st.integers(1, 5)) for _ in range(ndim)) + n_blocks = draw(st.integers(1, 3)) + dtype = draw(_DTYPES) + # value spans n_blocks chunk-sized blocks along axis 0; out_selection picks one + value_shape = (chunk_shape[0] * n_blocks, *chunk_shape[1:]) + value = draw(npst.arrays(dtype=np.dtype(dtype), shape=value_shape)) + block = draw(st.integers(0, n_blocks - 1)) + out_selection = ( + slice(block * chunk_shape[0], (block + 1) * chunk_shape[0]), + *(slice(0, s) for s in chunk_shape[1:]), + ) + return value, chunk_shape, out_selection + + +@settings(max_examples=200, deadline=None) +@given(case=_merge_cases(), with_existing=st.booleans()) +def test_merge_complete_chunk_equals_general_path( + case: tuple[np.ndarray, tuple[int, ...], tuple[slice, ...]], with_existing: bool +) -> None: + """The is_complete_chunk fast path (return a view of value[out_selection]) + must produce exactly what the general merge path produces — and a complete + write must be independent of any existing chunk content.""" + value_np, chunk_shape, out_selection = case + spec = _spec(chunk_shape, str(value_np.dtype)) + value = CPUNDBuffer.from_numpy_array(value_np) + chunk_selection = tuple(slice(0, s) for s in chunk_shape) + + existing = None + if with_existing: + existing = CPUNDBuffer.from_numpy_array(np.full(chunk_shape, 7, dtype=value_np.dtype)) + + fast = _merge_chunk_array(existing, value, out_selection, spec, chunk_selection, True, ()) + general = _merge_chunk_array(existing, value, out_selection, spec, chunk_selection, False, ()) + np.testing.assert_array_equal(fast.as_numpy_array(), general.as_numpy_array()) + np.testing.assert_array_equal(fast.as_numpy_array(), value_np[out_selection]) + + +# --------------------------------------------------------------------------- +# _decode_full_shard_bulk_if_uncompressed: the vectorized dense-shard decode must equal the +# general per-chunk decode (_decode_sync), across dtypes, endianness, write +# orders, and index locations. This is the bug class of the historical +# bulk-decode endianness fix. +# --------------------------------------------------------------------------- + + +@st.composite +def _shard_cases(draw: st.DrawFn) -> dict[str, Any]: + ndim = draw(st.integers(1, 2)) + chunk_shape = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) + grid = tuple(draw(st.integers(1, 3)) for _ in range(ndim)) + shard_shape = tuple(c * g for c, g in zip(chunk_shape, grid, strict=True)) + dtype = draw(_DTYPES) + data = draw(npst.arrays(dtype=np.dtype(dtype), shape=shard_shape)) + return { + "chunk_shape": chunk_shape, + "shard_shape": shard_shape, + "data": data, + "endian": draw(st.sampled_from(["little", "big"])), + "index_location": draw(st.sampled_from(["start", "end"])), + "subchunk_write_order": draw( + st.sampled_from(["morton", "lexicographic", "colexicographic", "unordered"]) + ), + } + + +@settings(max_examples=100, deadline=None) +@given(case=_shard_cases()) +def test_bulk_shard_decode_equals_general_decode(case: dict[str, Any]) -> None: + """For dense fixed-size uncompressed shards, the vectorized bulk decode must + reproduce the general per-chunk decode exactly, whatever the endianness, + subchunk write order, or index location.""" + codec = ShardingCodec( + chunk_shape=case["chunk_shape"], + codecs=[BytesCodec(endian=case["endian"])], + index_location=case["index_location"], + subchunk_write_order=case["subchunk_write_order"], + ) + spec = _spec(case["shard_shape"], str(case["data"].dtype), write_empty_chunks=True) + blob = codec._encode_sync(CPUNDBuffer.from_numpy_array(case["data"]), spec) + assert blob is not None # write_empty_chunks=True -> dense, never elided + + general = codec._decode_sync(blob, spec) + indexer = BasicIndexer( + tuple(slice(0, s) for s in case["shard_shape"]), + shape=case["shard_shape"], + chunk_grid=ChunkGrid.from_sizes(case["shard_shape"], case["chunk_shape"]), + ) + bulk = codec._decode_full_shard_bulk_if_uncompressed(blob, spec, indexer) + # the fast path must APPLY for this dense uncompressed configuration — + # a vacuous None would silently stop testing the equivalence + assert bulk is not None + np.testing.assert_array_equal(bulk.as_numpy_array(), general.as_numpy_array()) + np.testing.assert_array_equal(general.as_numpy_array(), case["data"]) + + +def test_merge_complete_chunk_returns_view_and_write_does_not_mutate_source() -> None: + """The complete-chunk merge fast path returns a VIEW of the caller's value + (no copy — that is the perf win), and a multi-chunk write through either + pipeline leaves the user's source array untouched. + + Pins both halves of the aliasing contract: a future "defensive copy" + refactor that silently reintroduces the per-chunk create/fill/copy breaks + the first assertion, and an in-place-mutating codec that corrupts the + user's array through the shared view breaks the second. + """ + # the fast path must return a view aliasing `value`, not a copy + value_np = np.arange(30, dtype="uint16") + spec = _spec((10,), "uint16") + value = CPUNDBuffer.from_numpy_array(value_np) + merged = _merge_chunk_array(None, value, (slice(10, 20),), spec, (slice(0, 10),), True, ()) + assert np.shares_memory(merged.as_numpy_array(), value_np), ( + "complete-chunk merge no longer returns a view of the caller's value" + ) + + # end-to-end: the source array is byte-identical after a multi-chunk write + for pipeline_path in ( + "zarr.core.codec_pipeline.FusedCodecPipeline", + "zarr.core.codec_pipeline.BatchedCodecPipeline", + ): + with zarr.config.set({"codec_pipeline.path": pipeline_path}): + arr = zarr.create_array( + store=MemoryStore(), + shape=(30,), + chunks=(10,), + dtype="uint16", + compressors=None, + fill_value=0, + ) + source = np.arange(30, dtype="uint16") + snapshot = source.copy() + arr[:] = source + np.testing.assert_array_equal(source, snapshot, err_msg=pipeline_path) + np.testing.assert_array_equal(arr[:], snapshot, err_msg=pipeline_path) + + +# --------------------------------------------------------------------------- +# Whole-shard bulk decode under arbitrary indexing: the bulk decode only fires +# for an *identity full-shard* read (every dimension a whole-dim step-1 slice), +# but it is reached through the partial-read path (`_decode_partial_sync`) for +# any indexer. A reordering or duplicating coordinate/orthogonal selection can +# have an output shape equal to the shard shape — trivially in 1-D (any +# selection of `shard_len` points), and in >=2-D whenever an axis-0 index array +# has exactly `shard_shape[0]` entries — and must NOT be served by the bulk +# path in natural order; it must honor the selection. This pins the END-TO-END +# read, which `test_bulk_shard_decode_equals_general_decode` (identity +# BasicIndexer only) cannot reach. See the vindex- and +# oindex-on-uncompressed-shard corruption bugs. +# --------------------------------------------------------------------------- + + +@st.composite +def _uncompressed_shard_index_cases(draw: st.DrawFn) -> dict[str, Any]: + ndim = draw(st.integers(1, 2)) + chunk_shape = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) + grid = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) + shard_shape = tuple(c * g for c, g in zip(chunk_shape, grid, strict=True)) + dtype = draw(_DTYPES) + data = draw(npst.arrays(dtype=np.dtype(dtype), shape=shard_shape)) + dim0 = shard_shape[0] + # axis-0 index array sized to the dimension: either a permutation + # (reordering, no duplicates) or an arbitrary list (duplicates likely) — + # both keep the output shape equal to the shard shape. + if draw(st.booleans()): + idx = np.array(draw(st.permutations(list(range(dim0)))), dtype=np.intp) + else: + idx = np.array( + draw(st.lists(st.integers(0, dim0 - 1), min_size=dim0, max_size=dim0)), + dtype=np.intp, + ) + return { + "chunk_shape": chunk_shape, + "shard_shape": shard_shape, + "data": data, + "idx": idx, + "endian": draw(st.sampled_from(["little", "big"])), + "index_location": draw(st.sampled_from(["start", "end"])), + "subchunk_write_order": draw( + st.sampled_from(["morton", "lexicographic", "colexicographic", "unordered"]) + ), + } + + +@settings(max_examples=200, deadline=None) +@given(case=_uncompressed_shard_index_cases()) +def test_reordering_read_on_uncompressed_shard_honors_selection(case: dict[str, Any]) -> None: + """A reordering or duplicating fancy/vindex/oindex read over a full + uncompressed shard must return the selected data, not the shard in natural + order — under the Fused pipeline (where the bulk-decode fast path engages) + exactly as under numpy.""" + idx = case["idx"] + data = case["data"] + ndim = data.ndim + serializer = BytesCodec(endian=case["endian"]) + + with zarr.config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + store=MemoryStore(), + shape=case["shard_shape"], + chunks=case["chunk_shape"], + shards={"shape": case["shard_shape"], "index_location": case["index_location"]}, + dtype=data.dtype, + serializer=serializer, + compressors=None, + filters=None, + fill_value=0, + ) + arr[...] = data + + # axis-0 index array (rest full slices): an OrthogonalIndexer whose + # output shape equals the shard shape but which reorders/duplicates rows. + rest = (slice(None),) * (ndim - 1) + np.testing.assert_array_equal(arr[(idx, *rest)], data[idx]) + np.testing.assert_array_equal(arr.oindex[(idx, *rest)], data[idx]) + if ndim == 1: + # coordinate selection: flattened point count == shard shape. + np.testing.assert_array_equal(arr.vindex[idx], data[idx]) + else: + # 2-D broadcast index arrays: full-coverage coordinate selection + # whose shape equals the shard shape. + cols = np.arange(case["shard_shape"][1]) + np.testing.assert_array_equal( + arr.vindex[idx[:, None], cols[None, :]], data[idx[:, None], cols[None, :]] + ) + + +# --------------------------------------------------------------------------- +# Scalar-broadcast write memoization: writing a scalar must produce the same +# STORED BYTES as writing the equivalent broadcast array. +# --------------------------------------------------------------------------- + + +@st.composite +def _scalar_cases(draw: st.DrawFn) -> dict[str, Any]: + n_chunks = draw(st.integers(2, 6)) + chunk = draw(st.integers(2, 6)) + shape = n_chunks * chunk + start = draw(st.integers(0, shape - 1)) + stop = draw(st.integers(start + 1, shape)) + return { + "shape": shape, + "chunk": chunk, + "sel": slice(start, stop), + "scalar": draw(st.integers(0, 255)), + "write_empty_chunks": draw(st.booleans()), + "sharded": draw(st.booleans()), + } + + +@settings(max_examples=100, deadline=None) +@given(case=_scalar_cases()) +def test_scalar_write_equals_broadcast_write(case: dict[str, Any]) -> None: + """arr[sel] = scalar and arr[sel] = full(sel_shape, scalar) must leave the + store byte-identical (pins the scalar-broadcast memoization in the sharded + partial-write path, incl. its empty-chunk normalization).""" + + def build() -> tuple[MemoryStore, zarr.Array[Any]]: + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(case["shape"],), + chunks=(case["chunk"],), + shards=(case["shape"],) if case["sharded"] else None, + dtype="uint8", + compressors=None, + fill_value=0, + config={"write_empty_chunks": case["write_empty_chunks"]}, + ) + return store, arr + + # The scalar-broadcast memoization lives in the Fused sync write path; pin it + # explicitly since Fused is no longer the default pipeline. + with zarr.config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + store_a, arr_a = build() + arr_a[case["sel"]] = case["scalar"] + + store_b, arr_b = build() + n = case["sel"].stop - case["sel"].start + arr_b[case["sel"]] = np.full(n, case["scalar"], dtype="uint8") + + keys_a = {k: bytes(v.to_bytes()) for k, v in store_a._store_dict.items()} + keys_b = {k: bytes(v.to_bytes()) for k, v in store_b._store_dict.items()} + assert keys_a == keys_b + + +# --------------------------------------------------------------------------- +# get_ranges_sync coalescing: merged fetches must return exactly what +# individual per-range gets return, for any gap/coalesce limits. +# --------------------------------------------------------------------------- + + +@st.composite +def _range_cases(draw: st.DrawFn) -> dict[str, Any]: + blob_len = draw(st.integers(1, 200)) + n = draw(st.integers(1, 8)) + ranges: list[RangeByteRequest | OffsetByteRequest | SuffixByteRequest | None] = [] + for _ in range(n): + kind = draw(st.sampled_from(["range", "offset", "suffix", "none"])) + if kind == "range": + start = draw(st.integers(0, blob_len - 1)) + end = draw(st.integers(start + 1, blob_len)) + ranges.append(RangeByteRequest(start, end)) + elif kind == "offset": + ranges.append(OffsetByteRequest(draw(st.integers(0, blob_len - 1)))) + elif kind == "suffix": + ranges.append(SuffixByteRequest(draw(st.integers(1, blob_len)))) + else: + ranges.append(None) + return { + "blob": draw(st.binary(min_size=blob_len, max_size=blob_len)), + "ranges": ranges, + "max_gap": draw(st.integers(0, 64)), + "max_coalesced": draw(st.integers(1, 512)), + } + + +@settings(max_examples=200, deadline=None) +@given(case=_range_cases()) +def test_get_ranges_sync_equals_individual_gets(case: dict[str, Any]) -> None: + """Coalesced byte-range reads must return exactly what one get_sync per + range returns — for any gap/coalesce limits (the offset re-slicing math is + where a coalescing bug would corrupt data).""" + store = MemoryStore() + store._is_open = True + proto = default_buffer_prototype() + store._store_dict["k"] = CPUBuffer.from_bytes(case["blob"]) + + expected = [store.get_sync("k", prototype=proto, byte_range=r) for r in case["ranges"]] + + got: dict[int, bytes | None] = {} + for idx, buf in store.get_ranges_sync( + "k", + case["ranges"], + prototype=proto, + max_gap_bytes=case["max_gap"], + max_coalesced_bytes=case["max_coalesced"], + ): + got[idx] = None if buf is None else bytes(buf.to_bytes()) + + for i, exp in enumerate(expected): + exp_bytes = None if exp is None else bytes(exp.to_bytes()) + assert got.get(i) == exp_bytes, f"range {i} ({case['ranges'][i]!r}) mismatch" diff --git a/tests/test_fused_pipeline.py b/tests/test_fused_pipeline.py new file mode 100644 index 0000000000..5c712fa97a --- /dev/null +++ b/tests/test_fused_pipeline.py @@ -0,0 +1,1235 @@ +"""Tests for FusedCodecPipeline -- the per-chunk-fused codec pipeline.""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr +from zarr.abc.codec import ( + ArrayBytesCodec, + ArrayBytesCodecPartialDecodeMixin, + ArrayBytesCodecPartialEncodeMixin, + BytesBytesCodec, +) +from zarr.abc.store import Store, _store_supports_sync_io +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.zstd import ZstdCodec +from zarr.core.codec_pipeline import FusedCodecPipeline +from zarr.core.config import config as zarr_config +from zarr.registry import register_codec +from zarr.storage import MemoryStore, StorePath, WrapperStore +from zarr.storage._utils import _normalize_byte_range_index +from zarr.testing.store import LatencyStore + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable, Iterable + + from zarr.abc.store import ByteRequest + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer + + +@pytest.mark.parametrize( + "codecs", + [ + (BytesCodec(),), + (BytesCodec(), GzipCodec(level=1)), + (BytesCodec(), ZstdCodec(level=1)), + (TransposeCodec(order=(1, 0)), BytesCodec()), + (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec(level=1)), + ], + ids=["bytes-only", "gzip", "zstd", "transpose", "transpose+zstd"], +) +def test_construction(codecs: tuple[Any, ...]) -> None: + """FusedCodecPipeline can be constructed from valid codec combinations.""" + pipeline = FusedCodecPipeline.from_codecs(codecs) + assert pipeline.codecs == codecs + + +def test_sync_api_compute_off_event_loop(monkeypatch: pytest.MonkeyPatch) -> None: + """Codec compute must never run on the thread driving the event loop. + + Every sync-API call, from every user thread, is serviced by the one global + `zarr_io` event loop. Running decode/encode inline on that loop's thread + turns it into a mutex around codec compute: concurrent readers serialize, + and the penalty grows with codec cost (observed as "fused pipeline is + slower for zstd data" under dask-style multi-threaded single-chunk reads). + """ + import asyncio + + from zarr.core.chunk_utils import ChunkTransform + + compute_on_loop = {"decode": False, "encode": False} + calls = {"decode": 0, "encode": 0} + real_decode = ChunkTransform.decode_chunk + real_encode = ChunkTransform.encode_chunk + + def _running_loop() -> bool: + try: + asyncio.get_running_loop() + except RuntimeError: + return False + return True + + def traced_decode(self: ChunkTransform, chunk_bytes: Any, chunk_spec: Any) -> Any: + calls["decode"] += 1 + compute_on_loop["decode"] = compute_on_loop["decode"] or _running_loop() + return real_decode(self, chunk_bytes, chunk_spec) + + def traced_encode(self: ChunkTransform, chunk_array: Any, chunk_spec: Any) -> Any: + calls["encode"] += 1 + compute_on_loop["encode"] = compute_on_loop["encode"] or _running_loop() + return real_encode(self, chunk_array, chunk_spec) + + monkeypatch.setattr(ChunkTransform, "decode_chunk", traced_decode) + monkeypatch.setattr(ChunkTransform, "encode_chunk", traced_encode) + + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + MemoryStore(), + shape=(8, 8), + chunks=(4, 4), + dtype="float64", + compressors=ZstdCodec(level=1), + ) + data = np.arange(64, dtype="float64").reshape(8, 8) + arr[:4, :4] = data[:4, :4] # single-chunk write (batch of 1) + arr[:] = data # multi-chunk write + # Guard against vacuity: if the sync fast path stops triggering, the + # traced ChunkTransform methods are never called (the async fallback + # uses AsyncChunkTransform) and the on-loop flags stay trivially False. + assert calls["encode"] > 0 + assert compute_on_loop["encode"] is False + + np.testing.assert_array_equal(arr[:4, :4], data[:4, :4]) # single-chunk read + np.testing.assert_array_equal(arr[:], data) # multi-chunk read + assert calls["decode"] > 0 + assert compute_on_loop["decode"] is False + + +def test_evolve_from_array_spec() -> None: + """evolve_from_array_spec creates a sync transform.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype import get_data_type_from_native_dtype + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + assert pipeline.sync_transform is None + + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(100,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + evolved = pipeline.evolve_from_array_spec(spec) + assert evolved.sync_transform is not None + + +# --------------------------------------------------------------------------- +# Sync path tests +# +# These exercise FusedCodecPipeline's synchronous API (write_sync / read_sync / +# sync_transform), which has no equivalent on BatchedCodecPipeline -- so they +# cannot live in the pipeline-agnostic CodecPipelineTests suite. The async +# roundtrip / fill-value behaviour is covered there (test_scenario) across both +# pipelines and sync/async stores. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("dtype", "shape"), + [ + ("float64", (100,)), + ("float32", (50,)), + ("int32", (200,)), + ("float64", (10, 10)), + ], + ids=["f64-1d", "f32-1d", "i32-1d", "f64-2d"], +) +def test_read_write_sync_roundtrip(dtype: str, shape: tuple[int, ...]) -> None: + """Data written via write_sync can be read back via read_sync.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + + store = MemoryStore() + zdtype = get_data_type_from_native_dtype(np.dtype(dtype)) + spec = ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + pipeline = pipeline.evolve_from_array_spec(spec) + + data = np.arange(int(np.prod(shape)), dtype=dtype).reshape(shape) + value = CPUNDBuffer.from_numpy_array(data) + chunk_selection = tuple(slice(0, s) for s in shape) + out_selection = chunk_selection + store_path = StorePath(store, "c/0") + + # Write sync + pipeline.write_sync( + [(store_path, spec, chunk_selection, out_selection, True)], + value, + ) + + # Read sync + out = CPUNDBuffer.from_numpy_array(np.zeros(shape, dtype=dtype)) + pipeline.read_sync( + [(store_path, spec, chunk_selection, out_selection, True)], + out, + ) + + np.testing.assert_array_equal(data, out.as_numpy_array()) + + +def test_read_sync_missing_chunk_fills() -> None: + """Sync read of a missing chunk fills with the fill value.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + + store = MemoryStore() + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(42.0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + pipeline = pipeline.evolve_from_array_spec(spec) + + out = CPUNDBuffer.from_numpy_array(np.zeros(10, dtype="float64")) + store_path = StorePath(store, "c/0") + chunk_sel = (slice(0, 10),) + + pipeline.read_sync( + [(store_path, spec, chunk_sel, chunk_sel, True)], + out, + ) + + np.testing.assert_array_equal(out.as_numpy_array(), np.full(10, 42.0)) + + +def test_sync_write_async_read_roundtrip() -> None: + """Data written via write_sync can be read back via async read.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + from zarr.core.sync import sync + + store = MemoryStore() + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(100,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + pipeline = pipeline.evolve_from_array_spec(spec) + + data = np.arange(100, dtype="float64") + value = CPUNDBuffer.from_numpy_array(data) + chunk_sel = (slice(0, 100),) + store_path = StorePath(store, "c/0") + + # Write sync + pipeline.write_sync( + [(store_path, spec, chunk_sel, chunk_sel, True)], + value, + ) + + # Read async + out = CPUNDBuffer.from_numpy_array(np.zeros(100, dtype="float64")) + sync( + pipeline.read( + [(store_path, spec, chunk_sel, chunk_sel, True)], + out, + ) + ) + + +def test_chunk_transform_uses_runtime_prototype() -> None: + """ChunkTransform must pass each codec the prototype from the runtime chunk_spec, + not one captured at evolve time. Constructs ChunkTransform directly (a + Fused-internal data structure with no BatchedCodecPipeline equivalent). + """ + from zarr.abc.codec import BytesBytesCodec + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import BufferPrototype, default_buffer_prototype + from zarr.core.chunk_utils import ChunkTransform + from zarr.core.dtype import get_data_type_from_native_dtype + + class _PrototypeRecordingCodec(BytesBytesCodec): # type: ignore[misc,unused-ignore] + """A no-op BB codec that records the prototype it was called with.""" + + is_fixed_size = True + seen_prototypes: list[object] + + def __init__(self) -> None: + object.__setattr__(self, "seen_prototypes", []) + + def to_dict(self) -> dict[str, Any]: + return {"name": "_prototype_recording", "configuration": {}} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _PrototypeRecordingCodec: + return cls() + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: + self.seen_prototypes.append(chunk_spec.prototype) + return chunk_bytes + + def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + self.seen_prototypes.append(chunk_spec.prototype) + return chunk_bytes + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: + return self._encode_sync(chunk_bytes, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + recording = _PrototypeRecordingCodec() + transform = ChunkTransform(codecs=(BytesCodec(), recording)) + + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + + def _spec(prototype: BufferPrototype) -> ArraySpec: + return ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0.0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=prototype, + ) + + proto_default = default_buffer_prototype() + # A distinct BufferPrototype instance with the same buffer/nd_buffer types -- + # fails an identity check but works at runtime. + proto_other = BufferPrototype(buffer=proto_default.buffer, nd_buffer=proto_default.nd_buffer) + assert proto_other is not proto_default + + arr = proto_default.nd_buffer.from_numpy_array(np.arange(10, dtype="float64")) + transform.encode_chunk(arr, _spec(proto_default)) + transform.encode_chunk(arr, _spec(proto_other)) + + assert recording.seen_prototypes[0] is proto_default + assert recording.seen_prototypes[1] is proto_other, ( + "ChunkTransform did not pass the runtime prototype to the codec" + ) + + +# --------------------------------------------------------------------------- +# Thread-pool (max_workers > 1) tests +# +# The pool dispatch in read_sync/write_sync is Fused-only and off by default +# (codec_pipeline.max_workers defaults to 1 == sequential). These tests opt in +# and exercise the pool path end-to-end, exception propagation from workers, +# and concurrent decode through the shared ChunkTransform. +# --------------------------------------------------------------------------- + +_FUSED_POOL_CONFIG = { + "codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline", + "codec_pipeline.max_workers": 4, +} + + +def test_read_write_with_thread_pool() -> None: + """With max_workers > 1, multi-chunk reads and writes dispatch through the + thread pool (pool.map in read_sync/write_sync) and produce the same results + as sequential execution. + + The `_get_pool` spy pins that the pool branch actually fires: without it, + a config-resolution regression (renamed key, `_resolve_max_workers` + returning 1) would silently degrade all the pool tests into re-testing the + sequential branch while staying green. + """ + from unittest.mock import patch + + import zarr.core.codec_pipeline as cp_mod + + with zarr_config.set(_FUSED_POOL_CONFIG): + assert cp_mod._resolve_max_workers() == 4, ( + "codec_pipeline.max_workers config did not reach _resolve_max_workers" + ) + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + data = np.arange(100, dtype="float64") + with patch.object(cp_mod, "_get_pool", wraps=cp_mod._get_pool) as pool_spy: + arr[:] = data # 10 chunks -> pool dispatch in write_sync + assert pool_spy.call_count >= 1, "multi-chunk write did not take the pool branch" + writes = pool_spy.call_count + np.testing.assert_array_equal(arr[:], data) # pool dispatch in read_sync + assert pool_spy.call_count > writes, "multi-chunk read did not take the pool branch" + arr[5:25] = 7.0 # partial write: merge path through the pool + data[5:25] = 7.0 + np.testing.assert_array_equal(arr[:], data) + + +def test_thread_pool_write_worker_exception_propagates() -> None: + """A store error raised inside a pool worker during write_sync surfaces to + the caller (write_sync consumes pool.map, so worker exceptions re-raise).""" + from unittest.mock import patch + + with zarr_config.set(_FUSED_POOL_CONFIG): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + with ( + patch.object(store, "set_sync", side_effect=RuntimeError("simulated store error")), + pytest.raises(RuntimeError, match="simulated store error"), + ): + arr[:] = np.arange(100, dtype="float64") + + +def test_thread_pool_read_worker_exception_propagates() -> None: + """A store error raised inside a pool worker during read_sync surfaces to + the caller (read_sync consumes pool.map into a tuple).""" + from unittest.mock import patch + + with zarr_config.set(_FUSED_POOL_CONFIG): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + arr[:] = np.arange(100, dtype="float64") + with ( + patch.object(store, "get_sync", side_effect=RuntimeError("simulated store error")), + pytest.raises(RuntimeError, match="simulated store error"), + ): + arr[:] + + +def test_resolve_max_workers_warns_and_falls_back_on_invalid_config() -> None: + """`codec_pipeline.max_workers` arrives via the config/env layer (e.g. + `ZARR_CODEC_PIPELINE__MAX_WORKERS`), so garbage input should warn and fall + back to the default rather than raising mid-read. + """ + import os + + import zarr.core.codec_pipeline as cp_mod + from zarr.errors import ZarrUserWarning + + default = os.cpu_count() or 1 + with zarr_config.set({"codec_pipeline.max_workers": "fast"}): + with pytest.warns(ZarrUserWarning, match="max_workers"): + result = cp_mod._resolve_max_workers() + assert result == default + + +async def test_encode_and_write_as_completed_cancels_stray_writes_on_failure() -> None: + """A failing write must not leave sibling writes running in the background. + + `_encode_and_write_as_completed` fires one write task per chunk as soon as + its encode completes, then `gather`s them. Plain `gather` (without + `return_exceptions=True`) re-raises the first exception without cancelling + the other in-flight tasks, so a still-running write would keep going after + the caller has already seen the exception -- and its eventual outcome is + never retrieved (an unraisable "Task exception was never retrieved" + warning if it later fails). + """ + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.chunk_utils import ChunkTransform + from zarr.core.codec_pipeline import _encode_and_write_as_completed + from zarr.core.dtype import get_data_type_from_native_dtype + + write_started = asyncio.Event() + write_finished = False + + class _SlowByteSetter: + async def get( + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + return None + + async def set(self, value: Buffer) -> None: + nonlocal write_finished + write_started.set() + await asyncio.sleep(0.2) + write_finished = True + + async def delete(self) -> None: + pass + + async def set_if_not_exists(self, default: Buffer) -> None: + pass + + class _FailingByteSetter: + async def get( + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + return None + + async def set(self, value: Buffer) -> None: + raise RuntimeError("simulated write failure") + + async def delete(self) -> None: + pass + + async def set_if_not_exists(self, default: Buffer) -> None: + pass + + zdtype = get_data_type_from_native_dtype(np.dtype("uint8")) + chunk_spec = ArraySpec( + shape=(1,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + chunk_array = CPUNDBuffer.from_numpy_array(np.zeros(1, dtype="uint8")) + transform = ChunkTransform(codecs=(BytesCodec(),)) + + batch = [ + (_SlowByteSetter(), chunk_array, chunk_spec), + (_FailingByteSetter(), chunk_array, chunk_spec), + ] + + with pytest.raises(RuntimeError, match="simulated write failure"): + await _encode_and_write_as_completed(batch, transform) # type: ignore[arg-type] + + assert write_started.is_set() + # Give the slow write's sleep long enough to finish if it were left + # running unattended in the background instead of being cancelled. + await asyncio.sleep(0.3) + assert not write_finished, "the slow write should have been cancelled, not left running" + + +def test_concurrent_reads_shared_transform_with_pool() -> None: + """Concurrent decode through the shared ChunkTransform produces correct data. + + The transform's `_resolve_specs` cache is shared mutable state. With no + array->array codecs the cache is bypassed entirely, so this uses a transpose + filter to force cache traffic, max_workers=4 so pool workers decode chunks + concurrently, and an outer thread pool so multiple reads are in flight at + once. Each round RE-OPENS the array so the shared transform starts with a + cold spec cache and the concurrent readers race the non-atomic first fill — + reading through a single pre-warmed handle would only ever exercise cache + hits. This pins correctness under concurrency (it cannot prove the absence + of a race, but a torn cache would corrupt results here). + """ + from concurrent.futures import ThreadPoolExecutor + + with zarr_config.set(_FUSED_POOL_CONFIG): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(40, 40), + chunks=(5, 5), + dtype="int32", + filters=[TransposeCodec(order=(1, 0))], + serializer=BytesCodec(), + compressors=None, + fill_value=-1, + ) + data = np.arange(1600, dtype="int32").reshape(40, 40) + arr[:] = data + + for _ in range(5): # several rounds, each racing a cold cache + fresh = zarr.open_array(store=store, mode="r") + + def read_row_block(i: int, handle: zarr.Array[Any] = fresh) -> np.ndarray: + return np.asarray(handle[i * 4 : (i + 1) * 4, :]) + + with ThreadPoolExecutor(max_workers=8) as ex: + futures = {ex.submit(read_row_block, i): i for i in range(10)} + for fut, i in futures.items(): + np.testing.assert_array_equal(fut.result(), data[i * 4 : (i + 1) * 4, :]) + + +def test_shared_transform_decode_alternating_specs() -> None: + """A single ChunkTransform must decode chunks of DIFFERENT specs correctly + when calls alternate, exercising eviction/refill of its single-entry + `_resolve_specs` cache. + + The two specs differ in shape, so each call evicts the other's cached entry. + A transpose filter forces the cache to be used (with no AA codec the cache is + bypassed). The cache entry is stored as one atomic tuple precisely so a + concurrent reader can never observe a key paired with another spec's resolved + chain; this test pins the sequential eviction/refill correctness that + underpins that guarantee. (The concurrent counterpart is + `test_concurrent_reads_shared_transform_with_pool`.) + """ + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.chunk_utils import ChunkTransform + from zarr.core.dtype import get_data_type_from_native_dtype + + def _spec(shape: tuple[int, ...]) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + transform = ChunkTransform(codecs=(TransposeCodec(order=(1, 0)), BytesCodec())) + + # two distinct specs (different shapes) sharing the one transform + cache slot + cases = [] + for shape in [(5, 7), (3, 11)]: + spec = _spec(shape) + arr = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + encoded = transform.encode_chunk(CPUNDBuffer.from_numpy_array(arr), spec) + assert encoded is not None + cases.append((spec, encoded, arr)) + + # Alternate specs so every call evicts and refills the single cache slot. + for i in range(20): + spec, encoded, expected = cases[i % len(cases)] + got = transform.decode_chunk(encoded, spec).as_numpy_array() + np.testing.assert_array_equal(got, expected) + + +def test_sharded_fallback_inner_chunks_avoid_async_transform() -> None: + """Inner chunks of a shard on a NON-sync store decode through the sync + ChunkTransform, not per-chunk AsyncChunkTransform coroutines. + + The sharding byte getters are in-memory dict wrappers; they implement + SyncByteGetter/SyncByteSetter, and the nested inner pipeline is evolved + (so its sync transform exists), letting the nested read/write take the + sync fast path. Without this, every inner chunk pays a coroutine for a + dict lookup plus an async per-chunk transform — measured at 1.5x (raw) to + 3.6x (gzip) of sharded fallback read time. + """ + from unittest.mock import patch + + from zarr.core.codec_pipeline import AsyncChunkTransform + from zarr.testing.store import LatencyStore + + calls = {"decode": 0, "encode": 0} + orig_decode = AsyncChunkTransform.decode_chunk + orig_encode = AsyncChunkTransform.encode_chunk + + async def spy_decode(self: Any, *args: Any, **kwargs: Any) -> Any: + calls["decode"] += 1 + return await orig_decode(self, *args, **kwargs) + + async def spy_encode(self: Any, *args: Any, **kwargs: Any) -> Any: + calls["encode"] += 1 + return await orig_encode(self, *args, **kwargs) + + # LatencyStore is not sync-capable -> the OUTER pipeline takes the async + # fallback; the INNER chunks go over the sharding byte getters. + store = LatencyStore(MemoryStore(), get_latency=0.0, set_latency=0.0) + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + shards=(50,), + dtype="uint8", + compressors=None, + fill_value=0, + ) + if not isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline): + pytest.skip("sync fast path for inner chunks is specific to FusedCodecPipeline") + + data = np.arange(100, dtype="uint8") + sync_calls = {"read_sync": 0} + orig_read_sync = FusedCodecPipeline.read_sync + + def spy_read_sync(self: Any, *args: Any, **kwargs: Any) -> Any: + sync_calls["read_sync"] += 1 + return orig_read_sync(self, *args, **kwargs) + + with ( + patch.object(AsyncChunkTransform, "decode_chunk", spy_decode), + patch.object(AsyncChunkTransform, "encode_chunk", spy_encode), + patch.object(FusedCodecPipeline, "read_sync", spy_read_sync), + ): + arr[:] = data + out = np.asarray(arr[:]) + + np.testing.assert_array_equal(out, data) + assert calls == {"decode": 0, "encode": 0}, ( + f"inner chunks went through per-chunk AsyncChunkTransform coroutines: {calls}" + ) + # The outer store is not sync-capable, so any read_sync calls are the + # NESTED pipeline taking the sync fast path over the sharding byte getters + # (the SyncByteGetter gate). Without the gate, inner chunks go through + # concurrent_map with one coroutine per chunk. (Writes don't appear here: + # the fallback write encodes whole shards through the outer sync transform + # -> ShardingCodec._encode_sync, never touching the nested byte setters.) + assert sync_calls["read_sync"] >= 1, "nested read did not take the sync fast path" + + +def test_write_over_sync_byte_setter_takes_sync_path() -> None: + """`FusedCodecPipeline.write` routes a non-StorePath `SyncByteSetter` (the + sharding codec's `_ShardingByteSetter`) through `write_sync`. + + This is the write-side twin of the SyncByteGetter gate: the read test + above cannot guard it because fallback whole-array writes encode shards + via `_encode_sync` and never touch the nested byte setters. The nested + `write` over `_ShardingByteSetter` is reached from the async shard encode + paths (`_encode_single`/`_encode_partial_single`), so pin the gate + directly: without it, this write degrades to the async fallback (one + coroutine per inner chunk for an in-memory dict store). + """ + import asyncio + from unittest.mock import patch + + from zarr.codecs.sharding import _ShardingByteSetter + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype import get_data_type_from_native_dtype + + zdtype = get_data_type_from_native_dtype(np.dtype("uint8")) + spec = ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + pipeline = FusedCodecPipeline.from_codecs([BytesCodec()]).evolve_from_array_spec(spec) + assert pipeline.sync_transform is not None + + shard_dict: dict[tuple[int, ...], Any] = {} + setter = _ShardingByteSetter(shard_dict, (0,)) + value = default_buffer_prototype().nd_buffer.from_numpy_array(np.arange(10, dtype="uint8")) + + sync_calls = {"write_sync": 0} + orig_write_sync = FusedCodecPipeline.write_sync + + def spy_write_sync(self: Any, *args: Any, **kwargs: Any) -> Any: + sync_calls["write_sync"] += 1 + return orig_write_sync(self, *args, **kwargs) + + sel = (slice(0, 10),) + with patch.object(FusedCodecPipeline, "write_sync", spy_write_sync): + asyncio.run(pipeline.write([(setter, spec, sel, sel, True)], value)) + + assert sync_calls["write_sync"] >= 1, ( + "write over a SyncByteSetter did not take the sync fast path" + ) + written = shard_dict[(0,)] + np.testing.assert_array_equal( + np.frombuffer(written.to_bytes(), dtype="uint8"), np.arange(10, dtype="uint8") + ) + + +# --------------------------------------------------------------------------- +# Async-only codecs inside a shard's inner codec chain +# --------------------------------------------------------------------------- + + +class _AsyncOnlyNoopCodec(BytesBytesCodec): # type: ignore[misc,unused-ignore] + """A no-op BB codec implementing ONLY the async codec interface. + + Deliberately does NOT satisfy `SupportsSyncCodec` (no `_decode_sync` / + `_encode_sync`), modelling a third-party codec that predates the sync + protocol. Class-level counters prove the codec actually ran. + """ + + is_fixed_size = True + encode_calls = 0 + decode_calls = 0 + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-async-only-noop", "configuration": {}} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _AsyncOnlyNoopCodec: + return cls() + + def compute_encoded_size(self, input_byte_length: int, _spec: Any) -> int: + return input_byte_length + + async def _encode_single(self, chunk_bytes: Any, chunk_spec: Any) -> Any: + type(self).encode_calls += 1 + return chunk_bytes + + async def _decode_single(self, chunk_bytes: Any, chunk_spec: Any) -> Any: + type(self).decode_calls += 1 + return chunk_bytes + + +def test_sharded_roundtrip_with_async_only_inner_codec() -> None: + """A sharded array whose INNER codec chain contains an async-only codec + round-trips under FusedCodecPipeline (full write, partial write, full read, + partial read). + + Regression: the pipeline's top-level guard (evolve_from_array_spec -> + sync_transform=None) only inspected the top-level chain. ShardingCodec + structurally satisfies SupportsSyncCodec, so a sync transform was built and + the sync fast path dove into ShardingCodec's sync shard paths, which raised + TypeError from the inner ChunkTransform. The pipeline must instead decline + the sync fast path and fall back to the async inner pipeline, like + BatchedCodecPipeline. + """ + _AsyncOnlyNoopCodec.encode_calls = 0 + _AsyncOnlyNoopCodec.decode_calls = 0 + + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(16, 16), + shards=(8, 8), + chunks=(4, 4), + dtype="int32", + compressors=[_AsyncOnlyNoopCodec()], + fill_value=-1, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + + data = np.arange(256, dtype="int32").reshape(16, 16) + arr[:] = data # full write + np.testing.assert_array_equal(arr[:], data) # full read + np.testing.assert_array_equal(arr[2:11, 3:14], data[2:11, 3:14]) # partial read + + arr[5:7, 5:13] = 0 # partial write (read-merge-write of existing shards) + data[5:7, 5:13] = 0 + np.testing.assert_array_equal(arr[:], data) + + assert _AsyncOnlyNoopCodec.encode_calls > 0, "async-only inner codec never encoded" + assert _AsyncOnlyNoopCodec.decode_calls > 0, "async-only inner codec never decoded" + + # The stored bytes are valid for the default pipeline too: read them back + # under BatchedCodecPipeline (default codec_pipeline.path). Opening from + # metadata needs the codec name in the registry. + from zarr.registry import register_codec + + register_codec("test-async-only-noop", _AsyncOnlyNoopCodec) + reread = zarr.open_array(store=store, mode="r") + np.testing.assert_array_equal(reread[:], data) + + +# --------------------------------------------------------------------------- +# AsyncChunkTransform: the async per-chunk codec chain used on the async +# fallback path. It is the async mirror of ChunkTransform, so it must produce +# identical bytes/arrays. The default (Fused, sync-store) path never uses it; +# these tests drive it directly over multi-codec chains so the aa/bb loops and +# the all-fill drop branch are exercised. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "codecs", + [ + (BytesCodec(),), + (BytesCodec(), GzipCodec(level=1)), + (TransposeCodec(order=(1, 0)), BytesCodec()), + (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec(level=1)), + ], + ids=["bytes-only", "bb", "aa", "aa+ab+bb"], +) +def test_async_chunk_transform_matches_sync(codecs: tuple[Any, ...]) -> None: + """`AsyncChunkTransform.decode_chunk`/`encode_chunk` must round-trip and + produce exactly what the synchronous `ChunkTransform` produces, across + array->array, array->bytes, and bytes->bytes codec combinations. + + This is the async mirror of the codecs the default pipeline runs + synchronously; a divergence here corrupts data only on the async fallback + path (remote stores), which no end-to-end test of the default pipeline + touches. + """ + import asyncio + + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.chunk_utils import ChunkTransform, evolve_codecs + from zarr.core.codec_pipeline import AsyncChunkTransform + from zarr.core.dtype import get_data_type_from_native_dtype + + shape = (4, 4) + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + spec = ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + evolved = evolve_codecs(codecs, spec) + sync_t = ChunkTransform(codecs=evolved) + async_t = AsyncChunkTransform(codecs=evolved) + + data = np.arange(16, dtype="int32").reshape(shape) + value = CPUNDBuffer.from_numpy_array(data) + + sync_bytes = sync_t.encode_chunk(value, spec) + async_bytes = asyncio.run(async_t.encode_chunk(value, spec)) + assert sync_bytes is not None + assert async_bytes is not None + np.testing.assert_array_equal(async_bytes.to_bytes(), sync_bytes.to_bytes()) + + sync_arr = sync_t.decode_chunk(async_bytes, spec) + async_arr = asyncio.run(async_t.decode_chunk(async_bytes, spec)) + np.testing.assert_array_equal(async_arr.as_numpy_array(), sync_arr.as_numpy_array()) + np.testing.assert_array_equal(async_arr.as_numpy_array(), data) + + +def test_async_decode_encode_passes_through_none_chunks() -> None: + """`FusedCodecPipeline.decode`/`encode` (the async batch entry points used + on the fallback path) map a None chunk to None and leave real chunks + untouched — pins the None-passthrough branch the default sync path skips.""" + import asyncio + + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + spec = ArraySpec( + shape=(4,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + pipeline = FusedCodecPipeline.from_codecs([BytesCodec()]).evolve_from_array_spec(spec) + + data = np.arange(4, dtype="int32") + value = CPUNDBuffer.from_numpy_array(data) + + # encode a real chunk and a None chunk together + encoded = list(asyncio.run(pipeline.encode([(value, spec), (None, spec)]))) + assert encoded[1] is None + assert encoded[0] is not None + + # decode the real chunk and a None chunk together + decoded = list(asyncio.run(pipeline.decode([(encoded[0], spec), (None, spec)]))) + assert decoded[1] is None + assert decoded[0] is not None + np.testing.assert_array_equal(decoded[0].as_numpy_array(), data) + + +# --------------------------------------------------------------------------- +# Graceful fallback for partial-mixin codecs without private sync-partial hooks +# +# The public partial-decode/encode contract (`ArrayBytesCodecPartialDecodeMixin` +# / `ArrayBytesCodecPartialEncodeMixin`) only requires the async +# `_decode_partial_single` / `_encode_partial_single`. The fused pipeline must +# route such codecs through its full-chunk sync path instead of asserting on +# the private `_decode_partial_sync` / `_encode_partial_sync` hooks. The double +# below is a minimal conforming implementer of that contract; it guards the +# public extension API, so it must not grow the private sync-partial methods. +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class PartialMixinCodec( + ArrayBytesCodec, ArrayBytesCodecPartialDecodeMixin, ArrayBytesCodecPartialEncodeMixin +): + """Serializer with sync whole-chunk methods plus ONLY async partial methods. + + This is the pre-fused public contract for partial-capable codecs: the + mixins' `_decode_partial_single` / `_encode_partial_single`. It must not + implement `_decode_partial_sync` / `_encode_partial_sync`. + """ + + inner: BytesCodec = field(default_factory=BytesCodec) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> PartialMixinCodec: + return cls() + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-partial-mixin"} + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> PartialMixinCodec: + return replace(self, inner=self.inner.evolve_from_array_spec(array_spec)) + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + return self.inner.compute_encoded_size(input_byte_length, chunk_spec) + + def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + return self.inner._decode_sync(chunk_bytes, chunk_spec) + + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + return self.inner._encode_sync(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + return self._encode_sync(chunk_array, chunk_spec) + + async def _decode_partial_single( + self, byte_getter: Any, selection: Any, chunk_spec: ArraySpec + ) -> NDBuffer | None: + chunk_bytes = await byte_getter.get(prototype=chunk_spec.prototype) + if chunk_bytes is None: + return None + return self._decode_sync(chunk_bytes, chunk_spec)[selection] + + async def _encode_partial_single( + self, byte_setter: Any, chunk_array: NDBuffer, selection: Any, chunk_spec: ArraySpec + ) -> None: + existing = await byte_setter.get(prototype=chunk_spec.prototype) + if existing is None: + full = chunk_spec.prototype.nd_buffer.create( + shape=chunk_spec.shape, + dtype=chunk_spec.dtype.to_native_dtype(), + fill_value=chunk_spec.fill_value, + ) + else: + full = self._decode_sync(existing, chunk_spec) + full[selection] = chunk_array + encoded = self._encode_sync(full, chunk_spec) + assert encoded is not None + await byte_setter.set(encoded) + + +register_codec("test-partial-mixin", PartialMixinCodec) + +_FUSED = {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +_BATCHED = {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"} + + +@pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") +@pytest.mark.parametrize("dtype", ["uint8", "float64"]) +def test_partial_mixin_codec_async_partial_only_round_trip(dtype: str) -> None: + """A serializer advertising the partial mixins with only async partial + methods must round-trip under the fused pipeline: full write, full read, + partial read, partial write, plus cross-pipeline parity with + BatchedCodecPipeline.""" + data = np.arange(64, dtype=dtype).reshape(8, 8) + + with zarr_config.set(_FUSED): + store = MemoryStore() + arr = zarr.create_array( + store, + shape=(8, 8), + chunks=(4, 4), + dtype=dtype, + serializer=PartialMixinCodec(), + compressors=None, + filters=None, + fill_value=0, + ) + + pipeline = arr._async_array.codec_pipeline + assert isinstance(pipeline, FusedCodecPipeline) + assert pipeline.supports_partial_decode + assert pipeline.supports_partial_encode + assert pipeline.sync_transform is not None + + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + np.testing.assert_array_equal(arr[1:5, 2:7], data[1:5, 2:7]) + + expected = data.copy() + expected[2:6, 1:3] = 7 + arr[2:6, 1:3] = expected[2:6, 1:3] + np.testing.assert_array_equal(arr[:], expected) + + with zarr_config.set(_BATCHED): + np.testing.assert_array_equal(zarr.open_array(store, mode="r")[:], expected) + + +# Sync-IO capability gating (`zarr.abc.store._store_supports_sync_io`) +# +# The fused read/write fast paths must engage iff the store advertises the +# FULL synchronous IO surface (get_sync + set_sync + delete_sync): write_sync +# needs get_sync for partial-chunk read-modify-write and delete_sync for +# all-fill chunk cleanup, so gating on any single protocol can crash +# mid-batch. Wrappers must forward the capability of the wrapped store. +# --------------------------------------------------------------------------- + + +class AsyncOnlyStore(Store): + """Dict-backed store implementing only the async `Store` surface (no `*_sync`).""" + + def __init__(self) -> None: + super().__init__(read_only=False) + self._data: dict[str, Buffer] = {} + + def __eq__(self, other: object) -> bool: + return other is self + + @property + def supports_writes(self) -> bool: + return True + + @property + def supports_deletes(self) -> bool: + return True + + @property + def supports_listing(self) -> bool: + return True + + async def get( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + try: + value = self._data[key] + except KeyError: + return None + start, stop = _normalize_byte_range_index(value, byte_range) + return prototype.buffer.from_buffer(value[start:stop]) + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + return [await self.get(key, prototype, byte_range) for key, byte_range in key_ranges] + + async def exists(self, key: str) -> bool: + return key in self._data + + async def set(self, key: str, value: Buffer) -> None: + self._check_writable() + self._data[key] = value + + async def delete(self, key: str) -> None: + self._check_writable() + self._data.pop(key, None) + + async def list(self) -> AsyncIterator[str]: + for key in list(self._data): + yield key + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + for key in list(self._data): + if key.startswith(prefix): + yield key + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + if prefix and not prefix.endswith("/"): + prefix += "/" + seen: set[str] = set() + for key in list(self._data): + if key.startswith(prefix): + head = key.removeprefix(prefix).split("/")[0] + if head not in seen: + seen.add(head) + yield head + + +class SetOnlySyncStore(AsyncOnlyStore): + """Implements `set_sync` but not `get_sync`/`delete_sync` (partial sync surface).""" + + def set_sync(self, key: str, value: Buffer) -> None: + self._check_writable() + self._data[key] = value + + +@pytest.mark.parametrize( + ("store_factory", "expect_sync_path"), + [ + (MemoryStore, True), + (lambda: WrapperStore(MemoryStore()), True), + (lambda: LatencyStore(MemoryStore()), True), + (SetOnlySyncStore, False), + (lambda: WrapperStore(AsyncOnlyStore()), False), + ], + ids=[ + "full-sync", + "wrapper-of-sync", + "latency-wrapper-of-sync", + "set-sync-only", + "wrapper-of-async-only", + ], +) +def test_sync_io_capability_gates_fused_paths( + store_factory: Callable[[], Store], expect_sync_path: bool +) -> None: + """The fused pipeline takes the sync fast path iff the store satisfies + `_store_supports_sync_io`, + and every store round-trips correctly through full writes, partial + (read-modify-write) writes, and all-fill (delete) writes — a store with a + partial sync surface must get a clean async fallback, never a mid-batch + error.""" + from unittest.mock import patch + + store = store_factory() + assert _store_supports_sync_io(store) is expect_sync_path + + calls = {"read_sync": 0, "write_sync": 0} + orig_read_sync = FusedCodecPipeline.read_sync + orig_write_sync = FusedCodecPipeline.write_sync + + def spy_read_sync(self: FusedCodecPipeline, *args: Any, **kwargs: Any) -> Any: + calls["read_sync"] += 1 + return orig_read_sync(self, *args, **kwargs) + + def spy_write_sync(self: FusedCodecPipeline, *args: Any, **kwargs: Any) -> Any: + calls["write_sync"] += 1 + return orig_write_sync(self, *args, **kwargs) + + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + store=store, + shape=(8,), + chunks=(4,), + dtype="uint8", + compressors=None, + fill_value=0, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + with ( + patch.object(FusedCodecPipeline, "read_sync", spy_read_sync), + patch.object(FusedCodecPipeline, "write_sync", spy_write_sync), + ): + data = np.arange(8, dtype="uint8") + arr[:] = data # complete-chunk writes + arr[:3] = 7 # partial write -> read-modify-write needs get + data[:3] = 7 + np.testing.assert_array_equal(arr[:], data) + arr[4:8] = 0 # all-fill chunk -> delete needed + data[4:8] = 0 + np.testing.assert_array_equal(arr[:], data) + + if expect_sync_path: + assert calls["write_sync"] > 0, "sync-capable store did not take the sync write path" + assert calls["read_sync"] > 0, "sync-capable store did not take the sync read path" + else: + assert calls["write_sync"] == 0, "non-sync store took the sync write path" + assert calls["read_sync"] == 0, "non-sync store took the sync read path" diff --git a/tests/test_group.py b/tests/test_group.py index 6f1f4e68fa..f7f2333ef5 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -24,6 +24,7 @@ from zarr.core._info import GroupInfo from zarr.core.buffer import default_buffer_prototype from zarr.core.config import config as zarr_config +from zarr.core.dtype import Float64, Int32 from zarr.core.dtype.common import unpack_dtype_json from zarr.core.dtype.npy.int import UInt8 from zarr.core.group import ( @@ -41,10 +42,11 @@ from zarr.core.metadata.v3 import ArrayV3Metadata from zarr.core.sync import _collect_aiterator, sync from zarr.errors import ( + ArrayNotFoundError, ContainsArrayError, ContainsGroupError, + GroupNotFoundError, MetadataValidationError, - ZarrDeprecationWarning, ZarrUserWarning, ) from zarr.storage import LocalStore, MemoryStore, StorePath, ZipStore @@ -55,19 +57,19 @@ from .conftest import meta_from_array, parse_store if TYPE_CHECKING: + import pathlib from collections.abc import Callable - from _pytest.compat import LEGACY_PATH - from zarr.core.buffer.core import Buffer from zarr.core.common import JSON, ZarrFormat + from zarr.core.dtype import ZDType, ZDTypeLike @pytest.fixture(params=["local", "memory", "zip"]) -async def store(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> Store: - result = await parse_store(request.param, str(tmpdir)) +async def store(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: + result = await parse_store(request.param, str(tmp_path)) if not isinstance(result, Store): - raise TypeError("Wrong store class returned by test fixture! got " + result + " instead") + raise TypeError(f"Wrong store class returned by test fixture! got {result} instead") return result @@ -103,7 +105,7 @@ async def test_create_creates_parents(store: Store, zarr_format: ZarrFormat) -> root = await zarr.api.asynchronous.open_group( store=store, ) - agroup = await root.getitem("a") + agroup = await root.get_group("a") assert agroup.attrs == {"key": "value"} # create a child node with a couple intermediates @@ -151,7 +153,7 @@ def test_group_name_properties( """ root = Group.from_store(store=StorePath(store=store, path=root_name), zarr_format=zarr_format) assert root.path == normalize_path(root_name) - assert root.name == "/" + root.path + assert root.name == f"/{root.path}" assert root.basename == root.path branch = root.create_group(branch_name) @@ -159,7 +161,7 @@ def test_group_name_properties( assert branch.path == normalize_path(branch_name) else: assert branch.path == "/".join([root.path, normalize_path(branch_name)]) - assert branch.name == "/" + branch.path + assert branch.name == f"/{branch.path}" assert branch.basename == branch_name.split("/")[-1] @@ -397,7 +399,7 @@ def test_group_getitem(store: Store, zarr_format: ZarrFormat, consolidated: bool assert group["subgroup"]["subarray"] == subsubarray assert group["subgroup/subarray"] == subsubarray - with pytest.raises(KeyError): + with pytest.raises(KeyError, match="nope"): group["nope"] with pytest.raises(KeyError, match="subarray/subsubarray"): @@ -448,6 +450,77 @@ def test_group_get_with_default(store: Store, zarr_format: ZarrFormat) -> None: assert result.attrs["foo"] == "bar" +def test_group_get_array(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_array` returns the array at the given path, for both direct child names + and nested paths, and the result is statically typed as an Array. + """ + group = Group.from_store(store, zarr_format=zarr_format) + subgroup = group.create_group(name="subgroup") + subarray = group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + subsubarray = subgroup.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + + observed = group.get_array("subarray") + assert isinstance(observed, Array) + assert observed == subarray + assert group.get_array("subgroup/subarray") == subsubarray + + +def test_group_get_array_missing(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_array` raises `ArrayNotFoundError` when no node exists at the given path. + """ + group = Group.from_store(store, zarr_format=zarr_format) + with pytest.raises(ArrayNotFoundError, match="No array found in store"): + group.get_array("missing") + + +def test_group_get_array_wrong_node_type(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_array` raises `ContainsGroupError` when the node at the given path is a + group rather than an array. + """ + group = Group.from_store(store, zarr_format=zarr_format) + group.create_group(name="subgroup") + with pytest.raises(ContainsGroupError, match="A group exists in store"): + group.get_array("subgroup") + + +def test_group_get_group(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_group` returns the group at the given path, for both direct child names + and nested paths, and the result is statically typed as a Group. + """ + group = Group.from_store(store, zarr_format=zarr_format) + subgroup = group.create_group(name="subgroup") + subsubgroup = subgroup.create_group(name="subsubgroup") + + observed = group.get_group("subgroup") + assert isinstance(observed, Group) + assert observed == subgroup + assert group.get_group("subgroup/subsubgroup") == subsubgroup + + +def test_group_get_group_missing(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_group` raises `GroupNotFoundError` when no node exists at the given path. + """ + group = Group.from_store(store, zarr_format=zarr_format) + with pytest.raises(GroupNotFoundError, match="No group found in store"): + group.get_group("missing") + + +def test_group_get_group_wrong_node_type(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_group` raises `ContainsArrayError` when the node at the given path is an + array rather than a group. + """ + group = Group.from_store(store, zarr_format=zarr_format) + group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + with pytest.raises(ContainsArrayError, match="An array exists in store"): + group.get_group("subarray") + + @pytest.mark.parametrize("consolidated", [True, False]) def test_group_delitem(store: Store, zarr_format: ZarrFormat, consolidated: bool) -> None: """ @@ -485,11 +558,11 @@ def test_group_delitem(store: Store, zarr_format: ZarrFormat, consolidated: bool assert group["subarray"] == subarray del group["subgroup"] - with pytest.raises(KeyError): + with pytest.raises(KeyError, match="subgroup"): group["subgroup"] del group["subarray"] - with pytest.raises(KeyError): + with pytest.raises(KeyError, match="subarray"): group["subarray"] @@ -709,13 +782,11 @@ async def test_group_update_attributes_async(store: Store, zarr_format: ZarrForm assert new_group.attrs == new_attrs -@pytest.mark.parametrize("method", ["create_array", "array"]) @pytest.mark.parametrize("name", ["a", "/a"]) def test_group_create_array( store: Store, zarr_format: ZarrFormat, overwrite: bool, - method: Literal["create_array", "array"], name: str, ) -> None: """ @@ -726,36 +797,16 @@ def test_group_create_array( dtype = "uint8" data = np.arange(np.prod(shape)).reshape(shape).astype(dtype) - if method == "create_array": - array = group.create_array(name=name, shape=shape, dtype=dtype) - array[:] = data - elif method == "array": - with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."): - with pytest.warns( - ZarrUserWarning, - match="The `compressor` argument is deprecated. Use `compressors` instead.", - ): - array = group.array(name=name, data=data, shape=shape, dtype=dtype) - else: - raise AssertionError + array = group.create_array(name=name, shape=shape, dtype=dtype) + array[:] = data if not overwrite: - if method == "create_array": - with pytest.raises(ContainsArrayError): # noqa: PT012 - a = group.create_array(name=name, shape=shape, dtype=dtype) - a[:] = data - elif method == "array": - with pytest.raises(ContainsArrayError): # noqa: PT012 - with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."): - with pytest.warns( - ZarrUserWarning, - match="The `compressor` argument is deprecated. Use `compressors` instead.", - ): - a = group.array(name=name, shape=shape, dtype=dtype) - a[:] = data + with pytest.raises(ContainsArrayError): # noqa: PT012 + a = group.create_array(name=name, shape=shape, dtype=dtype) + a[:] = data assert array.path == normalize_path(name) - assert array.name == "/" + array.path + assert array.name == f"/{array.path}" assert array.shape == shape assert array.dtype == np.dtype(dtype) assert np.array_equal(array[:], data) @@ -1084,7 +1135,7 @@ async def test_asyncgroup_getitem(store: Store, zarr_format: ZarrFormat) -> None assert await agroup.getitem(sub_group_path) == sub_group # check that asking for a nonexistent key raises KeyError - with pytest.raises(KeyError): + with pytest.raises(KeyError, match="foo"): await agroup.getitem("foo") @@ -1105,10 +1156,10 @@ async def test_asyncgroup_delitem(store: Store, zarr_format: ZarrFormat) -> None # todo: clean up the code duplication here if zarr_format == 2: - assert not await agroup.store_path.store.exists(array_name + "/" + ".zarray") - assert not await agroup.store_path.store.exists(array_name + "/" + ".zattrs") + assert not await agroup.store_path.store.exists(f"{array_name}/.zarray") + assert not await agroup.store_path.store.exists(f"{array_name}/.zattrs") elif zarr_format == 3: - assert not await agroup.store_path.store.exists(array_name + "/" + "zarr.json") + assert not await agroup.store_path.store.exists(f"{array_name}/zarr.json") else: raise AssertionError @@ -1116,10 +1167,10 @@ async def test_asyncgroup_delitem(store: Store, zarr_format: ZarrFormat) -> None _ = await agroup.create_group(sub_group_path, attributes={"foo": 100}) await agroup.delitem(sub_group_path) if zarr_format == 2: - assert not await agroup.store_path.store.exists(array_name + "/" + ".zgroup") - assert not await agroup.store_path.store.exists(array_name + "/" + ".zattrs") + assert not await agroup.store_path.store.exists(f"{array_name}/.zgroup") + assert not await agroup.store_path.store.exists(f"{array_name}/.zattrs") elif zarr_format == 3: - assert not await agroup.store_path.store.exists(array_name + "/" + "zarr.json") + assert not await agroup.store_path.store.exists(f"{array_name}/zarr.json") else: raise AssertionError @@ -1136,7 +1187,7 @@ async def test_asyncgroup_create_group( assert isinstance(subgroup, AsyncGroup) assert subgroup.path == normalize_path(name) - assert subgroup.name == "/" + subgroup.path + assert subgroup.name == f"/{subgroup.path}" assert subgroup.attrs == attributes assert subgroup.store_path.path == subgroup.path assert subgroup.store_path.store == store @@ -1176,9 +1227,7 @@ async def test_asyncgroup_create_array( assert subnode.store_path.store == store assert subnode.shape == shape assert subnode.dtype == dtype - # todo: fix the type annotation of array.metadata.chunk_grid so that we get some autocomplete - # here. - assert subnode.metadata.chunk_grid.chunk_shape == chunk_shape + assert subnode._chunk_grid.chunk_shape == chunk_shape assert subnode.metadata.zarr_format == zarr_format @@ -1342,7 +1391,7 @@ async def test_require_group(store: LocalStore | MemoryStore, zarr_format: ZarrF # await root.require_group("foo", overwrite=True) # test that requiring a group where an array is fails - with pytest.raises(TypeError): + with pytest.raises(TypeError, match="Incompatible object"): await foo_group.require_group("bar") @@ -1367,38 +1416,6 @@ async def test_require_groups(store: LocalStore | MemoryStore, zarr_format: Zarr assert no_group == () -def test_create_dataset_with_data(store: Store, zarr_format: ZarrFormat) -> None: - """Check that deprecated create_dataset method allows input data. - - See https://github.com/zarr-developers/zarr-python/issues/2631. - """ - root = Group.from_store(store=store, zarr_format=zarr_format) - arr = np.random.random((5, 5)) - with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."): - data = root.create_dataset("random", data=arr, shape=arr.shape) - np.testing.assert_array_equal(np.asarray(data), arr) - - -async def test_create_dataset(store: Store, zarr_format: ZarrFormat) -> None: - root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) - with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."): - foo = await root.create_dataset("foo", shape=(10,), dtype="uint8") - assert foo.shape == (10,) - - with ( - pytest.raises(ContainsArrayError), - pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."), - ): - await root.create_dataset("foo", shape=(100,), dtype="int8") - - _ = await root.create_group("bar") - with ( - pytest.raises(ContainsGroupError), - pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."), - ): - await root.create_dataset("bar", shape=(100,), dtype="int8") - - async def test_require_array(store: Store, zarr_format: ZarrFormat) -> None: root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) foo1 = await root.require_array("foo", shape=(10,), dtype="i8", attributes={"foo": 101}) @@ -1424,6 +1441,29 @@ async def test_require_array(store: Store, zarr_format: ZarrFormat) -> None: await root.require_array("bar", shape=(10,), dtype="int8") +@pytest.mark.parametrize( + ("dtype", "expected"), + [ + (Int32(), Int32()), + (np.dtype("int32"), Int32()), + ("int32", Int32()), + (None, Float64()), + ], + ids=["zdtype", "numpy", "str", "none"], +) +async def test_require_array_zdtype( + store: Store, zarr_format: ZarrFormat, dtype: ZDTypeLike | None, expected: ZDType[Any, Any] +) -> None: + """An existing array can be required with a ZDType, as well as a string, a NumPy dtype, + or None. See https://github.com/zarr-developers/zarr-python/issues/3377 + """ + root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + await root.create_array("foo", shape=(10,), dtype=expected) + + foo = await root.require_array("foo", shape=(10,), dtype=dtype, exact=True) + assert foo._zdtype == expected + + @pytest.mark.parametrize("consolidate", [True, False]) async def test_members_name(store: Store, consolidate: bool, zarr_format: ZarrFormat): group = Group.from_store(store=store, zarr_format=zarr_format) @@ -1527,7 +1567,7 @@ async def test_group_getitem_consolidated(self, store: Store) -> None: # On disk, we've consolidated all the metadata in the root zarr.json group = await zarr.api.asynchronous.open(store=store) - rg0 = await group.getitem("g0") + rg0 = await group.get_group("g0") expected = ConsolidatedMetadata( metadata={ @@ -1548,10 +1588,10 @@ async def test_group_getitem_consolidated(self, store: Store) -> None: ) assert rg0.metadata.consolidated_metadata == expected - rg1 = await rg0.getitem("g1") + rg1 = await rg0.get_group("g1") assert rg1.metadata.consolidated_metadata == expected.metadata["g1"].consolidated_metadata - rg2 = await rg1.getitem("g2") + rg2 = await rg1.get_group("g2") assert rg2.metadata.consolidated_metadata == ConsolidatedMetadata(metadata={}) async def test_group_delitem_consolidated(self, store: Store) -> None: @@ -1708,7 +1748,7 @@ def test_delitem_removes_children(store: Store, zarr_format: ZarrFormat) -> None arr = g1.create_array("0/0/0", shape=(1,), dtype="uint8") arr[:] = 1 del g1["0"] - with pytest.raises(KeyError): + with pytest.raises(KeyError, match="0/0"): g1["0/0"] @@ -1771,6 +1811,9 @@ def test_create_nodes_concurrency_limit(store: MemoryStore) -> None: (zarr.core.group.create_rooted_hierarchy, zarr.core.sync_group.create_rooted_hierarchy), (zarr.core.group.get_node, zarr.core.sync_group.get_node), ], + # The default ids (from __name__) collide: the method pair and the module-level pair + # for create_hierarchy would both be id'd "create_hierarchy-create_hierarchy". + ids=lambda func: f"{func.__module__.rsplit('.', maxsplit=1)[-1]}.{func.__qualname__}", ) def test_consistent_signatures( a_func: Callable[[object], object], b_func: Callable[[object], object] diff --git a/tests/test_indexing.py b/tests/test_indexing.py index 9c734fb0c3..04fbdad8c6 100644 --- a/tests/test_indexing.py +++ b/tests/test_indexing.py @@ -11,10 +11,13 @@ from numpy.testing import assert_array_equal import zarr +from tests.conftest import Expect, ExpectFail from zarr import Array from zarr.core.buffer import default_buffer_prototype +from zarr.core.chunk_grids import ChunkGrid from zarr.core.indexing import ( BasicSelection, + CoordinateIndexer, CoordinateSelection, OrthogonalSelection, Selection, @@ -102,6 +105,7 @@ def set_sync(self, key: str, value: Buffer) -> None: def test_normalize_integer_selection() -> None: + """normalize_integer_selection handles positive/negative indices and raises IndexError for out-of-bounds values.""" assert 1 == normalize_integer_selection(1, 100) assert 99 == normalize_integer_selection(-1, 100) with pytest.raises(IndexError): @@ -113,6 +117,7 @@ def test_normalize_integer_selection() -> None: def test_replace_ellipsis() -> None: + """replace_ellipsis expands Ellipsis to full slice(None) selections for 1D and 2D shapes.""" # 1D, single item assert (0,) == replace_ellipsis(0, (100,)) @@ -155,20 +160,23 @@ def test_replace_ellipsis() -> None: [ (42, "uint8"), pytest.param( - (b"aaa", 1, 4.2), [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], marks=pytest.mark.xfail + (b"aaa", 1, 4.2), + [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], + marks=pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning"), ), ], ) @pytest.mark.parametrize("use_out", [True, False]) def test_get_basic_selection_0d(store: StorePath, use_out: bool, value: Any, dtype: Any) -> None: + """get_basic_selection on a 0-dimensional array returns the scalar value via Ellipsis and (), including the `out` buffer path.""" # setup arr_np = np.array(value, dtype=dtype) arr_z = zarr_array_from_numpy_array(store, arr_np) assert_array_equal(arr_np, arr_z.get_basic_selection(Ellipsis)) assert_array_equal(arr_np, arr_z[...]) - assert value == arr_z.get_basic_selection(()) - assert value == arr_z[()] + assert arr_np[()] == arr_z.get_basic_selection(()) + assert arr_np[()] == arr_z[()] if use_out: # test out param @@ -201,77 +209,70 @@ def test_get_basic_selection_0d(store: StorePath, use_out: bool, value: Any, dty # assert_array_equal(a[["foo", "bar"]], c) -basic_selections_1d: list[BasicSelection] = [ - # single value - 42, - -1, - # slices - slice(0, 1050), - slice(50, 150), - slice(0, 2000), - slice(-150, -50), - slice(-2000, 2000), - slice(0, 0), # empty result - slice(-1, 0), # empty result - # total selections - slice(None), - Ellipsis, - (), - (Ellipsis, slice(None)), - # slice with step - slice(None), - slice(None, None), - slice(None, None, 1), - slice(None, None, 10), - slice(None, None, 100), - slice(None, None, 1000), - slice(None, None, 10000), - slice(0, 1050), - slice(0, 1050, 1), - slice(0, 1050, 10), - slice(0, 1050, 100), - slice(0, 1050, 1000), - slice(0, 1050, 10000), - slice(1, 31, 3), - slice(1, 31, 30), - slice(1, 31, 300), - slice(81, 121, 3), - slice(81, 121, 30), - slice(81, 121, 300), - slice(50, 150), - slice(50, 150, 1), - slice(50, 150, 10), +_BASIC_1D_CASES: list[Expect[BasicSelection, None]] = [ + Expect(input=5, output=None, id="single-positive"), + Expect(input=-1, output=None, id="single-negative"), + Expect(input=slice(3, 18), output=None, id="bounded-slice"), + Expect(input=slice(0, 100), output=None, id="over-bounds-slice"), + Expect(input=slice(-18, -3), output=None, id="negative-slice"), + Expect(input=slice(0, 0), output=None, id="empty-slice"), + Expect(input=slice(-1, 0), output=None, id="empty-negative-slice"), + Expect(input=slice(None), output=None, id="full-slice"), + Expect(input=Ellipsis, output=None, id="ellipsis"), + Expect(input=(), output=None, id="empty-tuple"), + Expect(input=(Ellipsis, slice(None)), output=None, id="ellipsis-slice"), + Expect(input=slice(None, None, 3), output=None, id="stride-3"), + Expect(input=slice(3, 27, 5), output=None, id="bounded-stride"), ] -basic_selections_1d_bad = [ - # only positive step supported - slice(None, None, -1), - slice(None, None, -10), - slice(None, None, -100), - slice(None, None, -1000), - slice(None, None, -10000), - slice(1050, -1, -1), - slice(1050, -1, -10), - slice(1050, -1, -100), - slice(1050, -1, -1000), - slice(1050, -1, -10000), - slice(1050, 0, -1), - slice(1050, 0, -10), - slice(1050, 0, -100), - slice(1050, 0, -1000), - slice(1050, 0, -10000), - slice(150, 50, -1), - slice(150, 50, -10), - slice(31, 1, -3), - slice(121, 81, -3), - slice(-1, 0, -1), - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), +_BASIC_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=slice(None, None, -1), + exception=IndexError, + id="negative-step", + msg="only slices with step >= 1 are supported", + ), + ExpectFail( + input=2.3, + exception=IndexError, + id="float", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + # get_basic_selection and z[...] word their errors differently for a string + # selection, so this case asserts only the exception type (msg=None). + ExpectFail( + input="foo", + exception=IndexError, + id="string", + msg=None, + ), + ExpectFail( + input=b"xxx", + exception=IndexError, + id="bytes", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=None, + exception=IndexError, + id="none", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=(0, 0), + exception=IndexError, + id="tuple-too-many", + msg="too many indices for array; expected 1, got 2", + ), + ExpectFail( + input=(slice(None), slice(None)), + exception=IndexError, + id="two-slices", + msg="too many indices for array; expected 1, got 2", + ), ] @@ -292,99 +293,133 @@ def _test_get_basic_selection( assert_array_equal(expect, b.as_numpy_array()) -# noinspection PyStatementEffect -def test_get_basic_selection_1d(store: StorePath) -> None: - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) +@pytest.mark.parametrize("case", _BASIC_1D_CASES, ids=lambda c: c.id) +def test_get_basic_selection_1d(store: StorePath, case: Expect[BasicSelection, None]) -> None: + """Basic getitem on a 1D array matches numpy for ints, slices, strides, and full selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_basic_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _BASIC_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_basic_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """Basic getitem on a 1D array rejects negative steps and invalid index types with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_basic_selection(case.input) + with case.raises(): + z[case.input] + + +_BASIC_2D_CASES: list[Expect[BasicSelection, None]] = [ + Expect(input=5, output=None, id="single-row"), + Expect(input=-1, output=None, id="single-row-neg"), + Expect(input=(5, slice(None)), output=None, id="row-and-full-col"), + Expect(input=(slice(None), 3), output=None, id="single-col"), + Expect(input=(slice(None), -1), output=None, id="single-col-neg"), + Expect(input=slice(None), output=None, id="full"), + Expect(input=slice(2, 9), output=None, id="row-slice"), + Expect(input=slice(0, 0), output=None, id="empty-row-slice"), + Expect(input=(slice(2, 9), slice(1, 4)), output=None, id="2d-slice"), + Expect(input=(slice(0, 12, 3), slice(0, 5, 2)), output=None, id="strided-2d-slice"), + Expect(input=Ellipsis, output=None, id="ellipsis"), + Expect(input=(), output=None, id="empty-tuple"), +] - for selection in basic_selections_1d: - _test_get_basic_selection(a, z, selection) +_BASIC_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=2.3, + exception=IndexError, + id="float", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input="foo", + exception=IndexError, + id="string", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=None, + exception=IndexError, + id="none", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=(2.3, slice(None)), + exception=IndexError, + id="float-in-tuple", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=slice(None, None, -1), + exception=IndexError, + id="negative-step", + msg="only slices with step >= 1 are supported", + ), + ExpectFail( + input=(slice(None), slice(None), slice(None)), + exception=IndexError, + id="too-many-dims", + msg="too many indices for array; expected 2, got 3", + ), + ExpectFail( + input=[0, 1], + exception=IndexError, + id="integer-list", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), +] - for selection_bad in basic_selections_1d_bad: - with pytest.raises(IndexError): - z.get_basic_selection(selection_bad) # type: ignore[arg-type] - with pytest.raises(IndexError): - z[selection_bad] # type: ignore[index] - with pytest.raises(IndexError): - z.get_basic_selection([1, 0]) # type: ignore[arg-type] - - -basic_selections_2d: list[BasicSelection] = [ - # single row - 42, - -1, - (42, slice(None)), - (-1, slice(None)), - # single col - (slice(None), 4), - (slice(None), -1), - # row slices - slice(None), - slice(0, 1000), - slice(250, 350), - slice(0, 2000), - slice(-350, -250), - slice(0, 0), # empty result - slice(-1, 0), # empty result - slice(-2000, 0), - slice(-2000, 2000), - # 2D slices - (slice(None), slice(1, 5)), - (slice(250, 350), slice(None)), - (slice(250, 350), slice(1, 5)), - (slice(250, 350), slice(-5, -1)), - (slice(250, 350), slice(-50, 50)), - (slice(250, 350, 10), slice(1, 5)), - (slice(250, 350), slice(1, 5, 2)), - (slice(250, 350, 33), slice(1, 5, 3)), - # total selections - (slice(None), slice(None)), - Ellipsis, - (), - (Ellipsis, slice(None)), - (Ellipsis, slice(None), slice(None)), -] +@pytest.mark.parametrize("case", _BASIC_2D_CASES, ids=lambda c: c.id) +def test_get_basic_selection_2d(store: StorePath, case: Expect[BasicSelection, None]) -> None: + """Basic getitem on a 2D array matches numpy for rows, cols, slices, and strides.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_basic_selection(a, z, case.input) -basic_selections_2d_bad = [ - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (2.3, slice(None)), - # only positive step supported - slice(None, None, -1), - (slice(None, None, -1), slice(None)), - (0, 0, 0), - (slice(None), slice(None), slice(None)), -] +@pytest.mark.parametrize("case", _BASIC_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_basic_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """Basic getitem on a 2D array rejects malformed selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_basic_selection(case.input) -# noinspection PyStatementEffect -def test_get_basic_selection_2d(store: StorePath) -> None: - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - for selection in basic_selections_2d: - _test_get_basic_selection(a, z, selection) +def test_basic_2d_fancy_fallback(store: StorePath) -> None: + """Indexing a 2D array with paired integer lists falls back to fancy (vectorized) indexing.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + np.testing.assert_array_equal(z[([0, 1], [0, 1])], a[([0, 1], [0, 1])]) - bad_selections = basic_selections_2d_bad + [ - # integer arrays - [0, 1], - (slice(None), [0, 1]), - ] - for selection_bad in bad_selections: - with pytest.raises(IndexError): - z.get_basic_selection(selection_bad) # type: ignore[arg-type] - # check fallback on fancy indexing - fancy_selection = ([0, 1], [0, 1]) - np.testing.assert_array_equal(z[fancy_selection], [0, 11]) + +def test_get_basic_selection_1d_rejects_integer_list(store: StorePath) -> None: + """get_basic_selection on a 1D array rejects an integer list (basic indexing is int/slice only).""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with pytest.raises(IndexError, match="unsupported selection item for basic indexing"): + z.get_basic_selection([1, 0]) + + +def test_get_basic_selection_2d_rejects_list_in_tuple(store: StorePath) -> None: + """get_basic_selection on a 2D array rejects a list nested in an index tuple.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with pytest.raises(IndexError, match="unsupported selection item for basic indexing"): + z.get_basic_selection((slice(None), [0, 1])) def test_fancy_indexing_fallback_on_get_setitem(store: StorePath) -> None: + """Paired integer-list indexing falls back to vectorized (fancy) get and set via `__getitem__`/`__setitem__`.""" z = zarr_array_from_numpy_array(store, np.zeros((20, 20))) z[[1, 2, 3], [1, 2, 3]] = 1 np.testing.assert_array_equal( @@ -443,8 +478,28 @@ def test_orthogonal_indexing_fallback_on_getitem_2d( np.testing.assert_array_equal(z[index], expected_result) +def test_setitem_zarr_array_as_value() -> None: + """Assigning a zarr array as a value in `__setitem__` does not raise a SyncError (regression for GH3611).""" + # Regression test for https://github.com/zarr-developers/zarr-python/issues/3611 + # Assigning a zarr Array as the value used to raise + # SyncError("Calling sync() from within a running loop") because the codec + # pipeline tried to index the zarr array inside an already-running async loop. + src = zarr.array(np.arange(10), chunks=(5,)) + dst = zarr.zeros(10, chunks=(5,), dtype=src.dtype) + + # Full assignment + dst[:] = src + assert_array_equal(dst[:], np.arange(10)) + + # Slice assignment + dst2 = zarr.zeros(10, chunks=(5,), dtype=src.dtype) + dst2[2:7] = src[2:7] + assert_array_equal(dst2[2:7], np.arange(2, 7)) + + @pytest.mark.skip(reason="fails on ubuntu, windows; numpy=2.2; in CI") def test_setitem_repeated_index(): + """oindex assignment with repeated indices writes the last value for each duplicated index position.""" array = zarr.array(data=np.zeros((4,)), chunks=(1,)) indexer = np.array([-1, -1, 0, 0]) array.oindex[(indexer,)] = [0, 1, 2, 3] @@ -530,6 +585,7 @@ def test_orthogonal_indexing_fallback_on_setitem_2d( def test_fancy_indexing_doesnt_mix_with_implicit_slicing(store: StorePath) -> None: + """Fancy indexing that would require implicit slicing over an unspecified axis raises IndexError on a 3D array.""" z2 = zarr_array_from_numpy_array(store, np.zeros((5, 5, 5))) with pytest.raises(IndexError): z2[[1, 2, 3], [1, 2, 3]] = 2 @@ -546,24 +602,27 @@ def test_fancy_indexing_doesnt_mix_with_implicit_slicing(store: StorePath) -> No [ (42, "uint8"), pytest.param( - (b"aaa", 1, 4.2), [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], marks=pytest.mark.xfail + (b"aaa", 1, 4.2), + [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], + marks=pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning"), ), ], ) def test_set_basic_selection_0d( store: StorePath, value: Any, dtype: str | list[tuple[str, str]] ) -> None: + """set_basic_selection and `__setitem__` write scalar values correctly to a 0-dimensional array.""" arr_np = np.array(value, dtype=dtype) arr_np_zeros = np.zeros_like(arr_np, dtype=dtype) arr_z = zarr_array_from_numpy_array(store, arr_np_zeros) assert_array_equal(arr_np_zeros, arr_z) arr_z.set_basic_selection(Ellipsis, value) - assert_array_equal(value, arr_z) - arr_z[...] = 0 + assert_array_equal(arr_np, arr_z) + arr_z[...] = arr_np_zeros[()] assert_array_equal(arr_np_zeros, arr_z) arr_z[...] = value - assert_array_equal(value, arr_z) + assert_array_equal(arr_np, arr_z) # todo: uncomment the structured array tests when we can make them pass, # or delete them if we formally decide not to support structured dtypes. @@ -593,187 +652,279 @@ def _test_get_orthogonal_selection( assert_array_equal(expect, actual) -# noinspection PyStatementEffect -def test_get_orthogonal_selection_1d_bool(store: StorePath) -> None: - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_get_orthogonal_selection(a, z, ix) - - # test errors - with pytest.raises(IndexError): - z.oindex[np.zeros(50, dtype=bool)] # too short - with pytest.raises(IndexError): - z.oindex[np.zeros(2000, dtype=bool)] # too long - with pytest.raises(IndexError): - # too many dimensions - z.oindex[[[True, False], [False, True]]] # type: ignore[index] - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_1d_int(store: StorePath) -> None: - # setup - a = np.arange(550, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.01: - # sorted integer arrays - ix = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix.sort() - _test_get_orthogonal_selection(a, z, ix) - - selections = basic_selections_1d + [ - # test wraparound - [0, 3, 10, -23, -12, -1], - # explicit test not sorted - [3, 105, 23, 127], - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) +_ORTHO_1D_BOOL_CASES: list[Expect[OrthogonalSelection, None]] = [ + Expect(input=np.zeros(30, dtype=bool), output=None, id="empty-mask"), + Expect(input=np.ones(30, dtype=bool), output=None, id="full-mask"), + Expect(input=np.arange(30) % 2 == 0, output=None, id="alternating-mask"), + Expect(input=np.arange(30) == 7, output=None, id="single-true"), + Expect( + input=np.isin(np.arange(30), [0, 1, 8, 15, 29]), + output=None, + id="sparse-cross-chunk", + ), +] - bad_selections = basic_selections_1d_bad + [ - [a.shape[0] + 1], # out of bounds - [-(a.shape[0] + 1)], # out of bounds - [[2, 4], [6, 8]], # too many dimensions - ] - for bad_selection in bad_selections: - with pytest.raises(IndexError): - z.get_orthogonal_selection(bad_selection) # type: ignore[arg-type] - with pytest.raises(IndexError): - z.oindex[bad_selection] # type: ignore[index] +_ORTHO_1D_BOOL_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=np.zeros(5, dtype=bool), + exception=IndexError, + id="mask-too-short", + msg="wrong length for dimension; expected 30, got 5", + ), + ExpectFail( + input=np.zeros(50, dtype=bool), + exception=IndexError, + id="mask-too-long", + msg="wrong length for dimension; expected 30, got 50", + ), + ExpectFail( + input=[[True, False], [False, True]], + exception=IndexError, + id="mask-too-many-dims", + msg="must be 1-dimensional only", + ), +] -def _test_get_orthogonal_selection_2d( - a: npt.NDArray[Any], z: Array, ix0: npt.NDArray[np.bool], ix1: npt.NDArray[np.bool] +@pytest.mark.parametrize("case", _ORTHO_1D_BOOL_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_bool( + store: StorePath, case: Expect[OrthogonalSelection, None] ) -> None: - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice - (ix0, slice(1, 5)), - (ix0, slice(1, 5, 2)), - (slice(250, 350), ix1), - (slice(250, 350, 10), ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_2d(store: StorePath) -> None: - # setup - a = np.arange(5400, dtype=int).reshape(600, 9) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) + """oindex with a 1D boolean mask matches numpy across chunk boundaries.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_orthogonal_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _ORTHO_1D_BOOL_BAD_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_bool_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """oindex rejects masks of the wrong length or dimensionality with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.oindex[case.input] + + +_ORTHO_1D_INT_CASES: list[Expect[OrthogonalSelection, None]] = [ + Expect(input=[0, 8, 15, 29], output=None, id="sorted"), + Expect(input=[3, 29, 1, 16], output=None, id="unsorted"), + Expect(input=[2, 2, 8, 8], output=None, id="duplicates"), + Expect(input=[0, 3, 10, -23, -12, -1], output=None, id="wraparound"), + Expect(input=[15], output=None, id="single"), +] - # mixed int array / bool array - selections = ( - (ix0, np.nonzero(ix1)[0]), - (np.nonzero(ix0)[0], ix1), - ) - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) +_ORTHO_1D_INT_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=[31], + exception=IndexError, + id="out-of-bounds-high", + msg="index out of bounds for dimension with length 30", + ), + ExpectFail( + input=[-31], + exception=IndexError, + id="out-of-bounds-low", + msg="index out of bounds for dimension with length 30", + ), + ExpectFail( + input=[[2, 4], [6, 8]], + exception=IndexError, + id="too-many-dims", + msg="integer arrays in an orthogonal selection must be 1-dimensional only", + ), +] - # sorted integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix0.sort() - ix1.sort() - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - for selection_2d in basic_selections_2d: - _test_get_orthogonal_selection(a, z, selection_2d) +@pytest.mark.parametrize("case", _ORTHO_1D_INT_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_int( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """oindex with a 1D integer array matches numpy, including wraparound and duplicates.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_orthogonal_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _ORTHO_1D_INT_BAD_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_int_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """oindex rejects out-of-bounds or multi-dimensional integer selections with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_orthogonal_selection(case.input) + with case.raises(): + z.oindex[case.input] + + +_ORTHO_2D_IX0_BOOL = np.isin(np.arange(12), [0, 5, 11]) # rows 0, 5, 11 +_ORTHO_2D_IX1_BOOL = np.array([True, False, True, False, True]) # cols 0, 2, 4 +_ORTHO_2D_IX0_INT = np.array([0, 5, 11]) +_ORTHO_2D_IX1_INT = np.array([0, 2, 4]) + +_ORTHO_2D_CASES: list[Expect[OrthogonalSelection, None]] = [ + Expect(input=(_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_BOOL), output=None, id="both-bool"), + Expect(input=(_ORTHO_2D_IX0_BOOL, slice(1, 4)), output=None, id="bool-slice"), + Expect(input=(_ORTHO_2D_IX0_BOOL, slice(0, 5, 2)), output=None, id="bool-strided-slice"), + Expect(input=(slice(2, 9), _ORTHO_2D_IX1_BOOL), output=None, id="slice-bool"), + Expect(input=(slice(0, 12, 4), _ORTHO_2D_IX1_BOOL), output=None, id="strided-slice-bool"), + Expect(input=(_ORTHO_2D_IX0_BOOL, 3), output=None, id="bool-int"), + Expect(input=(7, _ORTHO_2D_IX1_BOOL), output=None, id="int-bool"), + Expect(input=(_ORTHO_2D_IX0_INT, _ORTHO_2D_IX1_INT), output=None, id="both-int"), + Expect(input=(_ORTHO_2D_IX0_INT, _ORTHO_2D_IX1_BOOL), output=None, id="int-array-bool-array"), + Expect(input=(_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_INT), output=None, id="bool-array-int-array"), + Expect(input=7, output=None, id="single-row"), + Expect(input=(slice(None), 3), output=None, id="single-col"), + Expect(input=(slice(None), slice(None)), output=None, id="full"), + Expect(input=slice(2, 9), output=None, id="row-slice"), +] - for selection_2d_bad in basic_selections_2d_bad: - with pytest.raises(IndexError): - z.get_orthogonal_selection(selection_2d_bad) # type: ignore[arg-type] - with pytest.raises(IndexError): - z.oindex[selection_2d_bad] # type: ignore[index] +_ORTHO_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=2.3, + exception=IndexError, + id="float-index", + msg="unsupported selection item for orthogonal indexing", + ), + # get_orthogonal_selection and oindex raise different messages for a string + # selection, so assert only the exception type. + ExpectFail( + input="foo", + exception=IndexError, + id="string-index", + msg=None, + ), + ExpectFail( + input=None, + exception=IndexError, + id="none-index", + msg="unsupported selection item for orthogonal indexing", + ), + ExpectFail( + input=slice(None, None, -1), + exception=IndexError, + id="negative-step", + msg="only slices with step >= 1 are supported", + ), + ExpectFail( + input=(0, 0, 0), + exception=IndexError, + id="too-many-dims", + msg="too many indices for array", + ), +] -def _test_get_orthogonal_selection_3d( - a: npt.NDArray, - z: Array, - ix0: npt.NDArray[np.bool], - ix1: npt.NDArray[np.bool], - ix2: npt.NDArray[np.bool], +@pytest.mark.parametrize("case", _ORTHO_2D_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_2d( + store: StorePath, case: Expect[OrthogonalSelection, None] ) -> None: - selections = [ - # single value - (60, 15, 4), - (-1, -1, -1), - # index all axes with array - (ix0, ix1, ix2), - # mixed indexing with single array / slices - (ix0, slice(10, 20), slice(1, 5)), - (slice(30, 50), ix1, slice(1, 5)), - (slice(30, 50), slice(10, 20), ix2), - (ix0, slice(10, 20, 5), slice(1, 5, 2)), - (slice(30, 50, 3), ix1, slice(1, 5, 2)), - (slice(30, 50, 3), slice(10, 20, 5), ix2), - # mixed indexing with single array / ints - (ix0, 15, 4), - (60, ix1, 4), - (60, 15, ix2), - # mixed indexing with single array / slice / int - (ix0, slice(10, 20), 4), - (15, ix1, slice(1, 5)), - (slice(30, 50), 15, ix2), - # mixed indexing with two array / slice - (ix0, ix1, slice(1, 5)), - (slice(30, 50), ix1, ix2), - (ix0, slice(10, 20), ix2), - # mixed indexing with two array / integer - (ix0, ix1, 4), - (15, ix1, ix2), - (ix0, 15, ix2), - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) + """oindex on a 2D array matches numpy for array/slice/int combinations per axis.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_orthogonal_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _ORTHO_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """oindex on a 2D array rejects malformed selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_orthogonal_selection(case.input) + with case.raises(): + z.oindex[case.input] + + +_ORTHO_3D_IX0_BOOL = np.isin(np.arange(7), [0, 3, 6]) # axis 0 +_ORTHO_3D_IX1_BOOL = np.isin(np.arange(6), [0, 2, 5]) # axis 1 +_ORTHO_3D_IX2_BOOL = np.isin(np.arange(10), [0, 4, 9]) # axis 2 +_ORTHO_3D_IX0_INT = np.array([0, 3, 6]) +_ORTHO_3D_IX1_INT = np.array([0, 2, 5]) +_ORTHO_3D_IX2_INT = np.array([0, 4, 9]) + +_ORTHO_3D_CASES: list[Expect[OrthogonalSelection, None]] = [ + # single value + Expect(input=(5, 3, 8), output=None, id="single-value"), + Expect(input=(-1, -1, -1), output=None, id="all-negative"), + # index all axes with arrays + Expect( + input=(_ORTHO_3D_IX0_BOOL, _ORTHO_3D_IX1_BOOL, _ORTHO_3D_IX2_BOOL), + output=None, + id="three-bool-arrays", + ), + Expect( + input=(_ORTHO_3D_IX0_INT, _ORTHO_3D_IX1_INT, _ORTHO_3D_IX2_INT), + output=None, + id="three-int-arrays", + ), + # mixed indexing with single array / slices + Expect( + input=(_ORTHO_3D_IX0_BOOL, slice(1, 5), slice(2, 9)), output=None, id="array-slice-slice" + ), + Expect( + input=(slice(1, 6), _ORTHO_3D_IX1_BOOL, slice(2, 9)), output=None, id="slice-array-slice" + ), + Expect( + input=(slice(1, 6), slice(1, 5), _ORTHO_3D_IX2_BOOL), output=None, id="slice-slice-array" + ), + Expect( + input=(_ORTHO_3D_IX0_BOOL, slice(0, 6, 2), slice(0, 10, 3)), + output=None, + id="array-strided-strided", + ), + Expect( + input=(slice(0, 7, 2), _ORTHO_3D_IX1_BOOL, slice(0, 10, 3)), + output=None, + id="strided-array-strided", + ), + Expect( + input=(slice(0, 7, 2), slice(0, 6, 2), _ORTHO_3D_IX2_BOOL), + output=None, + id="strided-strided-array", + ), + # mixed indexing with single array / ints + Expect(input=(_ORTHO_3D_IX0_BOOL, 3, 8), output=None, id="array-int-int"), + Expect(input=(5, _ORTHO_3D_IX1_BOOL, 8), output=None, id="int-array-int"), + Expect(input=(5, 3, _ORTHO_3D_IX2_BOOL), output=None, id="int-int-array"), + # mixed indexing with single array / slice / int + Expect(input=(_ORTHO_3D_IX0_BOOL, slice(1, 5), 8), output=None, id="array-slice-int"), + Expect(input=(5, _ORTHO_3D_IX1_BOOL, slice(2, 9)), output=None, id="int-array-slice"), + Expect(input=(slice(1, 6), 3, _ORTHO_3D_IX2_BOOL), output=None, id="slice-int-array"), + # mixed indexing with two arrays / slice + Expect( + input=(_ORTHO_3D_IX0_BOOL, _ORTHO_3D_IX1_BOOL, slice(2, 9)), + output=None, + id="two-arrays-slice", + ), + Expect( + input=(slice(1, 6), _ORTHO_3D_IX1_BOOL, _ORTHO_3D_IX2_BOOL), + output=None, + id="slice-two-arrays", + ), + Expect( + input=(_ORTHO_3D_IX0_BOOL, slice(1, 5), _ORTHO_3D_IX2_BOOL), + output=None, + id="array-slice-array", + ), + # mixed indexing with two arrays / integer + Expect(input=(_ORTHO_3D_IX0_BOOL, _ORTHO_3D_IX1_BOOL, 8), output=None, id="two-arrays-int"), + Expect(input=(5, _ORTHO_3D_IX1_BOOL, _ORTHO_3D_IX2_BOOL), output=None, id="int-two-arrays"), + Expect(input=(_ORTHO_3D_IX0_BOOL, 3, _ORTHO_3D_IX2_BOOL), output=None, id="array-int-array"), +] -def test_get_orthogonal_selection_3d(store: StorePath) -> None: - # setup - a = np.arange(32400, dtype=int).reshape(120, 30, 9) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(60, 20, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - ix2 = np.random.binomial(1, 0.5, size=a.shape[2]).astype(bool) - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - - # sorted integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix2 = np.random.choice(a.shape[2], size=int(a.shape[2] * 0.5), replace=True) - ix0.sort() - ix1.sort() - ix2.sort() - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) +@pytest.mark.parametrize("case", _ORTHO_3D_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_3d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """oindex on a 3D array matches numpy for array/slice/int combinations per axis.""" + a = np.arange(420, dtype=int).reshape(7, 6, 10) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(3, 2, 4)) + _test_get_orthogonal_selection(a, z, case.input) def test_orthogonal_indexing_edge_cases(store: StorePath) -> None: + """oindex on a shape-(1, 2, 3) array correctly handles mixing integer, slice, int-list, and bool-list indexers per axis.""" a = np.arange(6).reshape(1, 2, 3) z = zarr_array_from_numpy_array(store, a, chunk_shape=(1, 2, 3)) @@ -806,30 +957,19 @@ def _test_set_orthogonal_selection( assert_array_equal(a, z[:]) -def test_set_orthogonal_selection_1d(store: StorePath) -> None: - # setup - v = np.arange(550, dtype=int) - a = np.empty(v.shape, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - # test with different degrees of sparseness - np.random.seed(42) - for p in 0.5, 0.01: - # boolean arrays - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_set_orthogonal_selection(v, a, z, ix) - - # sorted integer arrays - ix = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix.sort() - _test_set_orthogonal_selection(v, a, z, ix) - - # basic selections - for selection in basic_selections_1d: - _test_set_orthogonal_selection(v, a, z, selection) +@pytest.mark.parametrize("case", _ORTHO_1D_BOOL_CASES + _ORTHO_1D_INT_CASES, ids=lambda c: c.id) +def test_set_orthogonal_selection_1d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """set_orthogonal_selection on a 1D array round-trips through numpy for masks and int arrays.""" + v = np.arange(30, dtype=int) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_orthogonal_selection(v, a, z, case.input) def test_set_item_1d_last_two_chunks(store: StorePath): + """Regression for GH2849: `__setitem__` correctly writes to the last two chunks of a 1D array and to 0-dimensional scalar arrays.""" # regression test for GH2849 g = zarr.open_group(store=store, zarr_format=3, mode="w") a = g.create_array("bar", shape=(10,), chunks=(3,), dtype=int) @@ -848,110 +988,30 @@ def test_set_item_1d_last_two_chunks(store: StorePath): np.testing.assert_equal(z["zoo"][()], np.array(1)) -def _test_set_orthogonal_selection_2d( - v: npt.NDArray[np.int_], - a: npt.NDArray[np.int_], - z: Array, - ix0: npt.NDArray[np.bool], - ix1: npt.NDArray[np.bool], +@pytest.mark.parametrize("case", _ORTHO_2D_CASES, ids=lambda c: c.id) +def test_set_orthogonal_selection_2d( + store: StorePath, case: Expect[OrthogonalSelection, None] ) -> None: - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice or int - (ix0, slice(1, 5)), - (slice(250, 350), ix1), - (ix0, 4), - (42, ix1), - ] - for selection in selections: - _test_set_orthogonal_selection(v, a, z, selection) - - -def test_set_orthogonal_selection_2d(store: StorePath) -> None: - # setup - v = np.arange(5400, dtype=int).reshape(600, 9) + """set_orthogonal_selection on a 2D array round-trips through numpy.""" + v = np.arange(60, dtype=int).reshape(12, 5) a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - - # sorted integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix0.sort() - ix1.sort() - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - - for selection in basic_selections_2d: - _test_set_orthogonal_selection(v, a, z, selection) - - -def _test_set_orthogonal_selection_3d( - v: npt.NDArray[np.int_], - a: npt.NDArray[np.int_], - z: Array, - ix0: npt.NDArray[np.bool], - ix1: npt.NDArray[np.bool], - ix2: npt.NDArray[np.bool], -) -> None: - selections = ( - # single value - (60, 15, 4), - (-1, -1, -1), - # index all axes with bool array - (ix0, ix1, ix2), - # mixed indexing with single bool array / slice or int - (ix0, slice(10, 20), slice(1, 5)), - (slice(30, 50), ix1, slice(1, 5)), - (slice(30, 50), slice(10, 20), ix2), - (ix0, 15, 4), - (60, ix1, 4), - (60, 15, ix2), - (ix0, slice(10, 20), 4), - (slice(30, 50), ix1, 4), - (slice(30, 50), 15, ix2), - # indexing with two arrays / slice - (ix0, ix1, slice(1, 5)), - # indexing with two arrays / integer - (ix0, ix1, 4), - ) - for selection in selections: - _test_set_orthogonal_selection(v, a, z, selection) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_orthogonal_selection(v, a, z, case.input) -def test_set_orthogonal_selection_3d(store: StorePath) -> None: - # setup - v = np.arange(32400, dtype=int).reshape(120, 30, 9) +@pytest.mark.parametrize("case", _ORTHO_3D_CASES, ids=lambda c: c.id) +def test_set_orthogonal_selection_3d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """set_orthogonal_selection on a 3D array round-trips through numpy.""" + v = np.arange(420, dtype=int).reshape(7, 6, 10) a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(60, 20, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - ix2 = np.random.binomial(1, 0.5, size=a.shape[2]).astype(bool) - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - # sorted integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix2 = np.random.choice(a.shape[2], size=int(a.shape[2] * 0.5), replace=True) - ix0.sort() - ix1.sort() - ix2.sort() - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(3, 2, 4)) + _test_set_orthogonal_selection(v, a, z, case.input) def test_orthogonal_indexing_fallback_on_get_setitem(store: StorePath) -> None: + """Paired integer-list indexing on a 2D array falls back to orthogonal get and set via `__getitem__`/`__setitem__`.""" z = zarr_array_from_numpy_array(store, np.zeros((20, 20))) z[[1, 2, 3], [1, 2, 3]] = 1 np.testing.assert_array_equal( @@ -982,118 +1042,243 @@ def _test_get_coordinate_selection( assert_array_equal(expect, actual) -coordinate_selections_1d_bad = [ - # slice not supported - slice(5, 15), - slice(None), - Ellipsis, - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), +_COORD_1D_CASES: list[Expect[CoordinateSelection, None]] = [ + Expect(input=5, output=None, id="single"), + Expect(input=-1, output=None, id="single-negative"), + Expect(input=[0, 3, 10, -23, -12, -1], output=None, id="wraparound"), + Expect(input=[3, 25, 8, 17], output=None, id="out-of-order"), + Expect(input=[1, 8, 15, 29], output=None, id="sorted"), + Expect(input=[29, 15, 8, 1], output=None, id="reversed"), + Expect(input=np.array([29, 15, 8, 1], dtype=np.uint32), output=None, id="reversed-uint"), + Expect(input=[2, 2, 8, 8], output=None, id="duplicates"), + Expect(input=np.array([[2, 4], [6, 8]]), output=None, id="multi-dim"), + # sorted-1D fast path (chunk_shape=(7,)): boundaries, contiguous runs, single chunk, full + Expect(input=[0, 6, 7, 13, 14, 28, 29], output=None, id="sorted-chunk-boundaries"), + Expect(input=[0, 1, 2, 8, 9, 10, 21, 22, 23], output=None, id="sorted-contiguous-runs"), + Expect(input=[1, 2, 3, 4, 5, 6], output=None, id="sorted-single-chunk"), + Expect(input=list(range(30)), output=None, id="sorted-full"), + Expect(input=[0, 0, 7, 7, 7, 29], output=None, id="sorted-duplicates-boundaries"), +] + +# get_coordinate_selection and vindex word their errors differently for these +# invalid-type inputs, so these cases assert only the exception type (msg=None). +_COORD_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=slice(5, 15), exception=IndexError, id="slice", msg=None), + ExpectFail(input=slice(None), exception=IndexError, id="full-slice", msg=None), + ExpectFail(input=Ellipsis, exception=IndexError, id="ellipsis", msg=None), + ExpectFail(input=2.3, exception=IndexError, id="float", msg=None), + ExpectFail(input="foo", exception=IndexError, id="string", msg=None), + ExpectFail(input=b"xxx", exception=IndexError, id="bytes", msg=None), + ExpectFail(input=None, exception=IndexError, id="none", msg=None), + ExpectFail(input=(0, 0), exception=IndexError, id="tuple-pair", msg=None), + ExpectFail(input=(slice(None), slice(None)), exception=IndexError, id="two-slices", msg=None), + ExpectFail( + input=[31], + exception=IndexError, + id="out-of-bounds-high", + msg="index out of bounds for dimension with length 30", + ), + ExpectFail( + input=[-31], + exception=IndexError, + id="out-of-bounds-low", + msg="index out of bounds for dimension with length 30", + ), ] +_COORD_2D_IX0 = np.array([0, 5, 11, 2, 8]) +_COORD_2D_IX1 = np.array([1, 3, 4, 0, 2]) + +_COORD_2D_CASES: list[Expect[CoordinateSelection, None]] = [ + Expect(input=(5, 4), output=None, id="single"), + Expect(input=(-1, -1), output=None, id="single-negative"), + Expect(input=(_COORD_2D_IX0, _COORD_2D_IX1), output=None, id="both-arrays"), + # scalar broadcasts in coordinate indexing (numpy and zarr agree) + Expect(input=(np.array([0, 5, 11]), 4), output=None, id="array-int"), + Expect(input=(7, np.array([0, 2, 4])), output=None, id="int-array"), + Expect(input=([3, 3, 4, 2, 5], [1, 3, 4, 0, 2]), output=None, id="not-monotonic-first"), + Expect(input=([1, 1, 2, 2, 5], [1, 3, 2, 1, 0]), output=None, id="not-monotonic-second"), + Expect( + input=(np.array([[1, 1, 2], [2, 2, 5]]), np.array([[1, 3, 2], [1, 0, 0]])), + output=None, + id="multi-dim", + ), +] + +_COORD_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=(slice(5, 15), [1, 2, 3]), + exception=IndexError, + id="slice-with-array", + msg=None, + ), + ExpectFail( + input=([1, 2, 3], slice(5, 15)), + exception=IndexError, + id="array-with-slice", + msg=None, + ), + ExpectFail( + input=(Ellipsis, [1, 2, 3]), + exception=IndexError, + id="ellipsis-with-array", + msg=None, + ), + ExpectFail(input=Ellipsis, exception=IndexError, id="ellipsis", msg=None), + ExpectFail( + input=(np.array([12]), np.array([0])), + exception=IndexError, + id="out-of-bounds-axis0", + msg="index out of bounds for dimension with length 12", + ), + ExpectFail( + input=(np.array([0]), np.array([5])), + exception=IndexError, + id="out-of-bounds-axis1", + msg="index out of bounds for dimension with length 5", + ), +] -# noinspection PyStatementEffect -def test_get_coordinate_selection_1d(store: StorePath) -> None: - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix = np.random.choice(a.shape[0], size=n, replace=True) - _test_get_coordinate_selection(a, z, ix) - ix.sort() - _test_get_coordinate_selection(a, z, ix) - ix = ix[::-1] - _test_get_coordinate_selection(a, z, ix) +@pytest.mark.parametrize("case", _COORD_1D_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_1d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """vindex and get_coordinate_selection on a 1D array match numpy for int, list, and multi-dim selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_coordinate_selection(a, z, case.input) + +@pytest.mark.parametrize( + ("chunks", "shards"), + [((7,), None), ((7,), (21,))], + ids=["chunked", "sharded"], +) +def test_get_coordinate_selection_1d_fast_path( + store: StorePath, chunks: tuple[int, ...], shards: tuple[int, ...] | None +) -> None: + """The sorted-1D-runs fast path in CoordinateIndexer matches numpy on chunked and sharded arrays. + + Exercises the boundary/run/single-chunk/full-array cases that the fast path optimizes, plus + the sharded case where the top-level (shard) grid drives chunk assignment. + """ + a = np.arange(210, dtype=int) + z = zarr.create_array( + store=store / str(uuid4()), + shape=a.shape, + dtype=a.dtype, + chunks=chunks, + shards=shards, + ) + z[:] = a + rng = np.random.default_rng(0) selections = [ - # test single item - 42, - -1, - # test wraparound - [0, 3, 10, -23, -12, -1], - # test out of order - [3, 105, 23, 127], # not monotonically increasing - # test multi-dimensional selection - np.array([[2, 4], [6, 8]]), + np.sort(rng.choice(210, 60, replace=False)), # scattered sorted + np.array([0, 6, 7, 20, 21, 209]), # chunk/shard boundaries + np.concatenate([np.arange(s, s + 5) for s in (0, 33, 100, 180)]), # contiguous runs + np.array([0, 0, 7, 7, 209]), # sorted with duplicates + np.arange(210), # whole array + np.array([5]), # single element ] - for selection in selections: - _test_get_coordinate_selection(a, z, selection) + for sel in selections: + assert_array_equal(a[sel], z.get_coordinate_selection(sel)) + assert_array_equal(a[sel], z.vindex[sel]) - # test errors - bad_selections = coordinate_selections_1d_bad + [ - [a.shape[0] + 1], # out of bounds - [-(a.shape[0] + 1)], # out of bounds - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_coordinate_selection(selection) # type: ignore[arg-type] - with pytest.raises(IndexError): - z.vindex[selection] # type: ignore[index] +def test_coordinate_indexer_1d_last_chunk_boundary_does_not_overflow() -> None: + max_intp = np.iinfo(np.intp).max + chunk_size = max_intp // 2 + 1 + coords = np.arange(max_intp - 4, max_intp, dtype=np.intp) + chunk_grid = ChunkGrid.from_sizes((max_intp,), (chunk_size,)) + + (projection,) = tuple(CoordinateIndexer((coords,), (max_intp,), chunk_grid)) + + assert projection.chunk_coords == (1,) + assert_array_equal(projection.chunk_selection[0], coords - chunk_size) + assert projection.out_selection == slice(0, 4) + + +@pytest.mark.parametrize("coord_dtype", [np.int8, np.uint8, np.uint32]) +def test_coordinate_selection_1d_narrow_dtype_large_chunk( + store: StorePath, coord_dtype: type[np.integer[Any]] +) -> None: + source = np.arange(1_000) + coords = np.arange(10, dtype=coord_dtype) + z = zarr_array_from_numpy_array(store, source, chunk_shape=(1_000,)) + + assert_array_equal(z.get_coordinate_selection(coords), source[coords]) + assert_array_equal(z.vindex[coords], source[coords]) + assert_array_equal(z[coords], source[coords]) + + expected = source.copy() + expected[coords] = -1 + z.set_coordinate_selection(coords, -1) + assert_array_equal(z[:], expected) + z[:] = source + z.vindex[coords] = -1 + assert_array_equal(z[:], expected) + + +def test_coordinate_indexer_1d_sparse_selection_uses_general_path( + monkeypatch: pytest.MonkeyPatch, +) -> None: + coords = np.array([0, 99]) + chunk_grid = ChunkGrid.from_sizes((100,), (1,)) + + def unexpected_searchsorted(*args: Any, **kwargs: Any) -> None: + pytest.fail("sparse coordinate selection should not call searchsorted") + + monkeypatch.setattr(np, "searchsorted", unexpected_searchsorted) + projections = tuple(CoordinateIndexer((coords,), (100,), chunk_grid)) + + assert tuple(projection.chunk_coords for projection in projections) == ((0,), (99,)) + + +def test_get_coordinate_selection_1d_irregular_grid(store: StorePath) -> None: + """Coordinate selections on an irregular (rectilinear) chunk grid bypass the sorted-1D fast + path (which requires a regular grid) and still match numpy via the general path.""" + a = np.arange(30, dtype=int) + with zarr.config.set({"array.rectilinear_chunks": True}): + z = zarr.create_array( + store=store / str(uuid4()), + shape=a.shape, + dtype=a.dtype, + chunks=((3, 3, 4, 5, 5, 5, 5),), + ) + z[:] = a + for sel in (np.array([1, 8, 15, 29]), np.array([0, 3, 3, 29]), np.arange(30)): + assert_array_equal(a[sel], z.get_coordinate_selection(sel)) + + +@pytest.mark.parametrize("case", _COORD_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_coordinate_selection and vindex both raise IndexError for invalid 1D selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_coordinate_selection(case.input) # type: ignore[arg-type] + with case.raises(): + z.vindex[case.input] # type: ignore[index] + + +@pytest.mark.parametrize("case", _COORD_2D_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_2d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """vindex and get_coordinate_selection on a 2D array match numpy for coordinate selections.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_coordinate_selection(a, z, case.input) -def test_get_coordinate_selection_2d(store: StorePath) -> None: - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - ix0: npt.ArrayLike - ix1: npt.ArrayLike - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - selections = [ - # single value - (42, 4), - (-1, -1), - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - (42, 4), - ] - for selection in selections: - _test_get_coordinate_selection(a, z, selection) - - # not monotonically increasing (first dim) - ix0 = [3, 3, 4, 2, 5] - ix1 = [1, 3, 5, 7, 9] - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - # not monotonically increasing (second dim) - ix0 = [1, 1, 2, 2, 5] - ix1 = [1, 3, 2, 1, 0] - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - # multi-dimensional selection - ix0 = np.array([[1, 1, 2], [2, 2, 5]]) - ix1 = np.array([[1, 3, 2], [1, 0, 0]]) - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - selection = slice(5, 15), [1, 2, 3] - with pytest.raises(IndexError): - z.get_coordinate_selection(selection) # type:ignore[arg-type] - selection = [1, 2, 3], slice(5, 15) - with pytest.raises(IndexError): - z.get_coordinate_selection(selection) # type:ignore[arg-type] - selection = Ellipsis, [1, 2, 3] - with pytest.raises(IndexError): - z.get_coordinate_selection(selection) # type:ignore[arg-type] - selection = Ellipsis - with pytest.raises(IndexError): - z.get_coordinate_selection(selection) # type:ignore[arg-type] + +@pytest.mark.parametrize("case", _COORD_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_coordinate_selection raises IndexError when slices or Ellipsis appear in a 2D coordinate selection.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_coordinate_selection(case.input) # type: ignore[arg-type] def _test_set_coordinate_selection( @@ -1113,59 +1298,26 @@ def _test_set_coordinate_selection( assert_array_equal(a, z[:]) -def test_set_coordinate_selection_1d(store: StorePath) -> None: - # setup - v = np.arange(550, dtype=int) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.01: - n = int(a.size * p) - ix = np.random.choice(a.shape[0], size=n, replace=True) - _test_set_coordinate_selection(v, a, z, ix) - - # multi-dimensional selection - ix = np.array([[2, 4], [6, 8]]) - _test_set_coordinate_selection(v, a, z, ix) - - for selection in coordinate_selections_1d_bad: - with pytest.raises(IndexError): - z.set_coordinate_selection(selection, 42) # type:ignore[arg-type] - with pytest.raises(IndexError): - z.vindex[selection] = 42 # type:ignore[index] +@pytest.mark.parametrize("case", _COORD_1D_CASES, ids=lambda c: c.id) +def test_set_coordinate_selection_1d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """set_coordinate_selection and vindex assignment on a 1D array round-trip through numpy.""" + v = np.arange(30, dtype=int) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_coordinate_selection(v, a, z, case.input) -def test_set_coordinate_selection_2d(store: StorePath) -> None: - # setup - v = np.arange(5400, dtype=int).reshape(600, 9) +@pytest.mark.parametrize("case", _COORD_2D_CASES, ids=lambda c: c.id) +def test_set_coordinate_selection_2d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """set_coordinate_selection and vindex assignment on a 2D array round-trip through numpy.""" + v = np.arange(60, dtype=int).reshape(12, 5) a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - - selections = ( - (42, 4), - (-1, -1), - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ) - for selection in selections: - _test_set_coordinate_selection(v, a, z, selection) - - # multi-dimensional selection - ix0 = np.array([[1, 2, 3], [4, 5, 6]]) - ix1 = np.array([[1, 3, 2], [2, 0, 5]]) - _test_set_coordinate_selection(v, a, z, (ix0, ix1)) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_coordinate_selection(v, a, z, case.input) def _test_get_block_selection( @@ -1181,122 +1333,84 @@ def _test_get_block_selection( assert_array_equal(expect, actual) -block_selections_1d: list[BasicSelection] = [ - # test single item - 0, - 5, - # test wraparound - -1, - -4, - # test slice - slice(5), - slice(None, 3), - slice(5, 6), - slice(-3, -1), - slice(None), # Full slice +_BLOCK_1D_CASES: list[Expect[BasicSelection, slice]] = [ + Expect(input=0, output=slice(0, 7), id="block-0"), + Expect(input=2, output=slice(14, 21), id="block-mid"), + Expect(input=4, output=slice(28, 30), id="block-last"), + Expect(input=-1, output=slice(28, 30), id="block-neg-1"), + Expect(input=-2, output=slice(21, 28), id="block-neg-2"), + Expect(input=slice(3), output=slice(0, 21), id="slice-to-3"), + Expect(input=slice(None, 2), output=slice(0, 14), id="slice-none-2"), + Expect(input=slice(1, 2), output=slice(7, 14), id="slice-1-2"), + Expect(input=slice(-2, -1), output=slice(21, 28), id="slice-neg"), + Expect(input=slice(None), output=slice(0, 30), id="full"), ] -block_selections_1d_array_projection: list[slice] = [ - # test single item - slice(100), - slice(500, 600), - # test wraparound - slice(1000, None), - slice(700, 800), - # test slice - slice(500), - slice(None, 300), - slice(500, 600), - slice(800, 1000), - slice(None), +_BLOCK_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=slice(3, 8, 2), exception=IndexError, id="strided-slice"), + ExpectFail(input=2.3, exception=IndexError, id="float"), + ExpectFail(input=b"xxx", exception=IndexError, id="bytes"), + ExpectFail(input=None, exception=IndexError, id="none"), + ExpectFail(input=(0, 0), exception=IndexError, id="tuple-pair"), + ExpectFail(input=(slice(None), slice(None)), exception=IndexError, id="two-slices"), + ExpectFail(input=[0, 5, 3], exception=IndexError, id="int-list"), + ExpectFail(input=5, exception=IndexError, id="out-of-bounds-high"), + ExpectFail(input=-6, exception=IndexError, id="out-of-bounds-low"), ] -block_selections_1d_bad = [ - # slice not supported - slice(3, 8, 2), - # bad stuff - 2.3, - # "foo", # TODO - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), - [0, 5, 3], +_BLOCK_2D_CASES: list[Expect[BasicSelection, tuple[slice, slice]]] = [ + Expect(input=(0, 0), output=(slice(0, 5), slice(0, 2)), id="single-00"), + Expect(input=(1, 1), output=(slice(5, 10), slice(2, 4)), id="single-mid"), + Expect(input=(-1, -1), output=(slice(10, 12), slice(4, 5)), id="neg"), + Expect(input=(slice(0, 2), 0), output=(slice(0, 10), slice(0, 2)), id="slice-rows"), + Expect(input=(2, slice(1, 3)), output=(slice(10, 12), slice(2, 5)), id="slice-cols"), + Expect(input=(slice(0, 2), slice(0, 2)), output=(slice(0, 10), slice(0, 4)), id="both-slices"), + Expect(input=(slice(None), slice(None)), output=(slice(0, 12), slice(0, 5)), id="full"), ] +_BLOCK_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=(slice(5, 15), [1, 2, 3]), exception=IndexError, id="slice-with-array"), + ExpectFail(input=(Ellipsis, [1, 2, 3]), exception=IndexError, id="ellipsis-with-array"), + ExpectFail(input=(slice(15, 20), slice(None)), exception=IndexError, id="out-of-bounds"), +] -def test_get_block_selection_1d(store: StorePath) -> None: - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - for selection, expected_idx in zip( - block_selections_1d, block_selections_1d_array_projection, strict=True - ): - _test_get_block_selection(a, z, selection, expected_idx) +@pytest.mark.parametrize("case", _BLOCK_1D_CASES, ids=lambda c: c.id) +def test_get_block_selection_1d(store: StorePath, case: Expect[BasicSelection, slice]) -> None: + """get_block_selection / .blocks on a 1D array selects whole chunks matching the array slice.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_block_selection(a, z, case.input, case.output) - bad_selections = block_selections_1d_bad + [ - z.metadata.chunk_grid.get_nchunks(z.shape) + 1, # out of bounds - -(z.metadata.chunk_grid.get_nchunks(z.shape) + 1), # out of bounds - ] - for selection_bad in bad_selections: - with pytest.raises(IndexError): - z.get_block_selection(selection_bad) # type:ignore[arg-type] - with pytest.raises(IndexError): - z.blocks[selection_bad] # type:ignore[index] - - -block_selections_2d: list[BasicSelection] = [ - # test single item - (0, 0), - (1, 2), - # test wraparound - (-1, -1), - (-3, -2), - # test slice - (slice(1), slice(2)), - (slice(None, 2), slice(-2, -1)), - (slice(2, 3), slice(-2, None)), - (slice(-3, -1), slice(-3, -2)), - (slice(None), slice(None)), # Full slice -] - -block_selections_2d_array_projection: list[tuple[slice, slice]] = [ - # test single item - (slice(300), slice(3)), - (slice(300, 600), slice(6, 9)), - # test wraparound - (slice(900, None), slice(9, None)), - (slice(300, 600), slice(6, 9)), - # test slice - (slice(300), slice(6)), - (slice(None, 600), slice(6, 9)), - (slice(600, 900), slice(6, None)), - (slice(300, 900), slice(3, 6)), - (slice(None), slice(None)), # Full slice -] +@pytest.mark.parametrize("case", _BLOCK_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_block_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_block_selection / .blocks on a 1D array rejects invalid block selections with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_block_selection(case.input) + with case.raises(): + z.blocks[case.input] -def test_get_block_selection_2d(store: StorePath) -> None: - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) +@pytest.mark.parametrize("case", _BLOCK_2D_CASES, ids=lambda c: c.id) +def test_get_block_selection_2d( + store: StorePath, case: Expect[BasicSelection, tuple[slice, slice]] +) -> None: + """get_block_selection / .blocks on a 2D array selects whole chunk regions matching the array slices.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_block_selection(a, z, case.input, case.output) - for selection, expected_idx in zip( - block_selections_2d, block_selections_2d_array_projection, strict=True - ): - _test_get_block_selection(a, z, selection, expected_idx) - selection = slice(5, 15), [1, 2, 3] - with pytest.raises(IndexError): - z.get_block_selection(selection) - selection = Ellipsis, [1, 2, 3] - with pytest.raises(IndexError): - z.get_block_selection(selection) - selection = slice(15, 20), slice(None) - with pytest.raises(IndexError): # out of bounds - z.get_block_selection(selection) +@pytest.mark.parametrize("case", _BLOCK_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_block_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_block_selection on a 2D array rejects invalid or out-of-bounds block selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_block_selection(case.input) def _test_set_block_selection( @@ -1304,7 +1418,7 @@ def _test_set_block_selection( a: npt.NDArray[Any], z: zarr.Array, selection: BasicSelection, - expected_idx: slice, + expected_idx: slice | tuple[slice, ...], ) -> None: for value in 42, v[expected_idx], v[expected_idx].tolist(): # setup expectation @@ -1320,44 +1434,44 @@ def _test_set_block_selection( assert_array_equal(a, z[:]) -def test_set_block_selection_1d(store: StorePath) -> None: - # setup - v = np.arange(1050, dtype=int) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) +@pytest.mark.parametrize("case", _BLOCK_1D_CASES, ids=lambda c: c.id) +def test_set_block_selection_1d(store: StorePath, case: Expect[BasicSelection, slice]) -> None: + """set_block_selection / .blocks assignment on a 1D array round-trips through numpy for each block selection.""" + v = np.arange(30, dtype=int) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_block_selection(v, a, z, case.input, case.output) - for selection, expected_idx in zip( - block_selections_1d, block_selections_1d_array_projection, strict=True - ): - _test_set_block_selection(v, a, z, selection, expected_idx) - for selection_bad in block_selections_1d_bad: - with pytest.raises(IndexError): - z.set_block_selection(selection_bad, 42) # type:ignore[arg-type] - with pytest.raises(IndexError): - z.blocks[selection_bad] = 42 # type:ignore[index] +@pytest.mark.parametrize("case", _BLOCK_1D_BAD_CASES, ids=lambda c: c.id) +def test_set_block_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """set_block_selection / .blocks assignment on a 1D array rejects invalid block selections with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.set_block_selection(case.input, 42) + with case.raises(): + z.blocks[case.input] = 42 -def test_set_block_selection_2d(store: StorePath) -> None: - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) +@pytest.mark.parametrize("case", _BLOCK_2D_CASES, ids=lambda c: c.id) +def test_set_block_selection_2d( + store: StorePath, case: Expect[BasicSelection, tuple[slice, slice]] +) -> None: + """set_block_selection / .blocks assignment on a 2D array round-trips through numpy for each block selection.""" + v = np.arange(60, dtype=int).reshape(12, 5) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_block_selection(v, a, z, case.input, case.output) - for selection, expected_idx in zip( - block_selections_2d, block_selections_2d_array_projection, strict=True - ): - _test_set_block_selection(v, a, z, selection, expected_idx) - selection = slice(5, 15), [1, 2, 3] - with pytest.raises(IndexError): - z.set_block_selection(selection, 42) - selection = Ellipsis, [1, 2, 3] - with pytest.raises(IndexError): - z.set_block_selection(selection, 42) - selection = slice(15, 20), slice(None) - with pytest.raises(IndexError): # out of bounds - z.set_block_selection(selection, 42) +@pytest.mark.parametrize("case", _BLOCK_2D_BAD_CASES, ids=lambda c: c.id) +def test_set_block_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """set_block_selection on a 2D array rejects invalid or out-of-bounds block selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.set_block_selection(case.input, 42) def _test_get_mask_selection(a: npt.NDArray[Any], z: Array, selection: npt.NDArray) -> None: @@ -1370,65 +1484,99 @@ def _test_get_mask_selection(a: npt.NDArray[Any], z: Array, selection: npt.NDArr assert_array_equal(expect, actual) -mask_selections_1d_bad = [ - # slice not supported - slice(5, 15), - slice(None), - Ellipsis, - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), +_MASK_1D_CASES: list[Expect[Any, None]] = [ + Expect(input=np.zeros(30, dtype=bool), output=None, id="all-false"), + Expect(input=np.ones(30, dtype=bool), output=None, id="all-true"), + Expect(input=np.arange(30) % 2 == 0, output=None, id="alternating"), + Expect( + input=np.isin(np.arange(30), [0, 7, 14, 29]), + output=None, + id="sparse-cross-chunk", + ), ] +# msg=None for all 1d bad cases: get_mask_selection and vindex raise different +# messages for the same input, so no single substring satisfies both assertions. +_MASK_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=slice(5, 15), exception=IndexError, id="slice"), + ExpectFail(input=slice(None), exception=IndexError, id="full-slice"), + ExpectFail(input=Ellipsis, exception=IndexError, id="ellipsis"), + ExpectFail(input=2.3, exception=IndexError, id="float"), + ExpectFail(input="foo", exception=IndexError, id="string"), + ExpectFail(input=b"xxx", exception=IndexError, id="bytes"), + ExpectFail(input=None, exception=IndexError, id="none"), + ExpectFail(input=(0, 0), exception=IndexError, id="tuple-pair"), + ExpectFail(input=(slice(None), slice(None)), exception=IndexError, id="two-slices"), + ExpectFail(input=np.zeros(5, dtype=bool), exception=IndexError, id="mask-too-short"), + ExpectFail(input=np.zeros(50, dtype=bool), exception=IndexError, id="mask-too-long"), + ExpectFail(input=[[True, False], [False, True]], exception=IndexError, id="too-many-dims"), +] -# noinspection PyStatementEffect -def test_get_mask_selection_1d(store: StorePath) -> None: - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_get_mask_selection(a, z, ix) - - # test errors - bad_selections = mask_selections_1d_bad + [ - np.zeros(50, dtype=bool), # too short - np.zeros(2000, dtype=bool), # too long - [[True, False], [False, True]], # too many dimensions - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_mask_selection(selection) # type: ignore[arg-type] - with pytest.raises(IndexError): - z.vindex[selection] # type:ignore[index] +def _make_sparse_2d_mask() -> npt.NDArray[np.bool_]: + """Build a deterministic sparse (12, 5) boolean mask with Trues at (0,0), (5,2), (11,4), (2,3).""" + mask = np.zeros((12, 5), dtype=bool) + for r, c in [(0, 0), (5, 2), (11, 4), (2, 3)]: + mask[r, c] = True + return mask + + +_MASK_2D_CASES: list[Expect[Any, None]] = [ + Expect(input=np.zeros((12, 5), dtype=bool), output=None, id="all-false"), + Expect(input=np.ones((12, 5), dtype=bool), output=None, id="all-true"), + Expect( + input=(np.add.outer(np.arange(12), np.arange(5)) % 2).astype(bool), + output=None, + id="checkerboard", + ), + Expect( + input=_make_sparse_2d_mask(), + output=None, + id="sparse", + ), +] +_MASK_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=np.zeros((12, 3), dtype=bool), exception=IndexError, id="too-few-cols"), + ExpectFail(input=np.zeros((20, 5), dtype=bool), exception=IndexError, id="too-many-rows"), + ExpectFail(input=[True, False], exception=IndexError, id="wrong-ndim"), +] -# noinspection PyStatementEffect -def test_get_mask_selection_2d(store: StorePath) -> None: - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.size).astype(bool).reshape(a.shape) - _test_get_mask_selection(a, z, ix) +@pytest.mark.parametrize("case", _MASK_1D_CASES, ids=lambda c: c.id) +def test_get_mask_selection_1d(store: StorePath, case: Expect[Any, None]) -> None: + """get_mask_selection / vindex / getitem on a 1D array match numpy for boolean masks.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_mask_selection(a, z, case.input) - # test errors - with pytest.raises(IndexError): - z.vindex[np.zeros((1000, 5), dtype=bool)] # too short - with pytest.raises(IndexError): - z.vindex[np.zeros((2000, 10), dtype=bool)] # too long - with pytest.raises(IndexError): - z.vindex[[True, False]] # wrong no. dimensions + +@pytest.mark.parametrize("case", _MASK_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_mask_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_mask_selection / vindex on a 1D array reject non-boolean-mask and mis-shaped selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_mask_selection(case.input) # type: ignore[arg-type] + with case.raises(): + z.vindex[case.input] # type: ignore[index] + + +@pytest.mark.parametrize("case", _MASK_2D_CASES, ids=lambda c: c.id) +def test_get_mask_selection_2d(store: StorePath, case: Expect[Any, None]) -> None: + """get_mask_selection / vindex / getitem on a 2D array match numpy for boolean masks.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_mask_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _MASK_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_mask_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """vindex on a 2D array rejects masks of the wrong shape or dimensionality.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.vindex[case.input] # type: ignore[index] def _test_set_mask_selection( @@ -1447,46 +1595,44 @@ def _test_set_mask_selection( assert_array_equal(a, z[:]) -def test_set_mask_selection_1d(store: StorePath) -> None: - # setup - v = np.arange(1050, dtype=int) +@pytest.mark.parametrize("case", _MASK_1D_CASES, ids=lambda c: c.id) +def test_set_mask_selection_1d(store: StorePath, case: Expect[Any, None]) -> None: + """set_mask_selection / vindex / setitem on a 1D array match numpy for boolean masks.""" + v = np.arange(30, dtype=int) a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_mask_selection(v, a, z, case.input) - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_set_mask_selection(v, a, z, ix) - for selection in mask_selections_1d_bad: - with pytest.raises(IndexError): - z.set_mask_selection(selection, 42) # type: ignore[arg-type] - with pytest.raises(IndexError): - z.vindex[selection] = 42 # type: ignore[index] +@pytest.mark.parametrize("case", _MASK_1D_BAD_CASES, ids=lambda c: c.id) +def test_set_mask_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """set_mask_selection / vindex on a 1D array reject non-boolean-mask and mis-shaped selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.set_mask_selection(case.input, 42) # type: ignore[arg-type] + with case.raises(): + z.vindex[case.input] = 42 # type: ignore[index] -def test_set_mask_selection_2d(store: StorePath) -> None: - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) +@pytest.mark.parametrize("case", _MASK_2D_CASES, ids=lambda c: c.id) +def test_set_mask_selection_2d(store: StorePath, case: Expect[Any, None]) -> None: + """set_mask_selection / vindex / setitem on a 2D array match numpy for boolean masks.""" + v = np.arange(60, dtype=int).reshape(12, 5) a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.size).astype(bool).reshape(a.shape) - _test_set_mask_selection(v, a, z, ix) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_mask_selection(v, a, z, case.input) def test_get_selection_out(store: StorePath) -> None: + """get_*_selection writes results into a provided out buffer, matching numpy.""" # basic selections - a = np.arange(1050) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) + a = np.arange(30) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) selections = [ - slice(50, 150), - slice(0, 1050), + slice(5, 15), + slice(0, 30), slice(1, 2), ] for selection in selections: @@ -1499,57 +1645,47 @@ def test_get_selection_out(store: StorePath) -> None: z.get_basic_selection(Ellipsis, out=[]) # type: ignore[arg-type] # orthogonal selections - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice - (ix0, slice(1, 5)), - (slice(250, 350), ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - # mixed int array / bool array - (ix0, np.nonzero(ix1)[0]), - (np.nonzero(ix0)[0], ix1), - ] - for selection in selections: - expect = oindex(a, selection) - out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) - z.get_orthogonal_selection(selection, out=out) - assert_array_equal(expect, out.as_numpy_array()[:]) + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + selections = [ + # index both axes with bool array + (_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_BOOL), + # mixed indexing with bool array / slice + (_ORTHO_2D_IX0_BOOL, slice(1, 4)), + (slice(2, 9), _ORTHO_2D_IX1_BOOL), + # mixed indexing with bool array / int + (_ORTHO_2D_IX0_BOOL, 3), + (7, _ORTHO_2D_IX1_BOOL), + # mixed int array / bool array + (_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_INT), + (_ORTHO_2D_IX0_INT, _ORTHO_2D_IX1_BOOL), + ] + for selection in selections: + expect = oindex(a, selection) + out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) + z.get_orthogonal_selection(selection, out=out) + assert_array_equal(expect, out.as_numpy_array()[:]) # coordinate selections - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ] - for selection in selections: - expect = a[selection] - out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) - z.get_coordinate_selection(selection, out=out) - assert_array_equal(expect, out.as_numpy_array()[:]) + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + selections = [ + # index both axes with array + (np.array([0, 5, 11]), np.array([0, 2, 4])), + # mixed indexing with array / int + (np.array([0, 5, 11]), 3), + (7, np.array([0, 2, 4])), + ] + for selection in selections: + expect = a[selection] + out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) + z.get_coordinate_selection(selection, out=out) + assert_array_equal(expect, out.as_numpy_array()[:]) @pytest.mark.xfail(reason="fields are not supported in v3") def test_get_selections_with_fields(store: StorePath) -> None: + """Would verify that basic, orthogonal, coordinate, and mask selections with structured-array `fields` arguments return the correct sub-fields (xfail: fields unsupported in v3).""" a = np.array( [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)], dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")], @@ -1658,6 +1794,7 @@ def test_get_selections_with_fields(store: StorePath) -> None: @pytest.mark.xfail(reason="fields are not supported in v3") def test_set_selections_with_fields(store: StorePath) -> None: + """Would verify that basic, orthogonal, coordinate, and mask set-selections with structured-array `fields` correctly write individual fields and reject multi-field assignment (xfail: fields unsupported in v3).""" v = np.array( [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)], dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")], @@ -1743,6 +1880,7 @@ def test_set_selections_with_fields(store: StorePath) -> None: def test_slice_selection_uints() -> None: + """make_slice_selection accepts unsigned integer indices without error and produces correct shape.""" arr = np.arange(24).reshape((4, 6)) idx = np.uint64(3) slice_sel = make_slice_selection((idx,)) @@ -1750,6 +1888,7 @@ def test_slice_selection_uints() -> None: def test_numpy_int_indexing(store: StorePath) -> None: + """Indexing with a plain Python int and with `np.int64` both return the correct scalar element.""" a = np.arange(1050) z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) assert a[42] == z[42] @@ -1784,6 +1923,7 @@ def test_numpy_int_indexing(store: StorePath) -> None: async def test_accessed_chunks( shape: tuple[int, ...], chunks: tuple[int, ...], ops: list[tuple[str, tuple[slice, ...]]] ) -> None: + """Only the chunks intersected by a slice selection are read or written, verified via a `CountingDict` store.""" # Test that only the required chunks are accessed during basic selection operations # shape: array shape # chunks: chunk size @@ -1840,22 +1980,23 @@ async def test_accessed_chunks( [1, ...], [slice(None)], [1, 3], - [[1, 2, 3], 9], - [np.arange(1000)], - [slice(5, 15)], - [slice(2, 4), 4], + [[1, 2, 3], 4], + [np.arange(12)], + [slice(2, 9)], + [slice(1, 3), 3], [[1, 3]], # mask selection - [np.tile([True, False], (1000, 5))], - [np.full((1000, 10), False)], + [np.tile([True, False, True, False, True], (12, 1))], + [np.full((12, 5), False)], # coordinate selection - [[1, 2, 3, 4], [5, 6, 7, 8]], - [[100, 200, 300], [4, 5, 6]], + [[1, 2, 3, 4], [0, 1, 2, 3]], + [[10, 11, 5], [4, 0, 2]], ], ) def test_indexing_equals_numpy(store: StorePath, selection: Selection) -> None: - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) + """Indexing a zarr array with assorted basic/mask/coordinate selections matches numpy.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) # note: in python 3.10 a[*selection] is not valid unpacking syntax expected = a[*selection,] actual = z[*selection,] @@ -1865,17 +2006,18 @@ def test_indexing_equals_numpy(store: StorePath, selection: Selection) -> None: @pytest.mark.parametrize( "selection", [ - [np.tile([True, False], 500), np.tile([True, False], 5)], - [np.full(1000, False), np.tile([True, False], 5)], - [np.full(1000, True), np.full(10, True)], - [np.full(1000, True), [True, False] * 5], + [np.tile([True, False], 6), np.tile([True, False, True, False, True], 1)], + [np.full(12, False), np.array([True, False, True, False, True])], + [np.full(12, True), np.full(5, True)], + [np.full(12, True), [True, False, True, False, True]], ], ) def test_orthogonal_bool_indexing_like_numpy_ix( store: StorePath, selection: list[npt.ArrayLike] ) -> None: - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) + """Orthogonal boolean indexing on each axis matches numpy's np.ix_ semantics.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) expected = a[np.ix_(*selection)] # note: in python 3.10 z[*selection] is not valid unpacking syntax actual = z[*selection,] @@ -1933,6 +2075,7 @@ def test_iter_grid_invalid() -> None: def test_indexing_with_zarr_array(store: StorePath) -> None: + """Regression for GH2133: indexing a zarr array with another zarr array (boolean or integer) as the indexer produces the same result as indexing with the equivalent numpy array.""" # regression test for https://github.com/zarr-developers/zarr-python/issues/2133 a = np.arange(10) za = zarr.array(a, chunks=2, store=store, path="a") @@ -1950,15 +2093,19 @@ def test_indexing_with_zarr_array(store: StorePath) -> None: @pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) -@pytest.mark.parametrize("shape", [(0, 2, 3), (0), (3, 0)]) +@pytest.mark.parametrize("shape", [(0, 2, 3), (0,), (3, 0)]) def test_zero_sized_chunks(store: StorePath, shape: list[int]) -> None: - z = zarr.create_array(store=store, shape=shape, chunks=shape, zarr_format=3, dtype="f8") + """Arrays with zero-extent dimensions can be created and indexed without error; reading back returns the fill value.""" + # Chunk sizes must be >= 1 per spec; use 1 for zero-extent dimensions. + chunks = tuple(max(1, s) for s in shape) + z = zarr.create_array(store=store, shape=shape, chunks=chunks, zarr_format=3, dtype="f8") z[...] = 42 assert_array_equal(z[...], np.zeros(shape, dtype="f8")) @pytest.mark.parametrize("store", ["memory"], indirect=["store"]) def test_vectorized_indexing_incompatible_shape(store) -> None: + """Regression for GH2469: vectorized set-indexing raises ValueError when the value shape is incompatible with the indexer shape.""" # GH2469 shape = (4, 4) chunks = (2, 2) @@ -1976,6 +2123,7 @@ def test_vectorized_indexing_incompatible_shape(store) -> None: def test_iter_chunk_regions(): + """_iter_chunk_regions yields slices that exactly cover each chunk, and reading/writing each region round-trips correctly.""" chunks = (2, 3) a = zarr.create((10, 10), chunks=chunks) a[:] = 1 @@ -2086,8 +2234,8 @@ class TestAsync: (np.array([False, False]), np.empty(shape=(0, 2), dtype="i8")), ], ) - @pytest.mark.asyncio async def test_async_oindex(self, store, indexer, expected): + """The async `oindex.getitem` interface returns the correct orthogonally-indexed result for int, slice, ellipsis, array, and boolean indexers.""" z = zarr.create_array(store=store, shape=(2, 2), chunks=(1, 1), zarr_format=3, dtype="i8") z[...] = np.array([[1, 2], [3, 4]]) async_zarr = z._async_array @@ -2095,8 +2243,8 @@ async def test_async_oindex(self, store, indexer, expected): result = await async_zarr.oindex.getitem(indexer) assert_array_equal(result, expected) - @pytest.mark.asyncio async def test_async_oindex_with_zarr_array(self, store): + """The async `oindex.getitem` interface accepts a zarr boolean array as the indexer and returns the correct rows.""" group = zarr.create_group(store=store, zarr_format=3) z1 = group.create_array(name="z1", shape=(2, 2), chunks=(1, 1), dtype="i8") @@ -2119,8 +2267,8 @@ async def test_async_oindex_with_zarr_array(self, store): (np.array([[False, True], [False, True]]), np.array([2, 4])), ], ) - @pytest.mark.asyncio async def test_async_vindex(self, store, indexer, expected): + """The async `vindex.getitem` interface returns the correct vectorized-indexed result for coordinate and boolean indexers.""" z = zarr.create_array(store=store, shape=(2, 2), chunks=(1, 1), zarr_format=3, dtype="i8") z[...] = np.array([[1, 2], [3, 4]]) async_zarr = z._async_array @@ -2128,8 +2276,8 @@ async def test_async_vindex(self, store, indexer, expected): result = await async_zarr.vindex.getitem(indexer) assert_array_equal(result, expected) - @pytest.mark.asyncio async def test_async_vindex_with_zarr_array(self, store): + """The async `vindex.getitem` interface accepts a zarr 2D boolean array as the indexer and returns the correct elements.""" group = zarr.create_group(store=store, zarr_format=3) z1 = group.create_array(name="z1", shape=(2, 2), chunks=(1, 1), dtype="i8") @@ -2144,8 +2292,8 @@ async def test_async_vindex_with_zarr_array(self, store): expected = np.array([2, 4]) assert_array_equal(result, expected) - @pytest.mark.asyncio async def test_async_invalid_indexer(self, store): + """The async `vindex.getitem` and `oindex.getitem` interfaces raise IndexError when given an unsupported indexer type.""" z = zarr.create_array(store=store, shape=(2, 2), chunks=(1, 1), zarr_format=3, dtype="i8") z[...] = np.array([[1, 2], [3, 4]]) async_zarr = z._async_array diff --git a/tests/test_info.py b/tests/test_info.py index 28c8803c83..08f2318dc2 100644 --- a/tests/test_info.py +++ b/tests/test_info.py @@ -74,7 +74,7 @@ def test_array_info(zarr_format: ZarrFormat) -> None: Read-only : True Store type : MemoryStore Filters : () - Serializer : BytesCodec(endian=) + Serializer : BytesCodec(endian='little') Compressors : ()""") @@ -117,7 +117,7 @@ def test_array_info_complete( Read-only : True Store type : MemoryStore Filters : () - Serializer : BytesCodec(endian=) + Serializer : BytesCodec(endian='little') Compressors : () No. bytes : {count_bytes} ({count_bytes_formatted}) No. bytes stored : {count_bytes_stored} ({count_bytes_stored_formatted}) diff --git a/tests/test_json.py b/tests/test_json.py new file mode 100644 index 0000000000..17a8c631d5 --- /dev/null +++ b/tests/test_json.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import math +from typing import TYPE_CHECKING + +import pytest + +from zarr.core._json import ( + buffer_to_json, + buffer_to_json_object, + get_json, + json_to_buffer, + set_json, +) +from zarr.core.buffer import cpu, default_buffer_prototype +from zarr.storage import MemoryStore +from zarr.storage._common import StorePath + +if TYPE_CHECKING: + from zarr.core.common import JSON + + +def test_json_to_buffer_round_trips() -> None: + """`buffer_to_json` inverts `json_to_buffer` for an arbitrary JSON value.""" + obj: JSON = {"zarr_format": 3, "node_type": "group", "attributes": {"a": [1, 2, 3]}} + buffer = json_to_buffer(obj) + assert buffer_to_json(buffer) == obj + + +def test_json_to_buffer_uses_given_prototype() -> None: + """`json_to_buffer` constructs the buffer from the supplied prototype.""" + prototype = default_buffer_prototype() + buffer = json_to_buffer({"x": 1}, prototype=prototype) + assert isinstance(buffer, prototype.buffer) + + +def test_json_to_buffer_allows_nan_by_default() -> None: + """`json_to_buffer` permits NaN by default (writes it as `NaN`).""" + buffer = json_to_buffer({"fill_value": math.nan}) + decoded = buffer_to_json(buffer) + assert isinstance(decoded, dict) + assert math.isnan(decoded["fill_value"]) + + +def test_json_to_buffer_allow_nan_false_rejects_nan() -> None: + """`json_to_buffer(allow_nan=False)` raises on a non-finite value.""" + with pytest.raises(ValueError, match="Out of range float"): + json_to_buffer({"fill_value": math.nan}, allow_nan=False) + + +def test_json_to_buffer_indent_controls_formatting() -> None: + """`json_to_buffer(indent=...)` controls whitespace in the serialized bytes.""" + obj: JSON = {"a": 1, "b": 2} + compact = json_to_buffer(obj).to_bytes() + indented = json_to_buffer(obj, indent=2).to_bytes() + assert b"\n" not in compact + assert b"\n" in indented + # both still round-trip to the same value + assert buffer_to_json(json_to_buffer(obj, indent=2)) == obj + + +async def test_get_json_reads_existing_key() -> None: + """`get_json` returns the parsed document stored at an existing key.""" + store = MemoryStore() + obj: JSON = {"zarr_format": 3, "node_type": "array"} + await set_json(store, "zarr.json", obj) + assert await get_json(store, "zarr.json") == obj + + +async def test_get_json_returns_none_for_missing_key() -> None: + """`get_json` returns None (rather than raising) when the key is absent.""" + store = MemoryStore() + assert await get_json(store, "does-not-exist") is None + + +async def test_set_json_then_get_json_round_trips() -> None: + """`set_json` followed by `get_json` returns the original value.""" + store = MemoryStore() + obj: JSON = {"a": 1, "b": [2, 3], "c": {"d": None}} + await set_json(store, "doc.json", obj) + assert await get_json(store, "doc.json") == obj + + +async def test_storepath_get_json_reads_existing_key() -> None: + """`StorePath.get_json` reads and parses the document at its own path.""" + store = MemoryStore() + obj: JSON = {"zarr_format": 2} + await set_json(store, "group/.zgroup", obj) + sp = StorePath(store, "group/.zgroup") + assert await sp.get_json() == obj + + +async def test_storepath_get_json_returns_none_for_missing() -> None: + """`StorePath.get_json` returns None when its path is absent.""" + store = MemoryStore() + sp = StorePath(store, "missing") + assert await sp.get_json() is None + + +def test_buffer_to_json_on_cpu_buffer() -> None: + """`buffer_to_json` works on a plain CPU buffer built from raw bytes.""" + buffer = cpu.Buffer.from_bytes(b'{"hello": "world"}') + assert buffer_to_json(buffer) == {"hello": "world"} + + +def test_buffer_to_json_object_returns_dict() -> None: + """`buffer_to_json_object` returns the parsed object as a dict.""" + buffer = cpu.Buffer.from_bytes(b'{"node_type": "group"}') + assert buffer_to_json_object(buffer) == {"node_type": "group"} + + +def test_buffer_to_json_object_rejects_non_object() -> None: + """`buffer_to_json_object` raises TypeError when the document is not an object.""" + buffer = cpu.Buffer.from_bytes(b"[1, 2, 3]") + with pytest.raises(TypeError, match="Expected a JSON object"): + buffer_to_json_object(buffer) diff --git a/tests/test_json_parse.py b/tests/test_json_parse.py new file mode 100644 index 0000000000..da723119aa --- /dev/null +++ b/tests/test_json_parse.py @@ -0,0 +1,122 @@ +"""Tests for :mod:`zarr.core.json_parse`. + +``convert`` delegates JSON type coercion to :func:`msgspec.convert` (translating +``msgspec.ValidationError`` into ``TypeError``); ``validate_json_value`` is the +hand-written fallback for the recursive ``JSON`` alias msgspec cannot build, +including a nesting-depth limit. The final group is a regression test for the +``parse_storage_transformers`` fix that motivated the depth limit work. +""" + +from __future__ import annotations + +from typing import Literal + +import pytest + +from zarr.core.json_parse import MAX_JSON_DEPTH, convert, parse_field, validate_json_value +from zarr.core.metadata.v3 import parse_storage_transformers + + +class TestConvert: + def test_literal(self) -> None: + assert convert(3, Literal[3]) == 3 + assert convert("array", Literal["array", "group"]) == "array" + + def test_literal_rejects_non_member(self) -> None: + with pytest.raises(ValueError, match="Expected instance of"): + convert(4, Literal[3]) + with pytest.raises(ValueError, match="Expected instance of"): + convert("Q", Literal["C", "F"]) + + def test_sequence_coerced_to_tuple(self) -> None: + assert convert([1, 2, 3], tuple[int, ...]) == (1, 2, 3) + assert convert([1, 2], tuple[int, int]) == (1, 2) + + def test_int(self) -> None: + assert convert(5, int) == 5 + + def test_bool_int_strictness(self) -> None: + # bool is an int subclass, but the two must not be interchangeable. + with pytest.raises(ValueError): + convert(True, int) + with pytest.raises(ValueError): + convert(1, bool) + # ... and True must not satisfy Literal[1]. + with pytest.raises(ValueError): + convert(True, Literal[1]) + + +class TestParseField: + def test_valid_passthrough(self) -> None: + assert parse_field(3, Literal[3], "zarr_format") == 3 + + def test_wraps_with_field_context(self) -> None: + with pytest.raises(ValueError, match="Failed to parse input for 'zarr_format'"): + parse_field(4, Literal[3], "zarr_format") + + def test_custom_error_type_and_chaining(self) -> None: + class MyError(ValueError): + pass + + with pytest.raises(MyError, match="Failed to parse input for 'node_type'") as exc_info: + parse_field(5, Literal["array"], "node_type", error=MyError) + # the generic type error is chained as the cause + assert isinstance(exc_info.value.__cause__, ValueError) + + +class TestValidateJsonValue: + @pytest.mark.parametrize("value", [None, True, 1, 1.5, "s"]) + def test_primitives(self, value: object) -> None: + assert validate_json_value(value) is value + + def test_nested(self) -> None: + value = {"a": [1, 2.0, "x", True, None], "b": {"c": [{}]}} + assert validate_json_value(value) is value + + def test_rejects_non_str_keys(self) -> None: + with pytest.raises(TypeError, match="keys must be str"): + validate_json_value({1: "x"}) + + def test_rejects_non_json_leaf(self) -> None: + with pytest.raises(TypeError, match="not a valid JSON value"): + validate_json_value(object()) + with pytest.raises(TypeError, match="not a valid JSON value"): + validate_json_value({"a": object()}) + + def test_depth_limit(self) -> None: + def nest(depth: int) -> object: + v: object = "leaf" + for _ in range(depth): + v = {"k": v} + return v + + # At the limit it passes; one level deeper it is rejected. This bound is + # new behavior the previous per-field parsers never had. + assert validate_json_value(nest(MAX_JSON_DEPTH)) is not None + with pytest.raises(ValueError, match="maximum depth"): + validate_json_value(nest(MAX_JSON_DEPTH + 1)) + + +class TestStorageTransformersRegression: + """`parse_storage_transformers` used to call `len(tuple(data))` and then + return `data` itself, exhausting a one-shot iterable and returning a value + typed as a tuple but not actually a tuple.""" + + def test_none(self) -> None: + assert parse_storage_transformers(None) == () + + def test_empty(self) -> None: + assert parse_storage_transformers([]) == () + + def test_list_returns_tuple(self) -> None: + result = parse_storage_transformers([{"a": 1}]) + assert result == ({"a": 1},) + assert isinstance(result, tuple) + + def test_generator_not_exhausted(self) -> None: + result = parse_storage_transformers(iter([{"a": 1}, {"b": 2}])) + assert result == ({"a": 1}, {"b": 2}) + + def test_non_iterable_rejected(self) -> None: + with pytest.raises(TypeError, match="Expected an iterable"): + parse_storage_transformers(5) diff --git a/tests/test_metadata/conftest.py b/tests/test_metadata/conftest.py new file mode 100644 index 0000000000..24f2417fce --- /dev/null +++ b/tests/test_metadata/conftest.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from zarr.codecs.bytes import BytesCodec + +if TYPE_CHECKING: + from zarr.core.metadata.v3 import ArrayMetadataJSON_V3 + + +def minimal_metadata_dict_v3( + extra_fields: dict[str, Any] | None = None, **overrides: Any +) -> ArrayMetadataJSON_V3: + """Build a minimal valid V3 array metadata JSON dict. + + The output matches the shape of ``ArrayV3Metadata.to_dict()`` — all + fields that ``to_dict`` always emits are included. + + Parameters + ---------- + extra_fields : dict, optional + Extra keys to inject into the dict (e.g. extension fields). + **overrides + Override any of the standard metadata fields. + """ + d: ArrayMetadataJSON_V3 = { + "zarr_format": 3, + "node_type": "array", + "shape": (4, 4), + "data_type": "uint8", + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (4, 4)}}, + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": 0, + "codecs": (BytesCodec().to_dict(),), # type: ignore[typeddict-item] + "attributes": {}, + "storage_transformers": (), + } + d.update(overrides) # type: ignore[typeddict-item] + if extra_fields is not None: + d.update(extra_fields) # type: ignore[typeddict-item] + return d diff --git a/tests/test_metadata/test_consolidated.py b/tests/test_metadata/test_consolidated.py index 9e8b763ef7..cd0fd92d74 100644 --- a/tests/test_metadata/test_consolidated.py +++ b/tests/test_metadata/test_consolidated.py @@ -51,6 +51,72 @@ async def memory_store_with_hierarchy(memory_store: Store) -> Store: class TestConsolidated: + @pytest.mark.filterwarnings("ignore:Consolidated metadata") + async def test_getitem_consolidated_empty_leaf_group( + self, memory_store: zarr.storage.MemoryStore, zarr_format: ZarrFormat + ) -> None: + # This test writes the bytes directly, rather than using the zarr API, to mimic + # how older versions of zarr-python wrote the consolidated metadata. + # Notably, zarr-python 2.x does not include a + # + # "consolidated_metadata": {"metadata": {}} + # + # field on the leaf group nodes. + if zarr_format == 2: + zmetadata: dict[str, JSON] = { + "metadata": { + ".zattrs": {}, + ".zgroup": {"zarr_format": 2}, + "raw/.zattrs": {}, + "raw/.zgroup": {"zarr_format": 2}, + "raw/varm/.zattrs": {}, + "raw/varm/.zgroup": {"zarr_format": 2}, + }, + "zarr_consolidated_format": 1, + } + await memory_store.set( + ".zgroup", cpu.Buffer.from_bytes(json.dumps({"zarr_format": 2}).encode()) + ) + await memory_store.set(".zattrs", cpu.Buffer.from_bytes(json.dumps({}).encode())) + await memory_store.set( + ".zmetadata", cpu.Buffer.from_bytes(json.dumps(zmetadata).encode()) + ) + + else: + zmetadata = { + "attributes": {}, + "zarr_format": 3, + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": { + "raw": { + "attributes": {}, + "zarr_format": 3, + "node_type": "group", + }, + "raw/varm": { + "attributes": {}, + "zarr_format": 3, + "node_type": "group", + }, + }, + }, + "node_type": "group", + } + await memory_store.set( + "zarr.json", cpu.Buffer.from_bytes(json.dumps(zmetadata).encode()) + ) + + group = await zarr.api.asynchronous.open_consolidated( + store=memory_store, zarr_format=zarr_format + ) + raw = await group.get_group("raw") + assert raw.metadata.consolidated_metadata is not None + + varm = await raw.get_group("varm") + assert varm.metadata.consolidated_metadata == ConsolidatedMetadata(metadata={}) + async def test_open_consolidated_false_raises(self) -> None: store = zarr.storage.MemoryStore() with pytest.raises(TypeError, match="use_consolidated"): @@ -702,8 +768,7 @@ async def test_absolute_path_for_subgroup(self, memory_store: zarr.storage.Memor await zarr.api.asynchronous.consolidate_metadata(memory_store) group = await zarr.api.asynchronous.open_group(store=memory_store) - subgroup = await group.getitem("/a") - assert isinstance(subgroup, AsyncGroup) + subgroup = await group.get_group("/a") members = [x async for x in subgroup.keys()] # noqa: SIM118 assert members == ["b"] @@ -774,3 +839,65 @@ async def test_open_group_in_non_consolidating_stores() -> None: # Opening a group with use_consolidated=True should fail with pytest.raises(ValueError, match="doesn't support consolidated metadata"): await AsyncGroup.open(memory_store, use_consolidated=True) + + +@pytest.mark.parametrize( + "order", + [ + # keys grouped by parent, the order zarr-python used to write before it + # started sorting the persisted keys + ["a", "b", "a/x", "a/y", "b/x", "b/y"], + # sibling subtrees interleaved, which is what the (depth, casefold) sort + # produces for names differing only by case + ["a", "b", "a/x", "b/x", "a/y", "b/y"], + # reversed, to cover a parent appearing after its children in the mapping + ["b/y", "b/x", "a/y", "a/x", "b", "a"], + ], +) +def test_flat_to_nested_is_order_independent(order: list[str]) -> None: + """The persisted key order is arbitrary, so nesting must not depend on it.""" + group_metadata: dict[str, JSON] = {"zarr_format": 3, "node_type": "group", "attributes": {}} + consolidated = ConsolidatedMetadata.from_dict( + { + "kind": "inline", + "must_understand": False, + "metadata": dict.fromkeys(order, group_metadata), + } + ) + + assert sorted(consolidated.metadata) == ["a", "b"] + for name in ("a", "b"): + child = consolidated.metadata[name] + assert isinstance(child, GroupMetadata) + assert child.consolidated_metadata is not None + assert sorted(child.consolidated_metadata.metadata) == ["x", "y"] + + +async def test_consolidated_metadata_case_differing_siblings(memory_store: Store) -> None: + """Sibling nodes whose names differ only by case each keep their own children. + + Regression test for https://github.com/zarr-developers/zarr-python/issues/4226 + """ + root = await zarr.api.asynchronous.create_group(store=memory_store) + for name in ("Study", "study"): + child = await root.create_group(f"obs/{name}") + await child.create_array(name="categories", shape=(2,), dtype="uint8") + await child.create_array(name="codes", shape=(2,), dtype="uint8") + + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await consolidate_metadata(memory_store) + + consolidated = await open_consolidated(store=memory_store) + result = sorted([key async for key, _ in consolidated.members(max_depth=None)]) + assert result == [ + "obs", + "obs/Study", + "obs/Study/categories", + "obs/Study/codes", + "obs/study", + "obs/study/categories", + "obs/study/codes", + ] diff --git a/tests/test_metadata/test_v2.py b/tests/test_metadata/test_v2.py index 8c3082e924..1358f458d6 100644 --- a/tests/test_metadata/test_v2.py +++ b/tests/test_metadata/test_v2.py @@ -29,9 +29,10 @@ def test_parse_zarr_format_valid() -> None: assert parse_zarr_format(2) == 2 -@pytest.mark.parametrize("data", [None, 1, 3, 4, 5, "3"]) +# The explicit id for "3" avoids colliding with the auto-generated id for the int 3. +@pytest.mark.parametrize("data", [None, 1, 3, 4, 5, pytest.param("3", id="3-str")]) def test_parse_zarr_format_invalid(data: Any) -> None: - with pytest.raises(ValueError, match=f"Invalid value. Expected 2. Got {data}"): + with pytest.raises(ValueError, match="Failed to parse input for 'zarr_format'"): parse_zarr_format(data) @@ -308,6 +309,60 @@ def test_from_dict_extra_fields() -> None: assert result == expected +def test_eq_nan_fill_value() -> None: + """Two metadata objects with an identical NaN fill_value compare equal. + + NaN is not equal to itself under IEEE 754, so the default dataclass __eq__ + reports two otherwise-identical metadata objects as unequal. Metadata + equality must treat matching NaN fill values as equal (see issue #2929). + """ + a = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + b = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + assert a == b + + +def test_eq_distinct_fill_value() -> None: + """Metadata objects that differ only in fill_value do not compare equal.""" + a = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=0.0, order="C") + b = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=1.0, order="C") + assert a != b + + +@pytest.mark.parametrize("fill_value", [np.float64("inf"), np.float64("-inf")]) +def test_eq_inf_fill_value(fill_value: np.float64) -> None: + """Two metadata objects with an identical infinite fill_value compare equal.""" + a = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=fill_value, order="C") + b = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=fill_value, order="C") + assert a == b + + +def test_hash_consistent_with_eq_nan_fill_value() -> None: + """Equal metadata objects with a NaN fill_value hash equal. + + NaN hashes by identity, so a field-based hash would break the + ``a == b implies hash(a) == hash(b)`` invariant for objects that compare + equal under the to_dict-based __eq__. + """ + a = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + b = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + assert a == b + assert hash(a) == hash(b) + + +def test_eq_non_metadata() -> None: + """Comparison against a non-metadata object returns False rather than erroring.""" + a = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=0.0, order="C") + assert a != object() + + def test_zstd_checksum() -> None: compressor_config: dict[str, JSON] = {"id": "zstd", "level": 5, "checksum": False} arr = zarr.create_array( diff --git a/tests/test_metadata/test_v3.py b/tests/test_metadata/test_v3.py index 01ed921053..d1e156e500 100644 --- a/tests/test_metadata/test_v3.py +++ b/tests/test_metadata/test_v3.py @@ -1,406 +1,327 @@ +"""Tests for zarr v3 metadata classes and parsing helpers.""" + from __future__ import annotations import json -import re -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np import pytest -from zarr import consolidate_metadata, create_group -from zarr.codecs.bytes import BytesCodec +from tests.conftest import Expect, ExpectFail +from tests.test_metadata.conftest import minimal_metadata_dict_v3 from zarr.core.buffer import default_buffer_prototype -from zarr.core.chunk_key_encodings import DefaultChunkKeyEncoding, V2ChunkKeyEncoding +from zarr.core.chunk_grids import is_regular_1d, is_regular_nd from zarr.core.config import config -from zarr.core.dtype import UInt8, get_data_type_from_native_dtype -from zarr.core.dtype.npy.string import _NUMPY_SUPPORTS_VLEN_STRING -from zarr.core.dtype.npy.time import DateTime64 +from zarr.core.dtype import Float64, UInt8 from zarr.core.group import GroupMetadata, parse_node_type +from zarr.core.metadata.v2 import ArrayV2Metadata from zarr.core.metadata.v3 import ( + ARRAY_METADATA_KEYS, ArrayMetadataJSON_V3, ArrayV3Metadata, parse_codecs, parse_dimension_names, + parse_node_type_array, parse_zarr_format, ) from zarr.errors import ( MetadataValidationError, NodeTypeValidationError, UnknownCodecError, - ZarrUserWarning, ) if TYPE_CHECKING: - from collections.abc import Sequence from typing import Any - from zarr.core.types import JSON - - from zarr.abc.codec import Codec - - -from zarr.core.metadata.v3 import ( - parse_node_type_array, -) -bool_dtypes = ("bool",) - -int_dtypes = ( - "int8", - "int16", - "int32", - "int64", - "uint8", - "uint16", - "uint32", - "uint64", -) +# --------------------------------------------------------------------------- +# Parsing helpers +# --------------------------------------------------------------------------- -float_dtypes = ( - "float16", - "float32", - "float64", -) -complex_dtypes = ("complex64", "complex128") -flexible_dtypes = ("str", "bytes", "void") -if _NUMPY_SUPPORTS_VLEN_STRING: - vlen_string_dtypes = ("T",) -else: - vlen_string_dtypes = ("O",) - -dtypes = ( - *bool_dtypes, - *int_dtypes, - *float_dtypes, - *complex_dtypes, - *flexible_dtypes, - *vlen_string_dtypes, -) +def test_parse_zarr_format_valid() -> None: + """The integer 3 is the only valid zarr_format for v3.""" + assert parse_zarr_format(3) == 3 @pytest.mark.parametrize("data", [None, 1, 2, 4, 5, "3"]) def test_parse_zarr_format_invalid(data: Any) -> None: - with pytest.raises( - MetadataValidationError, - match=f"Invalid value for 'zarr_format'. Expected '3'. Got '{data}'.", - ): + """Non-3 values are rejected.""" + with pytest.raises(MetadataValidationError): parse_zarr_format(data) -def test_parse_zarr_format_valid() -> None: - assert parse_zarr_format(3) == 3 - - def test_parse_node_type_valid() -> None: + """'array' and 'group' are the only valid node types.""" assert parse_node_type("array") == "array" assert parse_node_type("group") == "group" -@pytest.mark.parametrize("node_type", [None, 2, "other"]) -def test_parse_node_type_invalid(node_type: Any) -> None: - with pytest.raises( - MetadataValidationError, - match=f"Invalid value for 'node_type'. Expected 'array' or 'group'. Got '{node_type}'.", - ): - parse_node_type(node_type) +@pytest.mark.parametrize("data", [None, 2, "other"]) +def test_parse_node_type_invalid(data: Any) -> None: + """Non-string and unrecognized values are rejected.""" + with pytest.raises(MetadataValidationError): + parse_node_type(data) + + +def test_parse_node_type_array_valid() -> None: + """parse_node_type_array accepts only 'array'.""" + assert parse_node_type_array("array") == "array" @pytest.mark.parametrize("data", [None, "group"]) def test_parse_node_type_array_invalid(data: Any) -> None: - with pytest.raises( - NodeTypeValidationError, - match=f"Invalid value for 'node_type'. Expected 'array'. Got '{data}'.", - ): + """parse_node_type_array rejects 'group' and non-string values.""" + with pytest.raises(NodeTypeValidationError): parse_node_type_array(data) -def test_parse_node_typev_array_alid() -> None: - assert parse_node_type_array("array") == "array" +@pytest.mark.parametrize("data", [None, ("a", "b", "c"), ["a", "a", "a"], ()]) +def test_parse_dimension_names_valid(data: Any) -> None: + """None, tuples of strings, lists of strings, and empty tuples are accepted.""" + result = parse_dimension_names(data) + if data is None: + assert result is None + else: + assert result == tuple(data) -@pytest.mark.parametrize("data", [(), [1, 2, "a"], {"foo": 10}]) -def parse_dimension_names_invalid(data: Any) -> None: - with pytest.raises(TypeError, match="Expected either None or iterable of str,"): +@pytest.mark.parametrize("data", [[1, 2, "a"], [None, 3]]) +def test_parse_dimension_names_invalid(data: Any) -> None: + """Iterables containing non-string elements are rejected.""" + with pytest.raises(TypeError, match="Expected either None or"): parse_dimension_names(data) -@pytest.mark.parametrize("data", [None, ("a", "b", "c"), ["a", "a", "a"]]) -def parse_dimension_names_valid(data: Sequence[str] | None) -> None: - assert parse_dimension_names(data) == data +def test_parse_codecs_unknown_raises(monkeypatch: pytest.MonkeyPatch) -> None: + """An unregistered codec name raises UnknownCodecError.""" + from collections import defaultdict + import zarr.registry + from zarr.registry import Registry -@pytest.mark.parametrize("fill_value", [[1.0, 0.0], [0, 1]]) -@pytest.mark.parametrize("dtype_str", [*complex_dtypes]) -def test_jsonify_fill_value_complex(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) correctly handles complex values represented - as length-2 sequences - """ - zarr_format: Literal[3] = 3 - dtype = get_data_type_from_native_dtype(dtype_str) - expected = dtype.to_native_dtype().type(complex(*fill_value)) - observed = dtype.from_json_scalar(fill_value, zarr_format=zarr_format) - assert observed == expected - assert dtype.to_json_scalar(observed, zarr_format=zarr_format) == tuple(fill_value) + monkeypatch.setattr(zarr.registry, "_codec_registries", defaultdict(Registry)) + with pytest.raises(UnknownCodecError): + parse_codecs([{"name": "unknown"}]) -@pytest.mark.parametrize("fill_value", [{"foo": 10}]) -@pytest.mark.parametrize("dtype_str", [*int_dtypes, *float_dtypes, *complex_dtypes]) -def test_parse_fill_value_invalid_type(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) raises TypeError for invalid non-sequential types. - This test excludes bool because the bool constructor takes anything. - """ - dtype_instance = get_data_type_from_native_dtype(dtype_str) - with pytest.raises(TypeError, match=f"Invalid type: {fill_value}"): - dtype_instance.from_json_scalar(fill_value, zarr_format=3) +# --------------------------------------------------------------------------- +# Chunk-grid regularity helpers +# --------------------------------------------------------------------------- +# Cases used for both list/tuple (Python-sequence path) and ndarray (vectorized +# path) of `is_regular_1d`. Parametrizing the input form ensures both branches +# are exercised by the same suite of edge cases. +_REGULAR_1D_CASES: list[Expect[list[int], bool]] = [ + Expect(input=[], output=True, id="empty"), + Expect(input=[10], output=True, id="single-chunk"), + Expect(input=[10, 10, 10], output=True, id="all-equal"), + Expect(input=[10, 10, 10, 7], output=True, id="smaller-boundary"), + Expect(input=[10, 10, 10, 10], output=True, id="exact-multiple"), + Expect(input=[10, 5, 10], output=False, id="middle-mismatch"), + Expect(input=[10, 10, 10, 12], output=False, id="last-larger"), + # The first chunk anchors the size; later mismatches in the middle fail + # before the boundary check. + Expect(input=[5, 10, 5], output=False, id="middle-larger"), +] -@pytest.mark.parametrize( - "fill_value", - [ - [ - 1, - ], - (1, 23, 4), - ], -) -@pytest.mark.parametrize("dtype_str", [*int_dtypes, *float_dtypes]) -def test_parse_fill_value_invalid_type_sequence(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) raises TypeError for invalid sequential types. - This test excludes bool because the bool constructor takes anything, and complex because - complex values can be created from length-2 sequences. - """ - dtype_instance = get_data_type_from_native_dtype(dtype_str) - with pytest.raises(TypeError, match=re.escape(f"Invalid type: {fill_value}")): - dtype_instance.from_json_scalar(fill_value, zarr_format=3) +@pytest.mark.parametrize("case", _REGULAR_1D_CASES, ids=lambda c: c.id) +def test_is_regular_1d_sequence(case: Expect[list[int], bool]) -> None: + """`is_regular_1d` accepts plain Python sequences and uses the iterative path.""" + # list and tuple both go through the non-ndarray branch. + assert is_regular_1d(case.input) is case.output + assert is_regular_1d(tuple(case.input)) is case.output -@pytest.mark.parametrize("chunk_grid", ["regular"]) -@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) -@pytest.mark.parametrize("codecs", [[BytesCodec(endian=None)]]) -@pytest.mark.parametrize("fill_value", [0, 1]) -@pytest.mark.parametrize("chunk_key_encoding", ["v2", "default"]) -@pytest.mark.parametrize("dimension_separator", [".", "/", None]) -@pytest.mark.parametrize("dimension_names", ["nones", "strings", "missing"]) -@pytest.mark.parametrize("storage_transformers", [None, ()]) -def test_metadata_to_dict( - chunk_grid: str, - codecs: list[Codec], - fill_value: Any, - chunk_key_encoding: Literal["v2", "default"], - dimension_separator: Literal[".", "/"] | None, - dimension_names: Literal["nones", "strings", "missing"], - attributes: dict[str, Any] | None, - storage_transformers: tuple[dict[str, JSON]] | None, -) -> None: - shape = (1, 2, 3) - data_type_str = "uint8" - if chunk_grid == "regular": - cgrid = {"name": "regular", "configuration": {"chunk_shape": (1, 1, 1)}} - - cke: dict[str, Any] - cke_name_dict = {"name": chunk_key_encoding} - if dimension_separator is not None: - cke = cke_name_dict | {"configuration": {"separator": dimension_separator}} - else: - cke = cke_name_dict - dnames: tuple[str | None, ...] | None - if dimension_names == "strings": - dnames = tuple(map(str, range(len(shape)))) - elif dimension_names == "missing": - dnames = None - elif dimension_names == "nones": - dnames = (None,) * len(shape) +@pytest.mark.parametrize("case", _REGULAR_1D_CASES, ids=lambda c: c.id) +def test_is_regular_1d_ndarray(case: Expect[list[int], bool]) -> None: + """`is_regular_1d` accepts int64 ndarrays and uses the vectorized path.""" + arr = np.asarray(case.input, dtype=np.int64) + assert is_regular_1d(arr) is case.output - metadata_dict = { - "zarr_format": 3, - "node_type": "array", - "shape": shape, - "chunk_grid": cgrid, - "data_type": data_type_str, - "chunk_key_encoding": cke, - "codecs": tuple(c.to_dict() for c in codecs), - "fill_value": fill_value, - "storage_transformers": storage_transformers, - } - - if attributes is not None: - metadata_dict["attributes"] = attributes - if dnames is not None: - metadata_dict["dimension_names"] = dnames - metadata = ArrayV3Metadata.from_dict(metadata_dict) - observed = metadata.to_dict() - expected = metadata_dict.copy() - - # if unset or None or (), storage_transformers gets normalized to () - assert observed["storage_transformers"] == () - observed.pop("storage_transformers") - expected.pop("storage_transformers") +@pytest.mark.parametrize( + "case", + [ + Expect(input=[[10, 10, 10], [5, 5]], output=True, id="all-regular"), + Expect(input=[[10, 10, 7], [5, 5, 5, 3]], output=True, id="all-regular-with-boundary"), + Expect(input=[[10, 10, 10], [5, 8, 5]], output=False, id="second-dim-irregular"), + Expect(input=[[10, 5, 10], [5, 5]], output=False, id="first-dim-irregular"), + Expect(input=[], output=True, id="zero-dims"), + ], + ids=lambda c: c.id, +) +def test_is_regular_nd_sequence(case: Expect[list[list[int]], bool]) -> None: + """`is_regular_nd` returns True iff every per-dim spec is regular.""" + assert is_regular_nd(case.input) is case.output + # Same result via ndarray inputs. + assert is_regular_nd([np.asarray(d, dtype=np.int64) for d in case.input]) is case.output - if attributes is None: - assert observed["attributes"] == {} - observed.pop("attributes") - if dimension_separator is None: - if chunk_key_encoding == "default": - expected_cke_dict = DefaultChunkKeyEncoding(separator="/").to_dict() - else: - expected_cke_dict = V2ChunkKeyEncoding(separator=".").to_dict() - assert observed["chunk_key_encoding"] == expected_cke_dict - observed.pop("chunk_key_encoding") - expected.pop("chunk_key_encoding") - assert observed == expected +# --------------------------------------------------------------------------- +# Types +# --------------------------------------------------------------------------- -@pytest.mark.parametrize("indent", [2, 4, None]) -def test_json_indent(indent: int) -> None: - with config.set({"json_indent": indent}): - m = GroupMetadata() - d = m.to_buffer_dict(default_buffer_prototype())["zarr.json"].to_bytes() - assert d == json.dumps(json.loads(d), indent=indent).encode() +def test_array_metadata_keys_matches_typeddict() -> None: + """ + Test that the variable modelling the set of keys for array v3 metadata matches + the keys of the typeddict model for the metadata. + """ + assert ARRAY_METADATA_KEYS == set(ArrayMetadataJSON_V3.__annotations__.keys()) -@pytest.mark.parametrize("fill_value", [-1, 0, 1, 2932897]) -@pytest.mark.parametrize("precision", ["ns", "D"]) -async def test_datetime_metadata(fill_value: int, precision: Literal["ns", "D"]) -> None: - dtype = DateTime64(unit=precision) - metadata_dict: dict[str, Any] = { - "zarr_format": 3, - "node_type": "array", - "shape": (1,), - "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (1,)}}, - "data_type": dtype.to_json(zarr_format=3), - "chunk_key_encoding": {"name": "default", "separator": "."}, - "codecs": (BytesCodec(),), - "fill_value": dtype.to_json_scalar( - dtype.to_native_dtype().type(fill_value, dtype.unit), zarr_format=3 - ), - } - metadata = ArrayV3Metadata.from_dict(metadata_dict) - # ensure there isn't a TypeError here. - d = metadata.to_buffer_dict(default_buffer_prototype()) +# --------------------------------------------------------------------------- +# ArrayV3Metadata: round-trip +# --------------------------------------------------------------------------- - result = json.loads(d["zarr.json"].to_bytes()) - assert result["fill_value"] == fill_value +# Codecs after evolution for single-byte (uint8) and multi-byte (float64) types. +_UINT8_CODECS = ({"name": "bytes"},) +_FLOAT64_CODECS = ({"name": "bytes", "configuration": {"endian": "little"}},) @pytest.mark.parametrize( - ("data_type", "fill_value"), [("uint8", {}), ("int32", [0, 1]), ("float32", "foo")] + "case", + [ + Expect( + input={}, + output=minimal_metadata_dict_v3(codecs=_UINT8_CODECS), + id="minimal", + ), + Expect( + input={"attributes": {"key": "value"}}, + output=minimal_metadata_dict_v3(attributes={"key": "value"}, codecs=_UINT8_CODECS), + id="with_attributes", + ), + Expect( + input={"dimension_names": ("x", "y")}, + output=minimal_metadata_dict_v3(dimension_names=("x", "y"), codecs=_UINT8_CODECS), + id="with_dimension_names", + ), + Expect( + input={"storage_transformers": ()}, + output=minimal_metadata_dict_v3(storage_transformers=(), codecs=_UINT8_CODECS), + id="with_storage_transformers", + ), + Expect( + input={"data_type": "float64", "fill_value": 0.0}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value=0.0, codecs=_FLOAT64_CODECS + ), + id="float64", + ), + Expect( + input={"chunk_key_encoding": {"name": "v2", "configuration": {"separator": "."}}}, + output=minimal_metadata_dict_v3( + chunk_key_encoding={"name": "v2", "configuration": {"separator": "."}}, + codecs=_UINT8_CODECS, + ), + id="v2_chunk_key_encoding", + ), + Expect( + input={"data_type": "float64", "fill_value": "NaN"}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value="NaN", codecs=_FLOAT64_CODECS + ), + id="nan_fill_value", + ), + Expect( + input={"data_type": "float64", "fill_value": "Infinity"}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value="Infinity", codecs=_FLOAT64_CODECS + ), + id="inf_fill_value", + ), + Expect( + input={"data_type": "float64", "fill_value": "-Infinity"}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value="-Infinity", codecs=_FLOAT64_CODECS + ), + id="neg_inf_fill_value", + ), + Expect( + input={ + "attributes": {}, + "storage_transformers": (), + "extra_fields": {"my_ext": {"must_understand": False, "data": [1, 2, 3]}}, + }, + output=minimal_metadata_dict_v3( + attributes={}, + storage_transformers=(), + codecs=_UINT8_CODECS, + extra_fields={"my_ext": {"must_understand": False, "data": [1, 2, 3]}}, + ), + id="extra_fields", + ), + ], + ids=lambda case: case.id, ) -async def test_invalid_fill_value_raises(data_type: str, fill_value: float) -> None: - metadata_dict: dict[str, Any] = { - "zarr_format": 3, - "node_type": "array", - "shape": (1,), - "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (1,)}}, - "data_type": data_type, - "chunk_key_encoding": {"name": "default", "separator": "."}, - "codecs": ({"name": "bytes"},), - "fill_value": fill_value, # this is not a valid fill value for uint8 - } - # multiple things can go wrong here, so we don't match on the error message. - with pytest.raises(TypeError): - ArrayV3Metadata.from_dict(metadata_dict) +def test_array_metadata_roundtrip(case: Expect[dict[str, Any], dict[str, Any]]) -> None: + """from_dict(d).to_dict() produces the expected output, including codec evolution.""" + d = minimal_metadata_dict_v3(**case.input) + m = ArrayV3Metadata.from_dict(d) # type: ignore[arg-type] + assert m.to_dict() == case.output -@pytest.mark.parametrize("fill_value", [("NaN"), "Infinity", "-Infinity"]) -async def test_special_float_fill_values(fill_value: str) -> None: - metadata_dict: dict[str, Any] = { - "zarr_format": 3, - "node_type": "array", - "shape": (1,), - "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (1,)}}, - "data_type": "float64", - "chunk_key_encoding": {"name": "default", "separator": "."}, - "codecs": [{"name": "bytes"}], - "fill_value": fill_value, # this is not a valid fill value for uint8 - } - m = ArrayV3Metadata.from_dict(metadata_dict) - d = json.loads(m.to_buffer_dict(default_buffer_prototype())["zarr.json"].to_bytes()) - assert m.fill_value is not None - if fill_value == "NaN": - assert np.isnan(m.fill_value) - assert d["fill_value"] == "NaN" - elif fill_value == "Infinity": - assert np.isposinf(m.fill_value) - assert d["fill_value"] == "Infinity" - elif fill_value == "-Infinity": - assert np.isneginf(m.fill_value) - assert d["fill_value"] == "-Infinity" - - -def test_parse_codecs_unknown_codec_raises(monkeypatch: pytest.MonkeyPatch) -> None: - from collections import defaultdict +# --------------------------------------------------------------------------- +# ArrayV3Metadata: failure modes +# --------------------------------------------------------------------------- - import zarr.registry - from zarr.registry import Registry - - # to make sure the codec is always unknown (not sure if that's necessary) - monkeypatch.setattr(zarr.registry, "__codec_registries", defaultdict(Registry)) - codecs = [{"name": "unknown"}] - with pytest.raises(UnknownCodecError): - parse_codecs(codecs) +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"dimension_names": ("x", "y", "z")}, + exception=ValueError, + msg="dimension_names.*shape", + id="dimension_names_length_mismatch", + ), + ExpectFail( + input={"data_type": "uint8", "fill_value": {}}, + exception=TypeError, + id="invalid_fill_value_type", + ), + ], + ids=lambda case: case.id, +) +def test_array_metadata_from_dict_fails(case: ExpectFail[dict[str, Any]]) -> None: + """from_dict rejects invalid metadata documents.""" + d = minimal_metadata_dict_v3(**case.input) + with case.raises(): + ArrayV3Metadata.from_dict(d) # type: ignore[arg-type] @pytest.mark.parametrize( - "extra_value", + "case", [ - {"must_understand": False, "param": 10}, - {"must_understand": True}, - 10, + ExpectFail( + input=minimal_metadata_dict_v3(extra_fields={"my_ext": {"must_understand": True}}), + exception=MetadataValidationError, + msg="disallowed extra fields", + id="must_understand_true", + ), + ExpectFail( + input=minimal_metadata_dict_v3(extra_fields={"my_ext": 42}), + exception=MetadataValidationError, + msg="disallowed extra fields", + id="non_dict_extra_field", + ), ], + ids=lambda case: case.id, ) -def test_from_dict_extra_fields(extra_value: dict[str, object] | int) -> None: - """ - Test that from_dict accepts extra fields if they have are a JSON object with - "must_understand": false, and raises an exception otherwise. - """ - metadata_dict: ArrayMetadataJSON_V3 = { # type: ignore[typeddict-unknown-key] - "zarr_format": 3, - "node_type": "array", - "shape": (1,), - "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (1,)}}, - "data_type": "uint8", - "chunk_key_encoding": {"name": "default", "configuration": {"separator": "."}}, - "codecs": ({"name": "bytes"},), - "fill_value": 0, - "storage_transformers": (), - "attributes": {}, - "foo": extra_value, - } +def test_array_metadata_extra_fields_rejected(case: ExpectFail[dict[str, Any]]) -> None: + """from_dict rejects extra fields that don't conform to the spec.""" + with case.raises(): + ArrayV3Metadata.from_dict(case.input) - if isinstance(extra_value, dict) and extra_value.get("must_understand") is False: - # should be accepted - metadata = ArrayV3Metadata.from_dict(metadata_dict) # type: ignore[arg-type] - assert isinstance(metadata, ArrayV3Metadata) - assert metadata.to_dict() == metadata_dict - else: - # should raise an exception - with pytest.raises(MetadataValidationError, match="Got a Zarr V3 metadata document"): - metadata = ArrayV3Metadata.from_dict(metadata_dict) # type: ignore[arg-type] - -def test_init_invalid_extra_fields() -> None: - """ - Test that initializing ArrayV3Metadata with extra fields fails when those fields - shadow the array metadata fields. - """ +def test_init_extra_fields_collision() -> None: + """Extra field keys that collide with reserved metadata field names are rejected.""" extra_fields: dict[str, object] = {"shape": (10,), "data_type": "uint8"} - conflict_keys = set(extra_fields.keys()) - msg = ( - "Invalid extra fields. " - "The following keys: " - f"{sorted(conflict_keys)} " - "are invalid because they collide with keys reserved for use by the " - "array metadata document." - ) - with pytest.raises(ValueError, match=re.escape(msg)): + with pytest.raises(ValueError, match="collide with keys reserved"): ArrayV3Metadata( shape=(10,), data_type=UInt8(), @@ -414,50 +335,137 @@ def test_init_invalid_extra_fields() -> None: ) -@pytest.mark.parametrize("use_consolidated", [True, False]) -@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) -def test_group_to_dict(use_consolidated: bool, attributes: None | dict[str, Any]) -> None: +# --------------------------------------------------------------------------- +# Equality +# --------------------------------------------------------------------------- + + +def test_eq_nan_fill_value() -> None: + """Two metadata objects with an identical NaN fill_value compare equal. + + NaN is not equal to itself under IEEE 754, so the default dataclass __eq__ + reports two otherwise-identical metadata objects as unequal. Metadata + equality must treat matching NaN fill values as equal (see issue #2929). + """ + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + b = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + assert a == b + + +def test_eq_distinct_fill_value() -> None: + """Metadata objects that differ only in fill_value do not compare equal.""" + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=0.0)) # type: ignore[arg-type] + b = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=1.0)) # type: ignore[arg-type] + assert a != b + + +@pytest.mark.parametrize("fill_value", ["Infinity", "-Infinity"]) +def test_eq_inf_fill_value(fill_value: str) -> None: + """Two metadata objects with an identical infinite fill_value compare equal.""" + a = ArrayV3Metadata.from_dict( + minimal_metadata_dict_v3(data_type="float64", fill_value=fill_value) # type: ignore[arg-type] + ) + b = ArrayV3Metadata.from_dict( + minimal_metadata_dict_v3(data_type="float64", fill_value=fill_value) # type: ignore[arg-type] + ) + assert a == b + + +def test_hash_consistent_with_eq_nan_fill_value() -> None: + """Equal metadata objects with a NaN fill_value hash equal. + + NaN hashes by identity, so a field-based hash would break the + ``a == b implies hash(a) == hash(b)`` invariant for objects that compare + equal under the to_dict-based __eq__. """ - Test that the output of GroupMetadata.to_dict() is what we expect + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + b = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + assert a == b + assert hash(a) == hash(b) + + +def test_eq_non_metadata() -> None: + """Comparison against a non-metadata object returns False rather than erroring.""" + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=0.0)) # type: ignore[arg-type] + assert a != object() + + +def test_eq_across_zarr_formats() -> None: + """A v2 and v3 metadata describing the same array do not compare equal. + + Each __eq__ guards on its own concrete type and returns NotImplemented + otherwise, so the two versions are never equal even when they describe the + same array. """ - store: dict[str, object] = {} - if attributes is None: - expect_attributes = {} - else: - expect_attributes = attributes + v3 = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=0.0)) # type: ignore[arg-type] + v2 = ArrayV2Metadata(shape=(4, 4), dtype=Float64(), chunks=(4, 4), fill_value=0.0, order="C") + assert v2 != v3 + assert v3 != v2 + + +# --------------------------------------------------------------------------- +# JSON indent +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("indent", [2, 4, None]) +def test_json_indent(indent: int | None) -> None: + """The json_indent config setting controls indentation in to_buffer_dict output.""" + with config.set({"json_indent": indent}): + m = GroupMetadata() + d = m.to_buffer_dict(default_buffer_prototype())["zarr.json"].to_bytes() + assert d == json.dumps(json.loads(d), indent=indent).encode() + + +# --------------------------------------------------------------------------- +# GroupMetadata.to_dict +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) +def test_group_metadata_to_dict(attributes: dict[str, Any] | None) -> None: + """GroupMetadata.to_dict produces the expected v3 JSON structure.""" + meta = GroupMetadata(attributes=attributes) + assert meta.to_dict() == { + "zarr_format": 3, + "node_type": "group", + "attributes": attributes or {}, + } + +@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) +def test_group_metadata_to_dict_consolidated(attributes: dict[str, Any] | None) -> None: + """GroupMetadata.to_dict includes consolidated_metadata when present.""" + from zarr import consolidate_metadata, create_group + from zarr.errors import ZarrUserWarning + + store: dict[str, object] = {} group = create_group(store, attributes=attributes, zarr_format=3) group.create_group("foo") - if use_consolidated: - with pytest.warns( - ZarrUserWarning, - match="Consolidated metadata is currently not part in the Zarr format 3 specification.", - ): - group = consolidate_metadata(store) - meta = group.metadata - expect = { - "node_type": "group", - "zarr_format": 3, - "consolidated_metadata": { - "kind": "inline", - "must_understand": False, - "metadata": { - "foo": { - "attributes": {}, - "zarr_format": 3, - "node_type": "group", - "consolidated_metadata": { - "kind": "inline", - "metadata": {}, - "must_understand": False, - }, - } - }, - }, - "attributes": expect_attributes, - } - else: - meta = group.metadata - expect = {"node_type": "group", "zarr_format": 3, "attributes": expect_attributes} + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + group = consolidate_metadata(store) - assert meta.to_dict() == expect + assert group.metadata.to_dict() == { + "zarr_format": 3, + "node_type": "group", + "attributes": attributes or {}, + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": { + "foo": { + "attributes": {}, + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "metadata": {}, + "must_understand": False, + }, + } + }, + }, + } diff --git a/tests/test_pipeline_parity.py b/tests/test_pipeline_parity.py new file mode 100644 index 0000000000..94d95c4c24 --- /dev/null +++ b/tests/test_pipeline_parity.py @@ -0,0 +1,523 @@ +"""Pipeline parity test — exhaustive matrix of read/write scenarios. + +For every cell of the matrix (codec config x layout x operation +sequence x runtime config), assert that ``FusedCodecPipeline`` and +``BatchedCodecPipeline`` produce semantically identical results: + + * Same returned array contents on read. + * Same set of store keys after writes (catches divergent empty-shard + handling: one pipeline deletes, the other writes an empty blob). + * Reading each pipeline's store contents through the *other* pipeline + yields the same array (catches "wrote a layout that only one + pipeline can read" bugs). + +Pipeline-divergence bugs (e.g. one pipeline writes a dense shard +layout while the other writes a compact layout) fail this test +loudly with a clear diff, instead of waiting for a downstream +test to trip over the symptom. + +Byte-for-byte equality of store contents is intentionally NOT +checked: codecs like gzip embed the wall-clock timestamp in their +output, so two compressions of the same data done at different +seconds produce different bytes despite being semantically +identical. + +The matrix axes are: + + * codec chain — bytes-only, gzip, with/without sharding + * layout — chunk_shape, shard_shape (None for no sharding) + * write sequence — full overwrite, partial in middle, scalar to one + cell, multiple overlapping writes, sequence ending in fill values + * runtime config — write_empty_chunks True/False +""" + +from __future__ import annotations + +import warnings +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.sharding import ( + SUBCHUNK_WRITE_ORDER, + IndexLocation, + ShardingCodec, + SubchunkWriteOrder, +) +from zarr.codecs.transpose import TransposeCodec +from zarr.core.config import config as zarr_config +from zarr.errors import ZarrUserWarning +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + +# --------------------------------------------------------------------------- +# Reference helpers +# --------------------------------------------------------------------------- + + +def _store_snapshot(store: MemoryStore) -> dict[str, bytes]: + """Return {key: bytes} for every entry in the store.""" + return {k: bytes(v.to_bytes()) for k, v in store._store_dict.items()} + + +# --------------------------------------------------------------------------- +# Matrix definitions +# --------------------------------------------------------------------------- + + +# Each codec config is (filters, serializer, compressors). We only vary the +# pieces that actually affect the pipeline. compressors=None means a +# fixed-size chain (the byte-range fast path is eligible when sharded). +CodecConfig = dict[str, Any] + +CODEC_CONFIGS: list[tuple[str, CodecConfig]] = [ + ("bytes-only", {"compressors": None}), + ("gzip", {"compressors": GzipCodec(level=1)}), + # Big-endian serializer: the on-disk byte order is carried by the BytesCodec, + # not the dtype. Guards the bulk whole-shard decode against ignoring endian + # (it would otherwise reinterpret big-endian bytes as native — silent + # corruption). dtype is int32 so endianness is observable. + ( + "bytes-big-endian", + {"compressors": None, "serializer": BytesCodec(endian="big"), "dtype": "int32"}, + ), + # crc32c as a bytes->bytes codec after the serializer: the bulk fast path + # must NOT silently drop checksum verification (it falls through to the + # per-chunk path). Parity still requires identical bytes + contents across + # pipelines. (crc32c is a BytesBytesCodec, so it goes in `compressors`.) + ( + "bytes-crc32c", + {"compressors": [Crc32cCodec()], "serializer": BytesCodec(), "dtype": "int32"}, + ), +] + + +# (id, kwargs) — chunks/shards layout. kwargs are passed to create_array. +LayoutConfig = dict[str, Any] + +LAYOUT_CONFIGS: list[tuple[str, LayoutConfig]] = [ + ("1d-unsharded", {"shape": (100,), "chunks": (10,), "shards": None}), + ("1d-1chunk-per-shard", {"shape": (100,), "chunks": (10,), "shards": (10,)}), + ("1d-multi-chunk-per-shard", {"shape": (100,), "chunks": (10,), "shards": (50,)}), + ("2d-unsharded", {"shape": (20, 20), "chunks": (5, 5), "shards": None}), + ("2d-sharded", {"shape": (20, 20), "chunks": (5, 5), "shards": (10, 10)}), + # Nested sharding: outer chunk (10,10) sharded into inner chunks (5,5). + # Restricted to the codec configs that don't set their own `serializer` + # (bytes-only, gzip): this layout supplies an explicit nested-ShardingCodec + # `serializer`, and a codec config that also sets `serializer` (e.g. + # bytes-big-endian) would silently clobber it via dict merge, dropping + # sharding from the test entirely rather than exercising it. The gzip + # config applies as an outer bytes-bytes codec around the outer + # ShardingCodec -- this is the regression coverage for the fused pipeline + # applying outer AA/BB codecs around sharding (see + # `pipeline_supports_partial_decode`/`pipeline_supports_partial_encode`). + ( + "2d-nested-sharded", + { + "shape": (20, 20), + "chunks": (10, 10), + "shards": None, + "serializer": ShardingCodec( + chunk_shape=(10, 10), + codecs=[ShardingCodec(chunk_shape=(5, 5))], + ), + "_codec_ids": {"bytes-only", "gzip"}, + }, + ), +] + + +WriteOp = tuple[Any, Any] # (selection, value) +WriteSequence = tuple[str, list[WriteOp]] + + +def _full_overwrite(shape: tuple[int, ...]) -> list[WriteOp]: + return [((slice(None),) * len(shape), np.arange(int(np.prod(shape))).reshape(shape) + 1)] + + +def _partial_middle(shape: tuple[int, ...]) -> list[WriteOp]: + if len(shape) == 1: + n = shape[0] + return [((slice(n // 4, 3 * n // 4),), 7)] + # 2D: write a centered block + rs = slice(shape[0] // 4, 3 * shape[0] // 4) + cs = slice(shape[1] // 4, 3 * shape[1] // 4) + return [((rs, cs), 7)] + + +def _scalar_one_cell(shape: tuple[int, ...]) -> list[WriteOp]: + if len(shape) == 1: + return [((shape[0] // 2,), 99)] + return [((shape[0] // 2, shape[1] // 2), 99)] + + +def _overlapping(shape: tuple[int, ...]) -> list[WriteOp]: + if len(shape) == 1: + n = shape[0] + return [ + ((slice(0, n // 2),), 1), + ((slice(n // 4, 3 * n // 4),), 2), + ((slice(n // 2, n),), 3), + ] + rs1, cs1 = slice(0, shape[0] // 2), slice(0, shape[1] // 2) + rs2, cs2 = slice(shape[0] // 4, 3 * shape[0] // 4), slice(shape[1] // 4, 3 * shape[1] // 4) + return [((rs1, cs1), 1), ((rs2, cs2), 2)] + + +def _ends_in_fill(shape: tuple[int, ...]) -> list[WriteOp]: + """Write something then overwrite it with fill — exercises empty-chunk handling.""" + full = (slice(None),) * len(shape) + return [(full, 5), (full, 0)] + + +def _ends_in_partial_fill(shape: tuple[int, ...]) -> list[WriteOp]: + """Write data, then overwrite half with fill — some chunks become empty.""" + full: tuple[slice, ...] + half: tuple[slice, ...] + if len(shape) == 1: + full = (slice(None),) + half = (slice(0, shape[0] // 2),) + else: + full = (slice(None), slice(None)) + half = (slice(0, shape[0] // 2), slice(None)) + return [(full, 5), (half, 0)] + + +SEQUENCES: list[tuple[str, Callable[[tuple[int, ...]], list[WriteOp]]]] = [ + ("full-overwrite", _full_overwrite), + ("partial-middle", _partial_middle), + ("scalar-one-cell", _scalar_one_cell), + ("overlapping", _overlapping), + ("ends-in-fill", _ends_in_fill), + ("ends-in-partial-fill", _ends_in_partial_fill), +] + + +WRITE_EMPTY_CHUNKS = [False, True] + + +# --------------------------------------------------------------------------- +# Matrix iteration (pruned) +# --------------------------------------------------------------------------- + + +def _matrix() -> Iterator[Any]: + for codec_id, codec_kwargs in CODEC_CONFIGS: + for layout_id, layout in LAYOUT_CONFIGS: + allowed = layout.get("_codec_ids") + if allowed is not None and codec_id not in allowed: + continue + for seq_id, seq_fn in SEQUENCES: + for wec in WRITE_EMPTY_CHUNKS: + yield pytest.param( + codec_kwargs, + layout, + seq_fn, + wec, + id=f"{layout_id}-{codec_id}-{seq_id}-wec{wec}", + ) + + +# --------------------------------------------------------------------------- +# The parity test +# --------------------------------------------------------------------------- + + +@contextmanager +def _ignore_sharding_combo_warning() -> Iterator[None]: + """Suppress the "combining sharding_indexed disables partial reads" warning. + + Only the nested-sharded-plus-outer-codec matrix cell emits this; scoping the + ignore filter to just its message/category (rather than blanket-disabling + warnings) keeps every other warning in the run promoted to an error as usual. + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=r"Combining a `sharding_indexed` codec.*", + category=ZarrUserWarning, + ) + yield + + +def _write_under_pipeline( + pipeline_path: str, + codec_kwargs: CodecConfig, + layout: LayoutConfig, + sequence: list[WriteOp], + write_empty_chunks: bool, +) -> tuple[MemoryStore, Any]: + """Apply a sequence of writes via the chosen pipeline. + + Returns (store with the written data, final array contents read back). + """ + # Strip private metadata keys (e.g. "_codec_ids") before passing to create_array. + array_layout = {k: v for k, v in layout.items() if not k.startswith("_")} + # dtype defaults to float64 but a codec config may override it (e.g. an + # endian-sensitive int dtype). Merge so the override wins without a dup kwarg. + create_kwargs = {"dtype": "float64", **array_layout, **codec_kwargs} + store = MemoryStore() + with zarr_config.set({"codec_pipeline.path": pipeline_path}): + with _ignore_sharding_combo_warning(): + arr = zarr.create_array( + store=store, + fill_value=0, + config={"write_empty_chunks": write_empty_chunks}, + **create_kwargs, + ) + for sel, val in sequence: + arr[sel] = val + contents = arr[...] + return store, contents + + +def _read_under_pipeline(pipeline_path: str, store: MemoryStore) -> Any: + """Re-open an existing store under the chosen pipeline and read it whole.""" + with zarr_config.set({"codec_pipeline.path": pipeline_path}): + with _ignore_sharding_combo_warning(): + arr = zarr.open_array(store=store, mode="r") + return arr[...] + + +_BATCHED = "zarr.core.codec_pipeline.BatchedCodecPipeline" +_FUSED = "zarr.core.codec_pipeline.FusedCodecPipeline" + + +@pytest.mark.parametrize( + ("codec_kwargs", "layout", "sequence_fn", "write_empty_chunks"), + list(_matrix()), +) +def test_pipeline_parity( + codec_kwargs: CodecConfig, + layout: LayoutConfig, + sequence_fn: Callable[[tuple[int, ...]], list[WriteOp]], + write_empty_chunks: bool, +) -> None: + """FusedCodecPipeline must be semantically identical to BatchedCodecPipeline. + + Three checks, in order of decreasing diagnostic value: + + 1. Both pipelines return the same array contents after the same + write sequence (catches semantic correctness bugs). + 2. Both pipelines produce the same set of store keys (catches + empty-shard divergence: one deletes, the other doesn't). + 3. Each pipeline can correctly read the *other* pipeline's + output (catches layout-divergence bugs that would prevent + interop, e.g. dense vs compact shard layouts). + + Byte-for-byte store equality is intentionally not checked: codecs + like gzip embed wall-clock timestamps that vary between runs. + """ + sequence = sequence_fn(layout["shape"]) + + batched_store, batched_arr = _write_under_pipeline( + _BATCHED, codec_kwargs, layout, sequence, write_empty_chunks + ) + sync_store, sync_arr = _write_under_pipeline( + _FUSED, codec_kwargs, layout, sequence, write_empty_chunks + ) + + # 1. Array contents must agree. + np.testing.assert_array_equal( + sync_arr, + batched_arr, + err_msg="FusedCodecPipeline returned different array contents than BatchedCodecPipeline", + ) + + # 2. Store key sets must agree. + batched_keys = set(batched_store._store_dict) - {"zarr.json"} + sync_keys = set(sync_store._store_dict) - {"zarr.json"} + assert sync_keys == batched_keys, ( + f"Pipelines disagree on which store keys exist.\n" + f" only in batched: {sorted(batched_keys - sync_keys)}\n" + f" only in sync: {sorted(sync_keys - batched_keys)}" + ) + + # 3. Cross-read: each pipeline must correctly read the other's output. + sync_reads_batched = _read_under_pipeline(_FUSED, batched_store) + batched_reads_sync = _read_under_pipeline(_BATCHED, sync_store) + np.testing.assert_array_equal( + sync_reads_batched, + batched_arr, + err_msg="FusedCodecPipeline could not correctly read BatchedCodecPipeline's output", + ) + np.testing.assert_array_equal( + batched_reads_sync, + sync_arr, + err_msg="BatchedCodecPipeline could not correctly read FusedCodecPipeline's output", + ) + + +# --------------------------------------------------------------------------- +# Partial-read parity across subchunk write orders +# --------------------------------------------------------------------------- +# +# Note: general partial-read coverage (scalar single-element and strided reads +# from sharded arrays, which hit the sharding codec's partial-decode path) lives +# in tests/test_codec_pipeline_suite.py as Scenarios. Those run each pipeline +# against a numpy reference -- strictly stronger than checking the two pipelines +# only against each other, and they cover both the sync (_decode_partial_sync) +# and async (_decode_partial_single) partial-decode variants. What remains here +# is the cross-pipeline byte-identical-layout check, which the per-pipeline +# suite structurally cannot express. + + +@pytest.mark.parametrize("subchunk_write_order", SUBCHUNK_WRITE_ORDER) +@pytest.mark.parametrize("index_location", ["start", "end"]) +def test_pipeline_parity_subchunk_write_order( + subchunk_write_order: SubchunkWriteOrder, index_location: IndexLocation +) -> None: + """Both pipelines must agree across every subchunk_write_order, including a + PARTIAL write into an already-dense fixed-size shard. + + This is the regression net for the byte-range write fast path, which derives + each chunk's physical slot from its rank in subchunk_write_order. A wrong + (e.g. hardcoded morton) assumption corrupts non-default orders silently, so + we assert both identical contents AND identical stored bytes across pipelines. + write_empty_chunks=True keeps every slot present, making the shard dense and + the byte-range write path eligible. + """ + # 2D, fixed-size (no compression). The shard (array `chunks`) must hold + # MULTIPLE inner chunks, and be non-square, so morton / lexicographic / + # colexicographic produce physically DIFFERENT layouts — with one inner + # chunk per shard all orders coincide and a wrong-order bug is invisible. + # inner chunk = (2, 2); shard = (6, 4) -> a 3x2 grid of inner chunks. + shape, shard_shape, inner_chunk = (12, 8), (6, 4), (2, 2) + serializer = ShardingCodec( + chunk_shape=inner_chunk, + codecs=[BytesCodec()], + index_location=index_location, + subchunk_write_order=subchunk_write_order, + ) + ref = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + + def run(pipeline_path: str) -> tuple[dict[str, bytes], Any]: + store = MemoryStore() + with zarr_config.set({"codec_pipeline.path": pipeline_path}): + arr = zarr.create_array( + store=store, + shape=shape, + chunks=shard_shape, # array "chunks" == shard size for a ShardingCodec serializer + dtype="int32", + fill_value=-1, + serializer=serializer, + compressors=None, + config={"write_empty_chunks": True}, + ) + arr[:] = ref # dense full write + arr[3:9, 1:6] = 777 # partial write INTO the dense shard + contents = arr[...] + return _store_snapshot(store), contents + + batched_bytes, batched_contents = run(_BATCHED) + sync_bytes, sync_contents = run(_FUSED) + + # Contents must always match across pipelines and equal the reference — + # this catches a wrong-order byte-range write (it corrupts the data). + expected = ref.copy() + expected[3:9, 1:6] = 777 + np.testing.assert_array_equal(batched_contents, expected) + np.testing.assert_array_equal( + sync_contents, + batched_contents, + err_msg=f"pipeline contents diverged for subchunk_write_order={subchunk_write_order!r}", + ) + # The two pipelines must also produce byte-identical shards — a stronger + # check that they agree on physical layout. This holds for EVERY order + # (without special-casing any by name): both pipelines lay chunks out via + # the same `_subchunk_order_iter`, so for a given codec instance they must + # land on the same bytes whatever that order resolves to. We make no + # assumption here about what any particular order "means" — only that the + # two implementations agree. + assert sync_bytes == batched_bytes, ( + f"pipelines wrote different bytes for subchunk_write_order={subchunk_write_order!r} " + f"(index_location={index_location!r}) — byte-range write fast path likely assumed " + f"the wrong physical chunk order" + ) + + +# --------------------------------------------------------------------------- +# Outer array-array / bytes-bytes codecs around a sharding serializer +# --------------------------------------------------------------------------- +# +# Regression coverage for FusedCodecPipeline.supports_partial_decode/encode: +# it used to allow AA/BB codecs outside the sharding codec, so its partial +# branches called ShardingCodec._decode_partial_sync/_encode_partial_sync +# directly on the raw stored value, skipping any outer filter/compressor. +# That corrupted on-disk bytes for an outer bytes-bytes codec (unreadable by +# the other pipeline) and silently produced wrong data for an outer +# array-array codec. Both configs below force the partial branches: a +# region write and a region read are included alongside the full ones. + +_OUTER_AA_BB_CONFIGS: list[tuple[str, CodecConfig]] = [ + ( + "outer-gzip-around-sharding", + { + "serializer": ShardingCodec(chunk_shape=(2, 2)), + "compressors": [GzipCodec(level=1)], + }, + ), + ( + "outer-transpose-around-sharding", + { + "filters": [TransposeCodec(order=(1, 0))], + "serializer": ShardingCodec(chunk_shape=(2, 2)), + "compressors": None, + }, + ), +] + + +@pytest.mark.parametrize(("config_id", "codec_kwargs"), _OUTER_AA_BB_CONFIGS) +@pytest.mark.parametrize( + ("writer", "reader"), + [(_BATCHED, _FUSED), (_FUSED, _BATCHED)], + ids=["batched-write-fused-read", "fused-write-batched-read"], +) +def test_pipeline_parity_outer_aa_bb_codecs( + config_id: str, + codec_kwargs: CodecConfig, + writer: str, + reader: str, +) -> None: + """Data written under one pipeline with outer AA/BB codecs must read back + correctly under the other, including through a partial write and a + partial read. + """ + shape = (8, 8) + data = (np.arange(int(np.prod(shape))).reshape(shape) + 1).astype("uint16") + store = MemoryStore() + + with zarr_config.set({"codec_pipeline.path": writer}): + with _ignore_sharding_combo_warning(): + arr = zarr.create_array( + store=store, + shape=shape, + chunks=(4, 4), + dtype=data.dtype, + fill_value=0, + **codec_kwargs, + ) + arr[...] = data + arr[2:5, 1:3] = 99 # region write -- exercises the partial-encode branch + + expected = data.copy() + expected[2:5, 1:3] = 99 + + with zarr_config.set({"codec_pipeline.path": reader}): + with _ignore_sharding_combo_warning(): + arr2 = zarr.open_array(store=store, mode="r") + full = arr2[...] + partial = arr2[1:3, 2:7] # region read -- exercises the partial-decode branch + + np.testing.assert_array_equal(full, expected) + np.testing.assert_array_equal(partial, expected[1:3, 2:7]) diff --git a/tests/test_properties.py b/tests/test_properties.py index bab659c976..33888bfd4e 100644 --- a/tests/test_properties.py +++ b/tests/test_properties.py @@ -1,12 +1,14 @@ import itertools import json import numbers +from collections.abc import Generator from typing import Any import numpy as np import pytest from numpy.testing import assert_array_equal +import zarr from zarr.core.buffer import default_buffer_prototype pytest.importorskip("hypothesis") @@ -23,14 +25,25 @@ array_metadata, arrays, basic_indices, + block_indices, + block_test_arrays, + complex_rectilinear_arrays, numpy_arrays, orthogonal_indices, + rectilinear_arrays, simple_arrays, stores, zarr_formats, ) +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None, None, None]: + """Enable rectilinear chunks for all property tests since strategies may generate them.""" + with zarr.config.set({"array.rectilinear_chunks": True}): + yield + + def deep_equal(a: Any, b: Any) -> bool: """Deep equality check with handling of special cases for array metadata classes""" if isinstance(a, (complex, np.complexfloating)) and isinstance( @@ -106,12 +119,11 @@ def test_array_creates_implicit_groups(array): # this decorator removes timeout; not ideal but it should avoid intermittent CI failures -@pytest.mark.asyncio @settings(deadline=None) @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") @given(data=st.data()) async def test_basic_indexing(data: st.DataObject) -> None: - zarray = data.draw(simple_arrays()) + zarray = data.draw(st.one_of(simple_arrays(), rectilinear_arrays())) nparray = zarray[:] indexer = data.draw(basic_indices(shape=nparray.shape)) @@ -133,12 +145,25 @@ async def test_basic_indexing(data: st.DataObject) -> None: # TODO test async setitem? -@pytest.mark.asyncio +@settings(deadline=None) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +async def test_basic_indexing_complex_rectilinear(data: st.DataObject) -> None: + nparray, zarray = data.draw(complex_rectilinear_arrays()) + indexer = data.draw(basic_indices(shape=nparray.shape)) + assert_array_equal(nparray[indexer], zarray[indexer]) + + @given(data=st.data()) @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") async def test_oindex(data: st.DataObject) -> None: # integer_array_indices can't handle 0-size dimensions. - zarray = data.draw(simple_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1))) + zarray = data.draw( + st.one_of( + simple_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1)), + rectilinear_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1, max_side=20)), + ) + ) nparray = zarray[:] zindexer, npindexer = data.draw(orthogonal_indices(shape=nparray.shape)) @@ -165,12 +190,16 @@ async def test_oindex(data: st.DataObject) -> None: # note: async oindex setitem not yet implemented -@pytest.mark.asyncio @given(data=st.data()) @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") async def test_vindex(data: st.DataObject) -> None: # integer_array_indices can't handle 0-size dimensions. - zarray = data.draw(simple_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1))) + zarray = data.draw( + st.one_of( + simple_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1)), + rectilinear_arrays(shapes=npst.array_shapes(max_dims=3, min_side=1, max_side=20)), + ) + ) nparray = zarray[:] indexer = data.draw( npst.integer_array_indices( @@ -199,6 +228,59 @@ async def test_vindex(data: st.DataObject) -> None: # note: async vindex setitem not yet implemented +@settings(deadline=None) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +def test_mask_indexing(data: st.DataObject) -> None: + zarray = data.draw(st.one_of(simple_arrays(), rectilinear_arrays())) + nparray = zarray[:] + mask = data.draw(npst.arrays(dtype=np.bool_, shape=st.just(nparray.shape))) + + expected = nparray[mask] + + # sync get, via both the dedicated method and the vindex interface + assert_array_equal(expected, zarray.get_mask_selection(mask)) + assert_array_equal(expected, zarray.vindex[mask]) + + # sync set, via both interfaces + assume(zarray.shards is None) # GH2834 + new_data = data.draw(numpy_arrays(shapes=st.just(expected.shape), dtype=nparray.dtype)) + nparray[mask] = new_data + zarray.set_mask_selection(mask, new_data) + assert_array_equal(nparray, zarray[:]) + + zarray.vindex[mask] = new_data + assert_array_equal(nparray, zarray[:]) + + +@settings(deadline=None) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +def test_block_indexing(data: st.DataObject) -> None: + # Block indexing addresses whole inner chunks. block_indices() builds its + # array-space oracle from cumulative chunk offsets, so it works for regular + # (uniform), rectilinear, and sharded grids alike; block_test_arrays draws + # across that matrix (rectilinear + sharded is unsupported and not drawn). + zarray, nparray = data.draw(block_test_arrays()) + + block_indexer, array_indexer = data.draw(block_indices(chunk_sizes=zarray.write_chunk_sizes)) + expected = nparray[array_indexer] + + # sync get, via both the .blocks interface and the dedicated method + assert_array_equal(expected, zarray.blocks[block_indexer]) + assert_array_equal(expected, zarray.get_block_selection(block_indexer)) + + # sync set, via both interfaces; sharded set is broken upstream (GH2834) + assume(zarray.shards is None) + new_data = data.draw(numpy_arrays(shapes=st.just(expected.shape), dtype=nparray.dtype)) + nparray[array_indexer] = new_data + zarray.blocks[block_indexer] = new_data + assert_array_equal(nparray, zarray[:]) + + zarray.set_block_selection(block_indexer, new_data) + assert_array_equal(nparray, zarray[:]) + + @given(store=stores, meta=array_metadata()) # type: ignore[misc] @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") async def test_roundtrip_array_metadata_from_store( diff --git a/tests/test_regression/scripts/v2.18.py b/tests/test_regression/scripts/v2.18.py index 39e1c5210c..4c730b9c79 100644 --- a/tests/test_regression/scripts/v2.18.py +++ b/tests/test_regression/scripts/v2.18.py @@ -1,5 +1,5 @@ # /// script -# requires-python = ">=3.11" +# requires-python = ">=3.12" # dependencies = [ # "zarr==2.18", # "numcodecs==0.15" diff --git a/tests/test_regression/test_v2_dtype_regression.py b/tests/test_regression/test_v2_dtype_regression.py index 4f3329e88c..faba087e32 100644 --- a/tests/test_regression/test_v2_dtype_regression.py +++ b/tests/test_regression/test_v2_dtype_regression.py @@ -1,4 +1,5 @@ import subprocess +import sys from dataclasses import dataclass from itertools import product from pathlib import Path @@ -193,6 +194,10 @@ def source_array_v3(tmp_path: Path, request: pytest.FixtureRequest) -> ArrayV3: script_paths = [Path(__file__).resolve().parent / "scripts" / "v2.18.py"] +@pytest.mark.skipif( + sys.platform == "darwin" and sys.version_info >= (3, 14), + reason="Numcodecs pinned to 0.15 does not build on newer macos installations with newer python versions: see discussion https://github.com/zarr-developers/zarr-python/pull/3564#issuecomment-4081145034", +) @pytest.mark.skipif(not runner_installed(), reason="no python script runner installed") @pytest.mark.parametrize( "source_array_v2", array_cases_v2_18, indirect=True, ids=tuple(map(str, array_cases_v2_18)) @@ -210,8 +215,9 @@ def test_roundtrip_v2(source_array_v2: ArrayV2, tmp_path: Path, script_path: Pat ], capture_output=True, text=True, + check=False, ) - assert copy_op.returncode == 0 + assert copy_op.returncode == 0, f"stdout {copy_op.stdout}\n stderr{copy_op.stderr}" out_array = zarr.open_array(store=out_path, mode="r", zarr_format=2) assert source_array_v2.metadata.to_dict() == out_array.metadata.to_dict() assert np.array_equal(source_array_v2[:], out_array[:]) @@ -235,6 +241,7 @@ def test_roundtrip_v3(source_array_v3: ArrayV3, tmp_path: Path) -> None: ], capture_output=True, text=True, + check=False, ) assert copy_op.returncode == 0 out_array = zarr.open_array(store=out_path, mode="r", zarr_format=3) diff --git a/tests/test_store/test_core.py b/tests/test_store/test_core.py index 6589c68e09..7ba4344810 100644 --- a/tests/test_store/test_core.py +++ b/tests/test_store/test_core.py @@ -1,16 +1,24 @@ import tempfile -from collections.abc import Callable, Generator +from collections.abc import Awaitable, Callable, Generator from pathlib import Path from typing import Any, Literal import pytest -from _pytest.compat import LEGACY_PATH +from packaging.version import parse as parse_version import zarr from zarr import Group -from zarr.core.common import AccessModeLiteral, ZarrFormat +from zarr.abc.store import Store +from zarr.core.buffer import cpu +from zarr.core.common import ZARR_JSON, AccessModeLiteral, ZarrFormat from zarr.storage import FsspecStore, LocalStore, MemoryStore, StoreLike, StorePath, ZipStore -from zarr.storage._common import contains_array, contains_group, make_store_path +from zarr.storage._common import ( + _contains_node_v3, + contains_array, + contains_group, + make_store, + make_store_path, +) from zarr.storage._utils import ( _join_paths, _normalize_path_keys, @@ -19,13 +27,16 @@ normalize_path, ) +# contains_array and contains_group share this signature. +_ContainsFunc = Callable[[StorePath, ZarrFormat], Awaitable[bool]] + @pytest.fixture( params=["none", "temp_dir_str", "temp_dir_path", "store_path", "memory_store", "dict"] ) def store_like( request: pytest.FixtureRequest, -) -> Generator[None | str | Path | StorePath | MemoryStore | dict[Any, Any], None, None]: +) -> Generator[str | Path | StorePath | MemoryStore | dict[Any, Any] | None, None, None]: if request.param == "none": yield None elif request.param == "temp_dir_str": @@ -75,15 +86,86 @@ async def test_contains_array( @pytest.mark.parametrize("func", [contains_array, contains_group]) -async def test_contains_invalid_format_raises( - local_store: LocalStore, func: Callable[[Any], Any] -) -> None: +async def test_contains_invalid_format_raises(local_store: LocalStore, func: _ContainsFunc) -> None: """ Test contains_group and contains_array raise errors for invalid zarr_formats """ store_path = StorePath(local_store) - with pytest.raises(ValueError): - assert await func(store_path, zarr_format="3.0") # type: ignore[call-arg] + with pytest.raises(ValueError, match="Invalid zarr_format provided. Got 3.0, expected 2 or 3"): + assert await func(store_path, "3.0") # type: ignore[arg-type] + + +async def _write_zarr_json(store_path: StorePath, data: bytes) -> None: + """Write raw bytes to the v3 metadata key under `store_path`.""" + await (store_path / ZARR_JSON).set(cpu.Buffer.from_bytes(data)) + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_malformed_json_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document that is not valid JSON reads as 'not present'.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"{not valid json") + assert await func(store_path, 3) is False + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_non_object_json_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document that is valid JSON but not an object reads as 'not present'.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"[1, 2, 3]") + assert await func(store_path, 3) is False + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_missing_node_type_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document with no 'node_type' key reads as 'not present'.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b'{"zarr_format": 3}') + assert await func(store_path, 3) is False + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_non_utf8_bytes_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document that is not valid UTF-8 reads as 'not present' (not an error).""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"\x80\x81\x82\x83") + assert await func(store_path, 3) is False + + +async def test_contains_node_v3_malformed_json_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document is not valid JSON.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"{not valid json") + assert await _contains_node_v3(store_path) == "nothing" + + +async def test_contains_node_v3_non_object_json_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document is not a JSON object.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"[1, 2, 3]") + assert await _contains_node_v3(store_path) == "nothing" + + +async def test_contains_node_v3_missing_node_type_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document lacks a 'node_type' key.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b'{"zarr_format": 3}') + assert await _contains_node_v3(store_path) == "nothing" + + +async def test_contains_node_v3_non_utf8_bytes_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document is not valid UTF-8.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"\x80\x81\x82\x83") + assert await _contains_node_v3(store_path) == "nothing" @pytest.mark.parametrize("path", [None, "", "bar"]) @@ -100,7 +182,7 @@ async def test_make_store_path_none(path: str) -> None: @pytest.mark.parametrize("store_type", [str, Path]) @pytest.mark.parametrize("mode", ["r", "w"]) async def test_make_store_path_local( - tmpdir: LEGACY_PATH, + tmp_path: Path, store_type: type[str] | type[Path] | type[LocalStore], path: str, mode: AccessModeLiteral, @@ -108,10 +190,10 @@ async def test_make_store_path_local( """ Test the various ways of invoking make_store_path that create a LocalStore """ - store_like = store_type(str(tmpdir)) + store_like = store_type(str(tmp_path)) store_path = await make_store_path(store_like, path=path, mode=mode) assert isinstance(store_path.store, LocalStore) - assert Path(store_path.store.root) == Path(tmpdir) + assert Path(store_path.store.root) == Path(tmp_path) assert store_path.path == normalize_path(path) assert store_path.read_only == (mode == "r") @@ -145,18 +227,14 @@ async def test_store_path_invalid_mode_raises( Test that ValueErrors are raise for invalid mode. """ with pytest.raises(ValueError): - await StorePath.open( - LocalStore(str(tmp_path), read_only=modes[0]), - path="", - mode=modes[1], # type:ignore[arg-type] - ) + await StorePath.open(LocalStore(str(tmp_path), read_only=modes[0]), path="", mode=modes[1]) # type: ignore[arg-type] async def test_make_store_path_invalid() -> None: """ Test that invalid types raise TypeError """ - with pytest.raises(TypeError): + with pytest.raises(TypeError, match="Unsupported type for store_like: 'int'"): await make_store_path(1) @@ -173,6 +251,50 @@ async def test_make_store_path_storage_options_raises(store_like: StoreLike) -> await make_store_path(store_like, storage_options={"foo": "bar"}) +# universal-pathlib 0.2.x emits this from its own subclass registry when a local UPath is built. +@pytest.mark.filterwarnings( + "ignore:Detected a customized `__new__` method in subclass:DeprecationWarning" +) +@pytest.mark.parametrize( + ("url", "expected"), + [ + ("memory://bucket/foo.zarr", FsspecStore), + ("s3://bucket/foo.zarr", FsspecStore), + ("file://{tmp}/foo.zarr", LocalStore), + ("{tmp}/foo.zarr", LocalStore), + ], +) +async def test_make_store_upath(url: str, expected: type[Store], tmp_path: Path) -> None: + """ + A remote UPath becomes an FsspecStore, and a local one becomes a LocalStore, so that + UPath("/data") and Path("/data") agree. See https://github.com/zarr-developers/zarr-python/issues/4244. + """ + upath = pytest.importorskip("upath") + fsspec = pytest.importorskip("fsspec") + if url.startswith("s3://"): + pytest.importorskip("s3fs") + if url.startswith("memory://") and parse_version(fsspec.__version__) < parse_version( + "2024.12.0" + ): + # MemoryFileSystem is synchronous, so it can only be used once fsspec is new enough to + # supply AsyncFileSystemWrapper. + pytest.skip("No AsyncFileSystemWrapper") + store = await make_store(upath.UPath(url.format(tmp=tmp_path))) + assert isinstance(store, expected) + if isinstance(store, LocalStore): + # The local branch rebuilds the root from the UPath, so a mangled path would still + # produce a LocalStore. Pin the root down too, since "file://{tmp}" has no leading + # slash on Windows. + assert store.root == tmp_path / "foo.zarr" + + +async def test_make_store_upath_storage_options_raises() -> None: + """A UPath carries its own storage options, so a separate mapping is ambiguous.""" + upath = pytest.importorskip("upath") + with pytest.raises(TypeError, match="storage_options"): + await make_store(upath.UPath("memory://bucket/foo.zarr"), storage_options={"foo": "bar"}) + + async def test_unsupported() -> None: with pytest.raises(TypeError, match="Unsupported type for store_like: 'int'"): await make_store_path(1) @@ -195,7 +317,7 @@ def test_normalize_path_valid(path: str | bytes | Path) -> None: def test_normalize_path_upath() -> None: upath = pytest.importorskip("upath") - assert normalize_path(upath.UPath("foo/bar")) == "foo/bar" + assert normalize_path(upath.UPath("foo/bar", protocol="memory")) == "memory:/foo/bar" def test_normalize_path_none() -> None: @@ -204,7 +326,7 @@ def test_normalize_path_none() -> None: @pytest.mark.parametrize("path", [".", ".."]) def test_normalize_path_invalid(path: str) -> None: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="is invalid because its string representation contains"): normalize_path(path) @@ -277,7 +399,7 @@ def test_relativize_path_invalid() -> None: _relativize_path(path="a/b/c", prefix="b") -def test_different_open_mode(tmp_path: LEGACY_PATH) -> None: +def test_different_open_mode(tmp_path: Path) -> None: # Test with a store that implements .with_read_only() store = MemoryStore() zarr.create((100,), store=store, zarr_format=2, path="a") diff --git a/tests/test_store/test_fsspec.py b/tests/test_store/test_fsspec.py index 5e9e33f0e4..bb03970d5b 100644 --- a/tests/test_store/test_fsspec.py +++ b/tests/test_store/test_fsspec.py @@ -1,8 +1,8 @@ from __future__ import annotations import json -import os import re +import warnings from typing import TYPE_CHECKING, Any import numpy as np @@ -16,6 +16,7 @@ from zarr.core.sync import _collect_aiterator, sync from zarr.errors import ZarrUserWarning from zarr.storage import FsspecStore +from zarr.storage._common import make_store from zarr.storage._fsspec import _make_async from zarr.testing.store import StoreTests @@ -35,7 +36,9 @@ pytest.mark.filterwarnings( re.escape("ignore:datetime.datetime.utcnow() is deprecated:DeprecationWarning") ), - # TODO: fix these warnings + # FsspecStore.from_url() and from_mapper() now close the aiohttp session on store.close(). + # This filter covers stores that are GC'd without an explicit close() call, and any + # residual sessions from aiobotocore's ClientCreatorContext (a separate upstream issue). pytest.mark.filterwarnings("ignore:Unclosed client session:ResourceWarning"), pytest.mark.filterwarnings( "ignore:coroutine 'ClientCreatorContext.__aexit__' was never awaited:RuntimeWarning" @@ -49,41 +52,39 @@ fsspec = pytest.importorskip("fsspec") s3fs = pytest.importorskip("s3fs") requests = pytest.importorskip("requests") -moto_server = pytest.importorskip("moto.moto_server.threaded_moto_server") -moto = pytest.importorskip("moto") +# Skip this module entirely when moto is absent; the server itself comes from the shared +# `moto_server` fixture in tests/conftest.py. +pytest.importorskip("moto") botocore = pytest.importorskip("botocore") # ### amended from s3fs ### # test_bucket_name = "test" secure_bucket_name = "test-secure" -port = 5555 -endpoint_url = f"http://127.0.0.1:{port}/" -@pytest.fixture(scope="module") -def s3_base() -> Generator[None, None, None]: - # writable local S3 system +@pytest.fixture +def endpoint_url(moto_server: str) -> str: + """Endpoint of the shared session-scoped moto server (see tests/conftest.py). - # This fixture is module-scoped, meaning that we can reuse the MotoServer across all tests - server = moto_server.ThreadedMotoServer(ip_address="127.0.0.1", port=port) - server.start() - if "AWS_SECRET_ACCESS_KEY" not in os.environ: - os.environ["AWS_SECRET_ACCESS_KEY"] = "foo" - if "AWS_ACCESS_KEY_ID" not in os.environ: - os.environ["AWS_ACCESS_KEY_ID"] = "foo" + A fixture rather than a module-level constant because the server binds an ephemeral + port, so the endpoint is only known once the server is running.""" + return moto_server - yield - server.stop() - -def get_boto3_client() -> botocore.client.BaseClient: +def get_boto3_client(endpoint_url: str) -> botocore.client.BaseClient: # NB: we use the sync botocore client for setup session = botocore.session.Session() - return session.create_client("s3", endpoint_url=endpoint_url) + + # Prevent IllegalLocationConstraintException by explicitly setting region to + # "us-east-1", which does not require configuring LocationConstraint during + # bucket creation. (It is, in fact, forbidden for that region.) Necessary + # in the face of "ambient" AWS configuration in a development environment + # where the default region might be configured differently. + return session.create_client("s3", endpoint_url=endpoint_url, region_name="us-east-1") @pytest.fixture(autouse=True) -def s3(s3_base: None) -> Generator[s3fs.S3FileSystem, None, None]: +def s3(endpoint_url: str) -> Generator[s3fs.S3FileSystem, None, None]: """ Quoting Martin Durant: pytest-asyncio creates a new event loop for each async test. @@ -96,10 +97,17 @@ def s3(s3_base: None) -> Generator[s3fs.S3FileSystem, None, None]: https://github.com/zarr-developers/zarr-python/pull/1785#discussion_r1634856207 """ - client = get_boto3_client() + client = get_boto3_client(endpoint_url) client.create_bucket(Bucket=test_bucket_name, ACL="public-read") s3fs.S3FileSystem.clear_instance_cache() - s3 = s3fs.S3FileSystem(anon=False, client_kwargs={"endpoint_url": endpoint_url}) + s3 = s3fs.S3FileSystem( + anon=False, + client_kwargs={"endpoint_url": endpoint_url}, + # Prevent "AssertionError: Session was never entered" from aiobotocore + # at end of test execution. Using clear_instance_cache is insufficient, + # although still necessary. + skip_instance_cache=True, + ) session = sync(s3.set_session()) s3.invalidate_cache() yield s3 @@ -111,7 +119,7 @@ def s3(s3_base: None) -> Generator[s3fs.S3FileSystem, None, None]: # ### end from s3fs ### # -async def test_basic() -> None: +async def test_basic(endpoint_url: str) -> None: store = FsspecStore.from_url( f"s3://{test_bucket_name}/foo/spam/", storage_options={"endpoint_url": endpoint_url, "anon": False}, @@ -138,7 +146,7 @@ class TestFsspecStoreS3(StoreTests[FsspecStore, cpu.Buffer]): buffer_cls = cpu.Buffer @pytest.fixture - def store_kwargs(self) -> dict[str, str | bool]: + def store_kwargs(self, endpoint_url: str) -> dict[str, str | bool]: try: from fsspec import url_to_fs except ImportError: @@ -176,7 +184,7 @@ def test_store_supports_writes(self, store: FsspecStore) -> None: def test_store_supports_listing(self, store: FsspecStore) -> None: assert store.supports_listing - async def test_fsspec_store_from_uri(self, store: FsspecStore) -> None: + async def test_fsspec_store_from_uri(self, store: FsspecStore, endpoint_url: str) -> None: storage_options = { "endpoint_url": endpoint_url, "anon": False, @@ -229,7 +237,7 @@ async def test_fsspec_store_from_uri(self, store: FsspecStore) -> None: parse_version(fsspec.__version__) < parse_version("2024.03.01"), reason="Prior bug in from_upath", ) - def test_from_upath(self) -> None: + def test_from_upath(self, endpoint_url: str) -> None: upath = pytest.importorskip("upath") path = upath.UPath( f"s3://{test_bucket_name}/foo/bar/", @@ -242,7 +250,48 @@ def test_from_upath(self) -> None: assert result.fs.asynchronous assert result.path == f"{test_bucket_name}/foo/bar" - def test_init_warns_if_fs_asynchronous_is_false(self) -> None: + @pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.03.01"), + reason="Prior bug in from_upath", + ) + def test_from_upath_sync_filesystem(self, endpoint_url: str) -> None: + """ + A UPath built without ``asynchronous=True`` -- the common case -- yields an async-mode + filesystem that keeps the original storage options. + """ + upath = pytest.importorskip("upath") + path = upath.UPath( + f"s3://{test_bucket_name}/foo/bar/", + endpoint_url=endpoint_url, + anon=False, + ) + assert not path.fs.asynchronous + with warnings.catch_warnings(): + warnings.simplefilter("error", ZarrUserWarning) + result = FsspecStore.from_upath(path) + assert result.fs.asynchronous + assert result.fs.endpoint_url == endpoint_url + assert result.path == f"{test_bucket_name}/foo/bar" + + async def test_open_group_from_upath(self, endpoint_url: str) -> None: + """ + Passing a remote UPath to the top-level API works. + + Regression test for https://github.com/zarr-developers/zarr-python/issues/4244. + """ + upath = pytest.importorskip("upath") + path = upath.UPath( + f"s3://{test_bucket_name}/upath-group", + endpoint_url=endpoint_url, + anon=False, + ) + group = await zarr.api.asynchronous.open_group(path, mode="w", attributes={"key": "value"}) + assert isinstance(group.store_path.store, FsspecStore) + + reopened = await zarr.api.asynchronous.open_group(path, mode="r") + assert dict(reopened.attrs) == {"key": "value"} + + def test_init_warns_if_fs_asynchronous_is_false(self, endpoint_url: str) -> None: try: from fsspec import url_to_fs except ImportError: @@ -269,6 +318,20 @@ async def test_delete_dir_unsupported_deletes(self, store: FsspecStore) -> None: ): await store.delete_dir("test_prefix") + # ── Filesystem lifecycle ────────────────────────────────────────────────── + + async def test_close_marks_store_closed(self, endpoint_url: str) -> None: + """close() must succeed and mark the store not-open.""" + store = FsspecStore.from_url( + f"s3://{test_bucket_name}/lifecycle/", + storage_options={"endpoint_url": endpoint_url, "anon": False}, + ) + await store.set("probe", cpu.Buffer.from_bytes(b"x")) + + store.close() + + assert not store._is_open + def array_roundtrip(store: FsspecStore) -> None: """ @@ -286,6 +349,116 @@ def array_roundtrip(store: FsspecStore) -> None: np.testing.assert_array_equal(arr[:], data) +@pytest.mark.parametrize( + ("root", "key", "expected"), + [ + # `"/"` as root collapses so that bare-key backends (notably + # ReferenceFileSystem) get the right key. Regression test for + # https://github.com/zarr-developers/zarr-python/issues/3922 . + ("/", "zarr.json", "zarr.json"), + ("", "zarr.json", "zarr.json"), + # Trailing slashes on the root are stripped before joining. + ("foo/", "zarr.json", "foo/zarr.json"), + ("foo", "zarr.json", "foo/zarr.json"), + # Leading slashes on the root are preserved -- absolute filesystem + # paths must stay absolute. Regression test for the titiler-xarray + # breakage that #3924 introduced when `normalize_path` was applied to + # `FsspecStore.path`. + ("/home/runner/data.zarr", "zarr.json", "/home/runner/data.zarr/zarr.json"), + ("/home/runner/data.zarr/", "zarr.json", "/home/runner/data.zarr/zarr.json"), + # Multi-segment keys. + ("/home/foo", "a/b/zarr.json", "/home/foo/a/b/zarr.json"), + ("", "a/b/zarr.json", "a/b/zarr.json"), + # Trailing slash on the result is stripped (relevant when key is ""). + ("/home/foo", "", "/home/foo"), + ], +) +def test_dereference_path(root: str, key: str, expected: str) -> None: + """Verify the contract `_dereference_path` provides for `FsspecStore`. + + `FsspecStore.path` is stored verbatim; the join with a key must collapse a + sentinel `"/"` root, strip trailing slashes, and preserve leading + slashes on absolute paths. + """ + from zarr.storage._utils import _dereference_path + + assert _dereference_path(root, key) == expected + + +async def test_fsspec_store_open_group_via_reference_filesystem() -> None: + """End-to-end regression test for + https://github.com/zarr-developers/zarr-python/issues/3922 . + + ``ReferenceFileSystem`` keys its refs by bare strings like ``"zarr.json"``. + The bug was that ``FsspecStore(fs=ref_fs, path="/")`` produced + ``"//zarr.json"`` at the join site and failed to find the entry, raising + ``GroupNotFoundError``. This test pins ``path="/"`` explicitly to keep + coverage even if the default value changes later. + """ + import json + + from fsspec.implementations.reference import ReferenceFileSystem + + group_json = json.dumps({"zarr_format": 3, "node_type": "group", "attributes": {}}) + fs = ReferenceFileSystem( + fo={"version": 1, "refs": {"zarr.json": group_json}}, + asynchronous=True, + ) + store = FsspecStore(fs=fs, path="/", read_only=True) + group = await zarr.api.asynchronous.open_group(store, mode="r") + assert group.metadata.zarr_format == 3 + + +async def test_fsspec_store_read_array_chunk_via_reference_filesystem() -> None: + """End-to-end regression test that exercises the byte-range read path + against ``ReferenceFileSystem``. + + Beyond opening a group (covered by + ``test_fsspec_store_open_group_via_reference_filesystem``), this test + constructs a small zarr v3 array whose chunk lives in the refs dict and + reads it through the store. Path-handling bugs on the byte-range + fetch path (used by kerchunk-style virtualization) would surface here + rather than at metadata-open time. + """ + import json + + import numpy as np + from fsspec.implementations.reference import ReferenceFileSystem + + # Construct a minimal v3 zarr: a single 1-D uint8 array of length 4 with + # one chunk of size 4. The chunk bytes are little-endian uint8s 1..4. + array_meta = json.dumps( + { + "zarr_format": 3, + "node_type": "array", + "shape": [4], + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [4]}}, + "data_type": "uint8", + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": 0, + "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + "attributes": {}, + } + ) + chunk_bytes = bytes([1, 2, 3, 4]) + + refs: dict[str, str] = { + "zarr.json": array_meta, + # ReferenceFileSystem accepts raw bytes via base64 encoding or + # latin-1-decoded strings; latin-1 round-trips bytes 1:1. + "c/0": chunk_bytes.decode("latin-1"), + } + + fs = ReferenceFileSystem( + fo={"version": 1, "refs": refs}, + asynchronous=True, + ) + store = FsspecStore(fs=fs, path="/", read_only=True) + array = await zarr.api.asynchronous.open_array(store=store, mode="r") + data = await array.getitem(slice(None)) + np.testing.assert_array_equal(data, np.array([1, 2, 3, 4], dtype="uint8")) + + @pytest.mark.skipif( parse_version(fsspec.__version__) < parse_version("2024.12.0"), reason="No AsyncFileSystemWrapper", @@ -314,7 +487,7 @@ def test_wrap_sync_filesystem_raises(tmp_path: pathlib.Path) -> None: parse_version(fsspec.__version__) < parse_version("2024.12.0"), reason="No AsyncFileSystemWrapper", ) -def test_no_wrap_async_filesystem() -> None: +def test_no_wrap_async_filesystem(endpoint_url: str) -> None: """An async fs should not be wrapped automatically; fsspec's s3 filesystem is such an fs""" from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper @@ -364,7 +537,7 @@ def test_open_fsmap_file_raises(tmp_path: pathlib.Path) -> None: @pytest.mark.parametrize("asynchronous", [True, False]) -def test_open_fsmap_s3(asynchronous: bool) -> None: +def test_open_fsmap_s3(asynchronous: bool, endpoint_url: str) -> None: s3_filesystem = s3fs.S3FileSystem( asynchronous=asynchronous, endpoint_url=endpoint_url, anon=False ) @@ -372,7 +545,7 @@ def test_open_fsmap_s3(asynchronous: bool) -> None: array_roundtrip(mapper) -def test_open_s3map_raises() -> None: +def test_open_s3map_raises(endpoint_url: str) -> None: with pytest.raises(TypeError, match="Unsupported type for store_like:.*"): zarr.open(store=0, mode="w", shape=(3, 3)) s3_filesystem = s3fs.S3FileSystem(asynchronous=True, endpoint_url=endpoint_url, anon=False) @@ -388,8 +561,91 @@ def test_open_s3map_raises() -> None: zarr.open(store=mapper, storage_options={"anon": True}, mode="w", shape=(3, 3)) +async def test_close_does_not_close_filesystem_session() -> None: + """close() must not touch the filesystem's session. + + fsspec caches and shares filesystem instances across callers, so the + session is not the store's to close. HTTP is used because its aiohttp + session is observably closed for good; s3fs transparently reconnects, which + would hide a regression. No request is issued — set_session() only + constructs the session. + """ + pytest.importorskip("aiohttp") + store = FsspecStore.from_url("http://example.com/a") + session = await store.fs.set_session() + + store.close() + + assert not session.closed + + +async def test_close_does_not_break_a_sibling_store() -> None: + """Closing one store must not close a session another store is using. + + Two stores from different URLs on one host are handed the same cached + filesystem; a store that closed it on close() would take the sibling's + session down too. This is the regression guard for that bug. + """ + pytest.importorskip("aiohttp") + s1 = FsspecStore.from_url("http://example.com/a") + s2 = FsspecStore.from_url("http://example.com/b") + session = await s2.fs.set_session() + + s1.close() + + assert not session.closed + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_from_mapper_wraps_sync_filesystem(tmp_path: pathlib.Path) -> None: + """from_mapper() with a sync fs wraps it in an AsyncFileSystemWrapper.""" + import fsspec as _fsspec + from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper + + fs = _fsspec.filesystem("file", auto_mkdir=True) + mapper = fs.get_mapper(str(tmp_path)) + store = FsspecStore.from_mapper(mapper) + assert isinstance(store.fs, AsyncFileSystemWrapper) + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_with_read_only_shares_filesystem(tmp_path: pathlib.Path) -> None: + """with_read_only() returns a store sharing the source's filesystem.""" + source = FsspecStore.from_url(f"file://{tmp_path}", storage_options={"auto_mkdir": False}) + + derived = source.with_read_only(read_only=True) + + assert derived.fs is source.fs + assert derived.read_only + assert not source.read_only + + +def test_make_async_preserves_unserializable_storage_options() -> None: + """A sync instance of an async filesystem whose storage options hold objects that + cannot round-trip through JSON (e.g. an Azure credential) must still convert. + + See https://github.com/zarr-developers/zarr-python/issues/4220 + """ + pytest.importorskip("aiohttp") + credential = object() # stand-in for e.g. azure.identity.DefaultAzureCredential + sync_fs = fsspec.filesystem("http", client_kwargs={"auth": credential}) + assert sync_fs.async_impl + assert not sync_fs.asynchronous + + async_fs = _make_async(sync_fs) + + assert async_fs.asynchronous + assert async_fs.client_kwargs["auth"] is credential + + @pytest.mark.parametrize("asynchronous", [True, False]) -def test_make_async(asynchronous: bool) -> None: +def test_make_async(asynchronous: bool, endpoint_url: str) -> None: s3_filesystem = s3fs.S3FileSystem( asynchronous=asynchronous, endpoint_url=endpoint_url, anon=False ) @@ -434,3 +690,14 @@ async def test_with_read_only_auto_mkdir(tmp_path: Path) -> None: store_w = FsspecStore.from_url(f"file://{tmp_path}", storage_options={"auto_mkdir": False}) _ = store_w.with_read_only() + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +async def test_memory_scheme() -> None: + """Test that the "memory" scheme creates a `MemoryFileSystem`-backed store""" + store = await make_store("memory://test") + assert isinstance(store, FsspecStore) + assert store.fs.protocol == "memory" diff --git a/tests/test_store/test_fsspec_get_ranges.py b/tests/test_store/test_fsspec_get_ranges.py new file mode 100644 index 0000000000..61d834d22f --- /dev/null +++ b/tests/test_store/test_fsspec_get_ranges.py @@ -0,0 +1,124 @@ +# tests/test_store/test_fsspec_get_ranges.py +"""Lightweight integration tests for FsspecStore.get_ranges using MemoryFileSystem. + +These don't need moto/s3 — they exercise the new method against an in-process +fsspec MemoryFileSystem wrapped in the async wrapper. +""" + +from __future__ import annotations + +import pytest +from packaging.version import parse as parse_version + +from zarr.abc.store import RangeByteRequest +from zarr.core.buffer import Buffer, default_buffer_prototype +from zarr.storage import FsspecStore +from zarr.storage._fsspec import _make_async + +fsspec = pytest.importorskip("fsspec") + +# AsyncFileSystemWrapper (needed to wrap a sync MemoryFileSystem) landed in fsspec 2024.12.0. +# Older versions are pinned by the min-deps CI job, so skip the whole file there. +pytestmark = pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) + + +@pytest.fixture +def memory_store() -> FsspecStore: + """An FsspecStore backed by fsspec MemoryFileSystem (wrapped async).""" + from fsspec.implementations.memory import MemoryFileSystem + + # Each test gets a clean filesystem; MemoryFileSystem is a singleton per target_options, + # so clear state explicitly. + fs: MemoryFileSystem = MemoryFileSystem() + fs.store.clear() + fs.pseudo_dirs.clear() + async_fs = _make_async(fs) + return FsspecStore(fs=async_fs, path="/root") + + +async def _write(store: FsspecStore, key: str, data: bytes) -> None: + buf = default_buffer_prototype().buffer.from_bytes(data) + await store.set(key, buf) + + +async def test_get_ranges_happy_path(memory_store: FsspecStore) -> None: + blob = bytes(i % 256 for i in range(1024)) + await _write(memory_store, "blob", blob) + proto = default_buffer_prototype() + + ranges = [ + RangeByteRequest(0, 10), + RangeByteRequest(100, 110), + RangeByteRequest(500, 520), + ] + groups: list[list[tuple[int, Buffer | None]]] = [ + list(group) async for group in memory_store.get_ranges("blob", ranges, prototype=proto) + ] + + flat: dict[int, bytes] = {} + for group in groups: + for idx, buf in group: + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[100:110] + assert flat[2] == blob[500:520] + + +async def test_get_ranges_missing_key_raises(memory_store: FsspecStore) -> None: + """A request against a missing key raises BaseExceptionGroup containing FileNotFoundError.""" + proto = default_buffer_prototype() + agen = memory_store.get_ranges("does-not-exist", [RangeByteRequest(0, 10)], prototype=proto) + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + + +async def test_get_ranges_forwards_coalescing_kwargs(memory_store: FsspecStore) -> None: + """`max_gap_bytes=-1` forces no merging; we should see three groups for three ranges.""" + blob = bytes(i % 256 for i in range(1024)) + await _write(memory_store, "blob", blob) + proto = default_buffer_prototype() + + ranges = [ + RangeByteRequest(0, 10), + RangeByteRequest(11, 20), # adjacent: would merge under defaults + RangeByteRequest(21, 30), + ] + groups: list[list[tuple[int, Buffer | None]]] = [ + list(group) + async for group in memory_store.get_ranges( + "blob", ranges, prototype=proto, max_gap_bytes=-1 + ) + ] + # With merging disabled, every range becomes its own one-tuple group. + assert sorted(len(g) for g in groups) == [1, 1, 1] + + +async def test_get_ranges_mixed_range_types(memory_store: FsspecStore) -> None: + """Covers RangeByteRequest, OffsetByteRequest, SuffixByteRequest, and None in one call.""" + from zarr.abc.store import ByteRequest, OffsetByteRequest, SuffixByteRequest + + blob = bytes(i % 256 for i in range(512)) + await _write(memory_store, "mixed", blob) + proto = default_buffer_prototype() + + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + OffsetByteRequest(500), + SuffixByteRequest(12), + None, + ] + flat: dict[int, bytes] = {} + async for group in memory_store.get_ranges("mixed", ranges, prototype=proto): + for idx, buf in group: + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[500:] + assert flat[2] == blob[-12:] + assert flat[3] == blob diff --git a/tests/test_store/test_get_ranges.py b/tests/test_store/test_get_ranges.py new file mode 100644 index 0000000000..522d6565aa --- /dev/null +++ b/tests/test_store/test_get_ranges.py @@ -0,0 +1,183 @@ +# tests/test_store/test_get_ranges.py +"""Tests for `Store.get_ranges` — the ABC default implementation and wrapper delegation. + +`Store.get_ranges` is defined on the ABC with a default implementation built +on `coalesced_get(self.get, ...)`, so every store inherits a working version. +These tests cover that inherited path and the explicit delegation in +`WrapperStore` (which ensures wrapped stores' optimized overrides are honored). +Store-specific overrides (e.g. `FsspecStore`) have their own test modules. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from zarr.abc.store import RangeByteRequest +from zarr.core.buffer import default_buffer_prototype +from zarr.storage import MemoryStore, ZipStore +from zarr.storage._wrapper import WrapperStore + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Sequence + from pathlib import Path + + from zarr.abc.store import ByteRequest + from zarr.core.buffer import Buffer, BufferPrototype + + +async def _write(store: MemoryStore, key: str, data: bytes) -> None: + buf = default_buffer_prototype().buffer.from_bytes(data) + await store.set(key, buf) + + +async def test_memory_store_inherits_get_ranges_from_abc() -> None: + """MemoryStore doesn't override `get_ranges`; the ABC default must work end-to-end.""" + store = MemoryStore() + blob = bytes(i % 256 for i in range(512)) + await _write(store, "blob", blob) + + ranges = [RangeByteRequest(0, 10), RangeByteRequest(100, 110)] + proto = default_buffer_prototype() + flat: dict[int, bytes] = {} + async for group in store.get_ranges("blob", ranges, prototype=proto): + for idx, buf in group: + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[100:110] + + +async def test_memory_store_get_ranges_missing_key_raises() -> None: + """A missing key on a default-impl store raises BaseExceptionGroup containing FileNotFoundError.""" + store = MemoryStore() + proto = default_buffer_prototype() + agen = store.get_ranges("does-not-exist", [RangeByteRequest(0, 10)], prototype=proto) + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + + +def test_get_ranges_sync_reads_multiple_ranges() -> None: + """The synchronous `get_ranges_sync` on a sync-capable store returns each + requested range, mirroring the async `get_ranges` happy path.""" + import asyncio + + store = MemoryStore() + blob = bytes(i % 256 for i in range(512)) + asyncio.run(_write(store, "blob", blob)) + + ranges = [RangeByteRequest(0, 10), RangeByteRequest(100, 110)] + proto = default_buffer_prototype() + flat: dict[int, bytes] = {} + for idx, buf in store.get_ranges_sync("blob", ranges, prototype=proto): + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[100:110] + + +def test_get_ranges_sync_missing_key_raises() -> None: + """A missing key makes `get_ranges_sync` raise a BaseExceptionGroup + containing FileNotFoundError — the same contract as async `get_ranges`, so + callers handle a deleted shard uniformly across sync and async paths.""" + store = MemoryStore() + proto = default_buffer_prototype() + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + store.get_ranges_sync("does-not-exist", [RangeByteRequest(0, 10)], prototype=proto) + + +def test_get_ranges_sync_on_non_sync_store_raises_type_error(tmp_path: Path) -> None: + """`get_ranges_sync` requires the store to support synchronous reads + (`SupportsGetSync`); a non-sync store raises TypeError rather than silently + falling back.""" + store = ZipStore(tmp_path / "store.zip", mode="w") + proto = default_buffer_prototype() + with pytest.raises(TypeError, match="does not support synchronous reads"): + store.get_ranges_sync("k", [RangeByteRequest(0, 10)], prototype=proto) + + +async def test_wrapper_store_delegates_get_ranges() -> None: + """WrapperStore.get_ranges must delegate to the wrapped store, not fall back to the default.""" + + class CountingMemoryStore(MemoryStore): + """Tallies get_ranges invocations so we can assert delegation.""" + + get_ranges_calls: int = 0 + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int = 10, + max_gap_bytes: int = 1 << 20, + max_coalesced_bytes: int = 16 << 20, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + type(self).get_ranges_calls += 1 + async for group in super().get_ranges( + key, + byte_ranges, + prototype=prototype, + max_concurrency=max_concurrency, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + yield group + + inner = CountingMemoryStore() + blob = b"x" * 100 + await _write(inner, "k", blob) + wrapped = WrapperStore(inner) + + proto = default_buffer_prototype() + groups: list[list[tuple[int, Buffer | None]]] = [ + list(group) + async for group in wrapped.get_ranges("k", [RangeByteRequest(0, 5)], prototype=proto) + ] + + assert CountingMemoryStore.get_ranges_calls == 1 + assert len(groups) == 1 + assert groups[0][0][0] == 0 + + +async def test_wrapper_store_forwards_coalescing_kwargs() -> None: + """Coalescing kwargs flow through WrapperStore to the wrapped store's get_ranges.""" + + class SpyMemoryStore(MemoryStore): + last_max_gap_bytes: int | None = None + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int = 10, + max_gap_bytes: int = 1 << 20, + max_coalesced_bytes: int = 16 << 20, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + type(self).last_max_gap_bytes = max_gap_bytes + async for group in super().get_ranges( + key, + byte_ranges, + prototype=prototype, + max_concurrency=max_concurrency, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + yield group + + inner = SpyMemoryStore() + await _write(inner, "k", b"y" * 100) + wrapped = WrapperStore(inner) + proto = default_buffer_prototype() + async for _ in wrapped.get_ranges( + "k", [RangeByteRequest(0, 5)], prototype=proto, max_gap_bytes=-1 + ): + pass + + assert SpyMemoryStore.last_max_gap_bytes == -1 diff --git a/tests/test_store/test_latency.py b/tests/test_store/test_latency.py index 38ffb17dd6..9cb71fd6a0 100644 --- a/tests/test_store/test_latency.py +++ b/tests/test_store/test_latency.py @@ -1,8 +1,16 @@ from __future__ import annotations +import time +from unittest.mock import patch + +import numpy as np import pytest +import zarr +from zarr.abc.store import RangeByteRequest from zarr.core.buffer import default_buffer_prototype +from zarr.core.codec_pipeline import FusedCodecPipeline +from zarr.core.config import config as zarr_config from zarr.storage import MemoryStore from zarr.testing.store import LatencyStore @@ -55,3 +63,103 @@ async def test_latency_store_with_read_only_round_trip() -> None: # The original read-only wrapper remains read-only assert latency_ro.read_only + + +@pytest.mark.parametrize( + ("get_latency", "set_latency"), + [ + (0.01, 0.02), + ((0.1, 0.05), (0.2, 0.01)), + ], + ids=["scalar", "distribution"], +) +def test_with_store_preserves_latency_config( + get_latency: float | tuple[float, float], set_latency: float | tuple[float, float] +) -> None: + """Derived stores (e.g. via `with_read_only`) keep the raw latency config — + a `(loc, scale)` distribution must not collapse to one sampled float.""" + store = LatencyStore(MemoryStore(), get_latency=get_latency, set_latency=set_latency) + derived = store.with_read_only(True) + assert derived._get_latency == store._get_latency + assert derived._set_latency == store._set_latency + + +def test_sync_methods_inject_latency(monkeypatch: pytest.MonkeyPatch) -> None: + """`get_sync`/`set_sync` sleep the configured latency on the calling thread + before delegating to the wrapped store.""" + sleeps: list[float] = [] + monkeypatch.setattr(time, "sleep", sleeps.append) + + store = LatencyStore(MemoryStore(), get_latency=0.123, set_latency=0.456) + buf = default_buffer_prototype().buffer.from_bytes(b"abcd") + store.set_sync("key", buf) + assert sleeps == [pytest.approx(0.456)] + out = store.get_sync("key", prototype=default_buffer_prototype()) + assert out is not None + assert out.to_bytes() == b"abcd" + assert sleeps == [pytest.approx(0.456), pytest.approx(0.123)] + + +async def test_get_ranges_pays_latency_per_fetch() -> None: + """`get_ranges` routes through the coalescing default built on `self.get`, + so each merged fetch pays the configured latency instead of bypassing it + via WrapperStore delegation. Two ranges further apart than `max_gap_bytes` + cannot coalesce -> exactly two `get` calls.""" + proto = default_buffer_prototype() + inner = MemoryStore() + await inner.set("blob", proto.buffer.from_bytes(bytes(4 << 20))) + store = LatencyStore(inner, get_latency=0.0) + + requests = [RangeByteRequest(0, 10), RangeByteRequest(2 << 20, (2 << 20) + 10)] + results: list[tuple[int, object]] = [] + with patch.object(store, "get", wraps=store.get) as get_spy: + async for group in store.get_ranges("blob", requests, prototype=proto): + results.extend(group) + assert get_spy.await_count == 2 + assert sorted(idx for idx, _ in results) == [0, 1] + for _, buf in results: + assert buf is not None + assert len(buf) == 10 # type: ignore[arg-type] + + +async def test_get_partial_values_routes_through_get() -> None: + """`get_partial_values` issues one `self.get` per key-range so each fetch + pays the configured latency instead of bypassing it via WrapperStore + delegation.""" + proto = default_buffer_prototype() + inner = MemoryStore() + await inner.set("blob", proto.buffer.from_bytes(b"0123456789")) + store = LatencyStore(inner, get_latency=0.0) + + with patch.object(store, "get", wraps=store.get) as get_spy: + results = await store.get_partial_values( + proto, [("blob", RangeByteRequest(0, 4)), ("blob", None)] + ) + assert get_spy.await_count == 2 + assert results[0] is not None + assert results[0].to_bytes() == b"0123" + assert results[1] is not None + assert results[1].to_bytes() == b"0123456789" + + +def test_latency_store_engages_fused_sync_path() -> None: + """A LatencyStore wrapping a sync-capable store must take the fused sync + fast path: reads go through the inner store's `get_sync`, not the async + fallback.""" + inner = MemoryStore() + store = LatencyStore(inner, get_latency=0.0, set_latency=0.0) + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + store=store, + shape=(8,), + chunks=(4,), + dtype="uint8", + compressors=None, + fill_value=0, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + data = np.arange(8, dtype="uint8") + arr[:] = data + with patch.object(inner, "get_sync", wraps=inner.get_sync) as get_sync_spy: + np.testing.assert_array_equal(arr[:], data) + assert get_sync_spy.call_count == 2 # one per chunk diff --git a/tests/test_store/test_local.py b/tests/test_store/test_local.py index bdc9b48121..90d214ee2c 100644 --- a/tests/test_store/test_local.py +++ b/tests/test_store/test_local.py @@ -1,9 +1,7 @@ from __future__ import annotations -import json import pathlib import re -from typing import TYPE_CHECKING import numpy as np import pytest @@ -11,15 +9,11 @@ import zarr from zarr import create_array from zarr.core.buffer import Buffer, cpu -from zarr.core.sync import sync from zarr.storage import LocalStore from zarr.storage._local import _atomic_write from zarr.testing.store import StoreTests from zarr.testing.utils import assert_bytes_equal -if TYPE_CHECKING: - from zarr.core.buffer import BufferPrototype - class TestLocalStore(StoreTests[LocalStore, cpu.Buffer]): store_cls = LocalStore @@ -35,8 +29,8 @@ async def set(self, store: LocalStore, key: str, value: Buffer) -> None: (store.root / key).write_bytes(value.to_bytes()) @pytest.fixture - def store_kwargs(self, tmpdir: str) -> dict[str, str]: - return {"root": str(tmpdir)} + def store_kwargs(self, tmp_path: pathlib.Path) -> dict[str, str]: + return {"root": str(tmp_path)} def test_store_repr(self, store: LocalStore) -> None: assert str(store) == f"file://{store.root.as_posix()}" @@ -52,6 +46,20 @@ async def test_empty_with_empty_subdir(self, store: LocalStore) -> None: (store.root / "foo/bar").mkdir(parents=True) assert await store.is_empty("") + def test_delete_sync_directory(self, store: LocalStore) -> None: + """`delete_sync` on a key that is a directory must remove the whole tree. + + Mirrors the async `delete_dir` behavior: deleting `"foo"` where + `"foo"` is a directory containing further nested paths should remove + everything under it, not just fail or delete a single file. + """ + (store.root / "foo" / "bar").mkdir(parents=True) + (store.root / "foo" / "bar" / "baz").write_bytes(b"data") + + store.delete_sync("foo") + + assert not (store.root / "foo").exists() + def test_creates_new_directory(self, tmp_path: pathlib.Path) -> None: target = tmp_path.joinpath("a", "b", "c") assert not target.exists() @@ -114,54 +122,6 @@ async def test_move( ): await store2.move(destination) - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - async def test_get_bytes_with_prototype_none( - self, store: LocalStore, buffer_cls: None | BufferPrototype - ) -> None: - """Test that get_bytes works with prototype=None.""" - data = b"hello world" - key = "test_key" - await self.set(store, key, self.buffer_cls.from_bytes(data)) - - result = await store._get_bytes(key, prototype=buffer_cls) - assert result == data - - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - def test_get_bytes_sync_with_prototype_none( - self, store: LocalStore, buffer_cls: None | BufferPrototype - ) -> None: - """Test that get_bytes_sync works with prototype=None.""" - data = b"hello world" - key = "test_key" - sync(self.set(store, key, self.buffer_cls.from_bytes(data))) - - result = store._get_bytes_sync(key, prototype=buffer_cls) - assert result == data - - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - async def test_get_json_with_prototype_none( - self, store: LocalStore, buffer_cls: None | BufferPrototype - ) -> None: - """Test that get_json works with prototype=None.""" - data = {"foo": "bar", "number": 42} - key = "test.json" - await self.set(store, key, self.buffer_cls.from_bytes(json.dumps(data).encode())) - - result = await store._get_json(key, prototype=buffer_cls) - assert result == data - - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - def test_get_json_sync_with_prototype_none( - self, store: LocalStore, buffer_cls: None | BufferPrototype - ) -> None: - """Test that get_json_sync works with prototype=None.""" - data = {"foo": "bar", "number": 42} - key = "test.json" - sync(self.set(store, key, self.buffer_cls.from_bytes(json.dumps(data).encode()))) - - result = store._get_json_sync(key, prototype=buffer_cls) - assert result == data - @pytest.mark.parametrize("exclusive", [True, False]) def test_atomic_write_successful(tmp_path: pathlib.Path, exclusive: bool) -> None: diff --git a/tests/test_store/test_memory.py b/tests/test_store/test_memory.py index 03c8b24271..013dae7044 100644 --- a/tests/test_store/test_memory.py +++ b/tests/test_store/test_memory.py @@ -1,6 +1,5 @@ from __future__ import annotations -import json import re from typing import TYPE_CHECKING, Any @@ -9,15 +8,14 @@ import pytest import zarr -from zarr.core.buffer import Buffer, cpu, gpu -from zarr.core.sync import sync +from zarr.core.buffer import Buffer, cpu, default_buffer_prototype, gpu from zarr.errors import ZarrUserWarning -from zarr.storage import GpuMemoryStore, MemoryStore +from zarr.storage import GpuMemoryStore, ManagedMemoryStore, MemoryStore +from zarr.storage._utils import _join_paths from zarr.testing.store import StoreTests from zarr.testing.utils import gpu_test if TYPE_CHECKING: - from zarr.core.buffer import BufferPrototype from zarr.core.common import ZarrFormat @@ -79,53 +77,54 @@ async def test_deterministic_size( np.testing.assert_array_equal(a[:3], 1) np.testing.assert_array_equal(a[3:], 0) - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - async def test_get_bytes_with_prototype_none( - self, store: MemoryStore, buffer_cls: None | BufferPrototype - ) -> None: - """Test that get_bytes works with prototype=None.""" - data = b"hello world" - key = "test_key" - await self.set(store, key, self.buffer_cls.from_bytes(data)) - - result = await store._get_bytes(key, prototype=buffer_cls) - assert result == data - - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - def test_get_bytes_sync_with_prototype_none( - self, store: MemoryStore, buffer_cls: None | BufferPrototype - ) -> None: - """Test that get_bytes_sync works with prototype=None.""" - data = b"hello world" - key = "test_key" - sync(self.set(store, key, self.buffer_cls.from_bytes(data))) + @pytest.mark.parametrize("method", ["set", "set_sync", "set_if_not_exists"]) + async def test_set_does_not_retain_caller_buffer(self, store: MemoryStore, method: str) -> None: + """Writing a buffer must not alias the caller's memory. - result = store._get_bytes_sync(key, prototype=buffer_cls) - assert result == data + MemoryStore keeps whatever it is handed alive in a dict, so retaining + the caller's buffer lets a later mutation of that buffer rewrite data + already committed to the store. + """ + source = np.frombuffer(bytearray(b"\x01\x02\x03\x04"), dtype="B") + value = cpu.Buffer.from_array_like(source) - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - async def test_get_json_with_prototype_none( - self, store: MemoryStore, buffer_cls: None | BufferPrototype + if method == "set_sync": + store.set_sync("k", value) + else: + await getattr(store, method)("k", value) + + source[:] = 0xF # mutate the caller's memory after the write + stored = await store.get("k", prototype=default_buffer_prototype()) + assert stored is not None + assert stored.to_bytes() == b"\x01\x02\x03\x04" + + @pytest.mark.parametrize( + "pipeline", + [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", + ], + ) + @pytest.mark.parametrize(("shape", "chunks"), [((30,), (10,)), ((8,), (4,)), ((4,), (4,))]) + def test_write_does_not_alias_source_array( + self, pipeline: str, shape: tuple[int], chunks: tuple[int] ) -> None: - """Test that get_json works with prototype=None.""" - data = {"foo": "bar", "number": 42} - key = "test.json" - await self.set(store, key, self.buffer_cls.from_bytes(json.dumps(data).encode())) - - result = await store._get_json(key, prototype=buffer_cls) - assert result == data + """Mutating the source array after a write must not corrupt stored chunks. - @pytest.mark.parametrize("buffer_cls", [None, cpu.buffer_prototype]) - def test_get_json_sync_with_prototype_none( - self, store: MemoryStore, buffer_cls: None | BufferPrototype - ) -> None: - """Test that get_json_sync works with prototype=None.""" - data = {"foo": "bar", "number": 42} - key = "test.json" - sync(self.set(store, key, self.buffer_cls.from_bytes(json.dumps(data).encode()))) + Without compression the encoded buffer is a zero-copy view of the + caller's array all the way down to the store, so this covers both the + single-chunk and multi-chunk write paths. + """ + with zarr.config.set({"codec_pipeline.path": pipeline}): + array = zarr.create_array( + store=MemoryStore(), shape=shape, chunks=chunks, dtype="i4", compressors=None + ) + source = np.arange(shape[0], dtype="i4") + expected = source.copy() + array[:] = source + source[:] = -1 - result = store._get_json_sync(key, prototype=buffer_cls) - assert result == data + np.testing.assert_array_equal(array[:], expected) # TODO: fix this warning @@ -181,3 +180,348 @@ def test_from_dict(self) -> None: result = GpuMemoryStore.from_dict(d) for v in result._store_dict.values(): assert type(v) is gpu.Buffer + + def test_set_sync_converts_to_gpu_buffer(self, store: GpuMemoryStore) -> None: + """`set_sync` must convert its value to a `gpu.Buffer`, mirroring `set`. + + `GpuMemoryStore`'s invariant is that every stored value is a + `gpu.Buffer`. Without this override, the inherited `MemoryStore.set_sync` + would store the CPU buffer it was given as-is, breaking that invariant + for whichever code path (e.g. the fused pipeline) uses the sync API. + """ + cpu_value = cpu.Buffer.from_bytes(b"aaaa") + msg = "Creating a zarr.buffer.gpu.Buffer with an array that does not support the __cuda_array_interface__ for zero-copy transfers, falling back to slow copy based path" + with pytest.warns(ZarrUserWarning, match=msg): + store.set_sync("k", cpu_value) + assert type(store._store_dict["k"]) is gpu.Buffer + + +class TestManagedMemoryStore(StoreTests[ManagedMemoryStore, cpu.Buffer]): + store_cls = ManagedMemoryStore + buffer_cls = cpu.Buffer + + async def set(self, store: ManagedMemoryStore, key: str, value: Buffer) -> None: + store._store_dict[_join_paths([store.path, key])] = value + + async def get(self, store: ManagedMemoryStore, key: str) -> Buffer: + return store._store_dict[_join_paths([store.path, key])] + + @pytest.fixture + def store_kwargs(self, request: pytest.FixtureRequest) -> dict[str, Any]: + # Use a unique name per test to avoid sharing state between tests + # but ensure the name is deterministic for equality tests + # Replace '/' with '-' since store names cannot contain '/' + # A non-empty path exercises prefix handling; a store with an + # unprefixed key in its backing dict would pass these tests + # vacuously with path="". + sanitized_name = request.node.name.replace("/", "-") + return {"name": f"test-{sanitized_name}", "path": "prefix"} + + @pytest.fixture + async def store(self, store_kwargs: dict[str, Any]) -> ManagedMemoryStore: + return self.store_cls(**store_kwargs) + + def test_store_repr(self, store: ManagedMemoryStore) -> None: + assert str(store) == _join_paths([f"memory://{store.name}", store.path]) + + async def test_serializable_store(self, store: ManagedMemoryStore) -> None: + """ + Test pickling semantics for ManagedMemoryStore. + + When pickled and unpickled within the same process (where the original + store still exists in the registry), the unpickled store reconnects to + the same backing dict. + """ + import pickle + + # Add some data to the store + await store.set("test-key", self.buffer_cls.from_bytes(b"test-value")) + + # Pickle and unpickle the store + pickled = pickle.dumps(store) + store2 = pickle.loads(pickled) + + # The unpickled store should reconnect to the same backing dict + assert store2._store_dict is store._store_dict + assert store2.name == store.name + assert store2.path == store.path + assert store2.read_only == store.read_only + + # The data should be accessible + result = await store2.get("test-key") + assert result is not None + assert result.to_bytes() == b"test-value" + + async def test_pickle_with_path(self) -> None: + """Test that path is preserved through pickle round-trip.""" + import pickle + + store = ManagedMemoryStore(name="pickle-path-test", path="some/path") + await store.set("key", self.buffer_cls.from_bytes(b"value")) + + pickled = pickle.dumps(store) + store2 = pickle.loads(pickled) + + assert store2.path == "some/path" + assert store2._store_dict is store._store_dict + + # Check that operations use the path correctly + result = await store2.get("key") + assert result is not None + assert result.to_bytes() == b"value" + + def test_pickle_after_gc(self) -> None: + """ + Test that unpickling after the original store is garbage collected + creates a new empty store with the same name (in the same process). + """ + import gc + import pickle + + # Create a store with a unique name and pickle it + store = ManagedMemoryStore(name="gc-pickle-test") + store._store_dict["key"] = self.buffer_cls.from_bytes(b"value") + pickled = pickle.dumps(store) + + # Delete the store and garbage collect + del store + gc.collect() + + # Unpickling should create a new store with an empty dict + store2 = pickle.loads(pickled) + assert store2.name == "gc-pickle-test" + # The dict is empty because the original was garbage collected + assert len(store2._store_dict) == 0 + + async def test_cross_process_detection(self) -> None: + """ + Test that unpickling a ManagedMemoryStore in a different process raises an error. + + This prevents silent data loss when a store is pickled and unpickled + in a different process (e.g., with multiprocessing). + """ + import os + + store = ManagedMemoryStore(name="cross-process-test") + await store.set("key", self.buffer_cls.from_bytes(b"value")) + + # Get the reduce tuple and modify the state to simulate a different process + cls, args, state = store.__reduce__() + state["created_pid"] = os.getpid() + 1 # Fake a different process ID + + # Manually reconstruct what pickle.loads would do + # This simulates unpickling data that was pickled in a different process + reconstructed = cls(*args) + with pytest.raises(RuntimeError, match="was created in process"): + reconstructed.__setstate__(state) + + def test_store_supports_writes(self, store: ManagedMemoryStore) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: ManagedMemoryStore) -> None: + assert store.supports_listing + + @pytest.mark.parametrize("dtype", ["uint8", "float32", "int64"]) + @pytest.mark.parametrize("zarr_format", [2, 3]) + async def test_deterministic_size( + self, store: MemoryStore, dtype: npt.DTypeLike, zarr_format: ZarrFormat + ) -> None: + a = zarr.empty( + store=store, + shape=(3,), + chunks=(1000,), + dtype=dtype, + zarr_format=zarr_format, + overwrite=True, + ) + a[...] = 1 + a.resize((1000,)) + + np.testing.assert_array_equal(a[:3], 1) + np.testing.assert_array_equal(a[3:], 0) + + def test_from_url(self, store: ManagedMemoryStore) -> None: + """Test that from_url creates a store sharing the same dict.""" + url = str(store) + store2 = ManagedMemoryStore.from_url(url) + assert store2._store_dict is store._store_dict + + def test_from_url_with_path(self, store: ManagedMemoryStore) -> None: + """Test that from_url extracts path component from URL.""" + # Reconnect to the fixture's dict via its name, but with an empty + # path, so appending "/some/path" below yields exactly that path. + base = ManagedMemoryStore(name=store.name) + url = f"{base}/some/path" + store2 = ManagedMemoryStore.from_url(url) + assert store2._store_dict is store._store_dict + assert store2.path == "some/path" + assert str(store2) == url + + def test_from_url_invalid(self) -> None: + """Test that from_url raises ValueError for non-existent store.""" + with pytest.raises(ValueError, match="Memory store not found"): + ManagedMemoryStore.from_url("memory://nonexistent-store") + + def test_from_url_not_memory_scheme(self) -> None: + """Test that from_url raises ValueError for non-memory URLs.""" + with pytest.raises(ValueError, match="Expected a 'memory://' URL"): + ManagedMemoryStore.from_url("file:///tmp/test") + + def test_named_store(self) -> None: + """Test that stores can be created with explicit names.""" + store = ManagedMemoryStore(name="my-test-store") + assert store.name == "my-test-store" + assert str(store) == "memory://my-test-store" + + def test_named_store_shares_dict(self) -> None: + """Test that creating a store with the same name shares the dict.""" + store1 = ManagedMemoryStore(name="shared-store") + store2 = ManagedMemoryStore(name="shared-store") + assert store1._store_dict is store2._store_dict + assert store1.name == store2.name + + def test_auto_generated_name(self) -> None: + """Test that stores get auto-generated names when none provided.""" + store = ManagedMemoryStore() + assert store.name is not None + assert str(store) == f"memory://{store.name}" + + def test_with_read_only_shares_dict(self, store: ManagedMemoryStore) -> None: + """Test that with_read_only creates a store sharing the same dict.""" + store2 = store.with_read_only(True) + assert store2._store_dict is store._store_dict + assert store2.read_only is True + assert store.read_only is False + + def test_with_read_only_preserves_path(self) -> None: + """Test that with_read_only preserves the path.""" + store = ManagedMemoryStore(name="path-test", path="some/path") + store2 = store.with_read_only(True) + assert store2.path == "some/path" + assert store2._store_dict is store._store_dict + + async def test_path_prefix_operations(self) -> None: + """Test that store operations use the path prefix correctly.""" + store = ManagedMemoryStore(name="prefix-test") + store_with_path = ManagedMemoryStore.from_url("memory://prefix-test/subdir") + + # Write via store_with_path + await store_with_path.set("key", self.buffer_cls.from_bytes(b"value")) + + # The key should be stored with the prefix in the underlying dict + assert "subdir/key" in store._store_dict + assert "key" not in store._store_dict + + # Read via store_with_path should work + result = await store_with_path.get("key") + assert result is not None + assert result.to_bytes() == b"value" + + # Read via store without path should use full key + result2 = await store.get("subdir/key") + assert result2 is not None + assert result2.to_bytes() == b"value" + + async def test_path_list_operations(self) -> None: + """Test that list operations filter by path prefix.""" + store = ManagedMemoryStore(name="list-test") + + # Set up some keys at different paths + await store.set("a/key1", self.buffer_cls.from_bytes(b"v1")) + await store.set("a/key2", self.buffer_cls.from_bytes(b"v2")) + await store.set("b/key3", self.buffer_cls.from_bytes(b"v3")) + + # Create a store with path "a" + store_a = ManagedMemoryStore.from_url("memory://list-test/a") + + # list() should only return keys under "a", without the "a/" prefix + keys = [k async for k in store_a.list()] + assert sorted(keys) == ["key1", "key2"] + + async def test_path_exists(self) -> None: + """Test that exists() uses the path prefix.""" + store = ManagedMemoryStore(name="exists-test") + await store.set("prefix/key", self.buffer_cls.from_bytes(b"value")) + + store_with_path = ManagedMemoryStore.from_url("memory://exists-test/prefix") + assert await store_with_path.exists("key") + assert not await store_with_path.exists("prefix/key") + + def test_path_normalization(self) -> None: + """Test that paths are normalized.""" + store1 = ManagedMemoryStore(name="norm-test", path="a/b/") + store2 = ManagedMemoryStore(name="norm-test", path="/a/b") + store3 = ManagedMemoryStore(name="norm-test", path="a//b") + assert store1.path == "a/b" + assert store2.path == "a/b" + assert store3.path == "a/b" + + def test_name_cannot_contain_slash(self) -> None: + """Test that store names cannot contain '/'.""" + with pytest.raises(ValueError, match="cannot contain '/'"): + ManagedMemoryStore(name="foo/bar") + + def test_garbage_collection(self) -> None: + """Test that the dict is garbage collected when no stores reference it.""" + import gc + + store = ManagedMemoryStore() + url = str(store) + + # URL should resolve while store exists + store2 = ManagedMemoryStore.from_url(url) + assert store2._store_dict is store._store_dict + + # Delete both stores + del store + del store2 + gc.collect() + + # URL should no longer resolve + with pytest.raises(ValueError, match="garbage collected"): + ManagedMemoryStore.from_url(url) + + def test_sync_methods_respect_path_prefix(self) -> None: + """`get_sync`/`set_sync`/`delete_sync` must prefix keys with `self.path`, + exactly like the async `get`/`set`/`delete` methods. + + `ManagedMemoryStore` used to inherit these from `MemoryStore`, which + writes/reads the raw key. Two stores sharing a dict with different + `path` values would then cross-talk through the sync API. + """ + store = ManagedMemoryStore(name="sync-prefix-test", path="subdir") + data_buf = self.buffer_cls.from_bytes(b"value") + + store.set_sync("key", data_buf) + assert "subdir/key" in store._store_dict + assert "key" not in store._store_dict + + result = store.get_sync("key") + assert result is not None + assert result.to_bytes() == b"value" + + store.delete_sync("key") + assert "subdir/key" not in store._store_dict + + def test_fused_pipeline_respects_path_prefix(self) -> None: + """End-to-end regression: the fused pipeline's sync store fast path must + write chunks under the store's path prefix. + + `FusedCodecPipeline` uses `set_sync`/`get_sync` when a store implements + the sync protocols. If those methods skip the prefix that the async + methods apply, chunk data lands outside `self.path` and a fresh handle + re-reading through the prefix silently sees fill values instead. + """ + with zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} + ): + store = ManagedMemoryStore(name="fused-prefix-test", path="subdir") + arr = zarr.create_array(store, shape=(4,), chunks=(4,), dtype="uint8", zarr_format=3) + arr[:] = np.arange(4, dtype="uint8") + + bad_keys = [k for k in store._store_dict if not k.startswith("subdir/")] + assert bad_keys == [], f"keys written outside the store's path prefix: {bad_keys}" + + store2 = ManagedMemoryStore.from_url("memory://fused-prefix-test/subdir") + arr2 = zarr.open_array(store2, mode="r") + np.testing.assert_array_equal(arr2[:], np.arange(4, dtype="uint8")) diff --git a/tests/test_store/test_object.py b/tests/test_store/test_object.py index 6a4b796639..1ea148b3c3 100644 --- a/tests/test_store/test_object.py +++ b/tests/test_store/test_object.py @@ -1,4 +1,4 @@ -# ruff: noqa: E402 +import re from pathlib import Path from typing import TypedDict @@ -9,9 +9,10 @@ from hypothesis.stateful import ( run_state_machine_as_test, ) -from obstore.store import LocalStore, MemoryStore +from obstore.store import LocalStore, MemoryStore, S3Store from zarr.core.buffer import Buffer, cpu +from zarr.core.sync import _collect_aiterator from zarr.storage import ObjectStore from zarr.testing.stateful import ZarrHierarchyStateMachine from zarr.testing.store import StoreTests @@ -97,6 +98,39 @@ async def test_store_getsize_prefix(self, store: ObjectStore[LocalStore]) -> Non assert total_size == len(buf) * 2 +@pytest.mark.filterwarnings( + re.escape("ignore:datetime.datetime.utcnow() is deprecated:DeprecationWarning") +) +async def test_list_dir_ignores_s3_prefix_marker(moto_server: str) -> None: + """Ensure obstore's exact-prefix S3 directory marker is not listed as a child.""" + boto3 = pytest.importorskip("boto3") + bucket = "object-store-prefix-marker" + client = boto3.client( + "s3", + endpoint_url=moto_server, + region_name="us-east-1", + aws_access_key_id="x", + aws_secret_access_key="x", + ) + client.create_bucket(Bucket=bucket) + client.put_object(Bucket=bucket, Key="g/", Body=b"") + + store = ObjectStore( + S3Store( + bucket=bucket, + endpoint=moto_server, + region="us-east-1", + access_key_id="x", + secret_access_key="x", + client_options={"allow_http": True}, + virtual_hosted_style_request=False, + ) + ) + + assert await _collect_aiterator(store.list_dir("g")) == () + assert await _collect_aiterator(store.list_dir("g/")) == () + + @pytest.mark.slow_hypothesis def test_zarr_hierarchy() -> None: sync_store = ObjectStore(MemoryStore()) diff --git a/tests/test_store/test_stateful.py b/tests/test_store/test_stateful.py index 6ea89d91d6..82b482d0ff 100644 --- a/tests/test_store/test_stateful.py +++ b/tests/test_store/test_stateful.py @@ -1,9 +1,12 @@ # Stateful tests for arbitrary Zarr stores. +from collections.abc import Generator + import pytest from hypothesis.stateful import ( run_state_machine_as_test, ) +import zarr from zarr.abc.store import Store from zarr.storage import LocalStore, ZipStore from zarr.testing.stateful import ZarrHierarchyStateMachine, ZarrStoreStateMachine @@ -15,6 +18,13 @@ ] +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None, None, None]: + """Enable rectilinear chunks since strategies may generate them.""" + with zarr.config.set({"array.rectilinear_chunks": True}): + yield + + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") def test_zarr_hierarchy(sync_store: Store) -> None: def mk_test_instance_sync() -> ZarrHierarchyStateMachine: diff --git a/tests/test_store/test_utils.py b/tests/test_store/test_utils.py new file mode 100644 index 0000000000..291526fab8 --- /dev/null +++ b/tests/test_store/test_utils.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import sys +from unittest.mock import patch + +import pytest + +from zarr.abc.store import SuffixByteRequest +from zarr.core.buffer.core import default_buffer_prototype +from zarr.storage._utils import ParsedStoreUrl, _normalize_byte_range_index, parse_store_url + + +class TestParseStoreUrl: + """Tests for parse_store_url.""" + + def test_memory_url(self) -> None: + result = parse_store_url("memory://mystore") + assert result == ParsedStoreUrl( + scheme="memory", name="mystore", path="", raw="memory://mystore" + ) + + def test_memory_url_with_path(self) -> None: + result = parse_store_url("memory://mystore/path/to/data") + assert result == ParsedStoreUrl( + scheme="memory", + name="mystore", + path="path/to/data", + raw="memory://mystore/path/to/data", + ) + + def test_memory_url_no_name(self) -> None: + result = parse_store_url("memory://") + assert result.scheme == "memory" + assert result.name is None + + def test_s3_url(self) -> None: + result = parse_store_url("s3://bucket/key") + assert result == ParsedStoreUrl( + scheme="s3", name="bucket", path="key", raw="s3://bucket/key" + ) + + def test_file_url(self) -> None: + result = parse_store_url("file:///tmp/test") + assert result.scheme == "file" + + def test_local_absolute_path(self) -> None: + result = parse_store_url("/local/path") + assert result == ParsedStoreUrl(scheme="", name=None, path="/local/path", raw="/local/path") + + def test_local_relative_path(self) -> None: + result = parse_store_url("relative/path") + assert result == ParsedStoreUrl( + scheme="", name=None, path="relative/path", raw="relative/path" + ) + + @pytest.mark.parametrize( + "url", + [ + "C:\\Users\\foo", + "C:/Users/foo", + "D:/data/zarr", + "c:/test", + ], + ) + def test_windows_drive_letter(self, url: str) -> None: + """On Windows, bare drive-letter paths must be treated as local paths.""" + with patch.object(sys, "platform", "win32"): + result = parse_store_url(url) + assert result.scheme == "" + assert result.name is None + assert result.path == url + assert result.raw == url + + @pytest.mark.parametrize( + "url", + [ + "file:///C:/Users/foo", + "file://C:/Users/foo", + ], + ) + def test_file_url_with_drive_letter_on_windows(self, url: str) -> None: + """file:// URLs with drive letters are not treated as bare paths.""" + with patch.object(sys, "platform", "win32"): + result = parse_store_url(url) + assert result.scheme == "file" + + @pytest.mark.parametrize( + "url", + [ + "C:\\Users\\foo", + "C:/Users/foo", + ], + ) + def test_drive_letter_not_special_on_non_windows(self, url: str) -> None: + """On non-Windows platforms, drive-letter paths go through urlparse.""" + with patch.object(sys, "platform", "linux"): + result = parse_store_url(url) + # urlparse interprets the drive letter as a scheme + assert result.scheme == "c" + + +class TestNormalizeByteRangeIndex: + """Tests for _normalize_byte_range_index.""" + + def test_suffix_larger_than_data_returns_all_bytes(self) -> None: + """Regression: SuffixByteRequest with suffix > len(data) must not produce a + negative start index that causes numpy to return fewer bytes than available.""" + prototype = default_buffer_prototype() + data = prototype.buffer.from_bytes(b"hello") # 5 bytes + byte_range = SuffixByteRequest(suffix=7) + start, stop = _normalize_byte_range_index(data, byte_range) + assert start == 0, f"start should be 0 (clamped), got {start}" + result = data[start:stop] + assert len(result) == 5, f"expected all 5 bytes, got {len(result)}" + + def test_suffix_exact_length(self) -> None: + """SuffixByteRequest with suffix == len(data) returns all bytes.""" + prototype = default_buffer_prototype() + data = prototype.buffer.from_bytes(b"hello") + start, _stop = _normalize_byte_range_index(data, SuffixByteRequest(suffix=5)) + assert start == 0 + + def test_suffix_shorter_than_data(self) -> None: + """SuffixByteRequest with suffix < len(data) returns the last n bytes.""" + prototype = default_buffer_prototype() + data = prototype.buffer.from_bytes(b"hello") + start, _stop = _normalize_byte_range_index(data, SuffixByteRequest(suffix=3)) + assert start == 2 diff --git a/tests/test_store/test_wrapper.py b/tests/test_store/test_wrapper.py index b34a63d5d0..e556a108c5 100644 --- a/tests/test_store/test_wrapper.py +++ b/tests/test_store/test_wrapper.py @@ -4,12 +4,12 @@ import pytest -from zarr.abc.store import ByteRequest, Store +from zarr.abc.store import ByteRequest, Store, _store_supports_sync_io from zarr.core.buffer import Buffer from zarr.core.buffer.cpu import Buffer as CPUBuffer from zarr.core.buffer.cpu import buffer_prototype -from zarr.storage import LocalStore, WrapperStore -from zarr.testing.store import StoreTests +from zarr.storage import LocalStore, MemoryStore, WrapperStore, ZipStore +from zarr.testing.store import LatencyStore, StoreTests if TYPE_CHECKING: from pathlib import Path @@ -123,3 +123,47 @@ async def get( await store_wrapped.get(key, buffer_prototype) captured = capsys.readouterr() assert f"getting {key}" in captured.out + + +@pytest.mark.parametrize( + ("store_factory", "expected"), + [ + (lambda tmp: MemoryStore(), True), + (lambda tmp: LocalStore(str(tmp)), True), + (lambda tmp: WrapperStore(MemoryStore()), True), + (lambda tmp: LatencyStore(MemoryStore()), True), + (lambda tmp: ZipStore(tmp / "store.zip", mode="w"), False), + (lambda tmp: WrapperStore(ZipStore(tmp / "store.zip", mode="w")), False), + ], + ids=[ + "memory", + "local", + "wrapper-of-memory", + "latency-wrapper-of-memory", + "zip", + "wrapper-of-zip", + ], +) +def test_supports_sync_io(store_factory: Any, expected: bool, tmp_path: Path | Any) -> None: + """`_store_supports_sync_io` is True only for stores implementing the full + sync surface (get_sync + set_sync + delete_sync); wrappers forward the + wrapped store's capability via `_supports_sync_io`.""" + assert _store_supports_sync_io(store_factory(tmp_path)) is expected + + +def test_wrapper_get_sync_without_inner_sync_raises(tmp_path: Any) -> None: + store = WrapperStore(ZipStore(tmp_path / "store.zip", mode="w")) + with pytest.raises(TypeError, match="does not support synchronous get"): + store.get_sync("key") + + +def test_wrapper_set_sync_without_inner_sync_raises(tmp_path: Any) -> None: + store = WrapperStore(ZipStore(tmp_path / "store.zip", mode="w")) + with pytest.raises(TypeError, match="does not support synchronous set"): + store.set_sync("key", CPUBuffer.from_bytes(b"data")) + + +def test_wrapper_delete_sync_without_inner_sync_raises(tmp_path: Any) -> None: + store = WrapperStore(ZipStore(tmp_path / "store.zip", mode="w")) + with pytest.raises(TypeError, match="does not support synchronous delete"): + store.delete_sync("key") diff --git a/tests/test_store/test_zip.py b/tests/test_store/test_zip.py index 744ee82945..32b18c5273 100644 --- a/tests/test_store/test_zip.py +++ b/tests/test_store/test_zip.py @@ -1,6 +1,8 @@ from __future__ import annotations +import io import os +import pickle import shutil import tempfile import zipfile @@ -8,11 +10,19 @@ import numpy as np import pytest +from hypothesis import settings +from hypothesis.stateful import ( + RuleBasedStateMachine, + initialize, + precondition, + rule, + run_state_machine_as_test, +) import zarr from zarr import create_array from zarr.core.buffer import Buffer, cpu, default_buffer_prototype -from zarr.core.group import Group +from zarr.core.sync import sync from zarr.storage import ZipStore from zarr.testing.store import StoreTests @@ -130,15 +140,40 @@ def test_externally_zipped_store(self, tmp_path: Path) -> None: zarr_path = tmp_path / "foo.zarr" root = zarr.open_group(store=zarr_path, mode="w") root.require_group("foo") - assert isinstance(foo := root["foo"], Group) # noqa: RUF018 + foo = root.get_group("foo") foo["bar"] = np.array([1]) shutil.make_archive(str(zarr_path), "zip", zarr_path) zip_path = tmp_path / "foo.zarr.zip" zipped = zarr.open_group(ZipStore(zip_path, mode="r"), mode="r") assert list(zipped.keys()) == list(root.keys()) - assert isinstance(group := zipped["foo"], Group) + group = zipped.get_group("foo") assert list(group.keys()) == list(group.keys()) + async def test_list_without_explicit_open(self, tmp_path: Path) -> None: + # ZipStore.list(), list_dir(), and exists() should auto-open + # the zip file just like _get() and _set() do. + zip_path = tmp_path / "data.zip" + zarr_path = tmp_path / "foo.zarr" + root = zarr.open_group(store=zarr_path, mode="w") + root["x"] = np.array([1, 2, 3]) + shutil.make_archive(str(zarr_path), "zip", zarr_path) + shutil.move(f"{zarr_path}.zip", zip_path) + + store = ZipStore(zip_path, mode="r") + assert not store._is_open + + keys = [k async for k in store.list()] + assert len(keys) > 0 + + store2 = ZipStore(zip_path, mode="r") + assert not store2._is_open + assert await store2.exists(keys[0]) + + store3 = ZipStore(zip_path, mode="r") + assert not store3._is_open + dir_keys = [k async for k in store3.list_dir("")] + assert len(dir_keys) > 0 + async def test_move(self, tmp_path: Path) -> None: origin = tmp_path / "origin.zip" destination = tmp_path / "some_folder" / "destination.zip" @@ -152,3 +187,223 @@ async def test_move(self, tmp_path: Path) -> None: assert destination.exists() assert not origin.exists() assert np.array_equal(array[...], np.arange(10)) + + +class TestZipStoreFileObj: + """ZipStore backed by an open binary file-like object instead of a path.""" + + @pytest.fixture + def zip_bytes(self, tmp_path: Path) -> bytes: + path = tmp_path / "data.zip" + store = ZipStore(path, mode="w") + zarr.create_array(store, data=np.arange(10), chunks=(5,)) + store.close() + return path.read_bytes() + + def test_read_from_fileobj(self, zip_bytes: bytes) -> None: + # an existing archive can be read through any seekable binary reader + store = ZipStore(io.BytesIO(zip_bytes), mode="r") + array = zarr.open_array(store, mode="r") + assert np.array_equal(array[...], np.arange(10)) + assert store.path is None + + def test_write_to_fileobj(self) -> None: + # a writable file object receives the archive; the bytes it holds + # after close() are a complete, reopenable zip + buffer = io.BytesIO() + store = ZipStore(buffer, mode="w", read_only=False) + zarr.create_array(store, data=np.arange(4)) + store.close() + + roundtrip = ZipStore(io.BytesIO(buffer.getvalue()), mode="r") + array = zarr.open_array(roundtrip, mode="r") + assert np.array_equal(array[...], np.arange(4)) + + async def test_clear_unsupported(self, zip_bytes: bytes) -> None: + # clear() requires a filesystem location, so it raises a clear error + # for file-object-backed stores + store = ZipStore(io.BytesIO(zip_bytes), mode="a", read_only=False) + store._sync_open() + with pytest.raises(NotImplementedError, match="clear.*file-like"): + await store.clear() + + async def test_move_unsupported(self, zip_bytes: bytes) -> None: + # move() requires a filesystem location, so it raises a clear error + # for file-object-backed stores + store = ZipStore(io.BytesIO(zip_bytes), mode="a", read_only=False) + store._sync_open() + with pytest.raises(NotImplementedError, match="move.*file-like"): + await store.move("elsewhere.zip") + + def test_invalid_file_object_rejected(self) -> None: + # objects without read/seek/tell are rejected at construction, not + # deep inside zipfile + with pytest.raises(TypeError, match="read/seek/tell"): + ZipStore(42, mode="r") # type: ignore[arg-type] + + @pytest.mark.parametrize("mode", ["w", "a", "x"]) + def test_non_iobase_reader_write_modes_rejected(self, zip_bytes: bytes, mode: str) -> None: + # readers that are not io.IOBase instances are adapted for reading + # only; write modes are rejected at construction with a clear error + class MinimalReader: + def __init__(self, data: bytes) -> None: + self._buffer = io.BytesIO(data) + + def read(self, size: int, /) -> bytes: + return self._buffer.read(size) + + def seek(self, pos: int, whence: int = 0, /) -> int: + return self._buffer.seek(pos, whence) + + def tell(self) -> int: + return self._buffer.tell() + + with pytest.raises(TypeError, match="opened for reading"): + ZipStore(MinimalReader(zip_bytes), mode=mode, read_only=False) # type: ignore[arg-type] + + def test_fsspec_file(self, tmp_path: Path, zip_bytes: bytes) -> None: + # a file opened through fsspec (already an io.IOBase) is used directly; + # fsspec's local filesystem stands in for a remote one + fsspec = pytest.importorskip("fsspec") + + path = tmp_path / "fsspec.zip" + path.write_bytes(zip_bytes) + with fsspec.open(f"local://{path}", "rb") as fileobj: + store = ZipStore(fileobj, mode="r") + array = zarr.open_array(store, mode="r") + assert np.array_equal(array[...], np.arange(10)) + assert store.path is None + + def test_obstore_reader(self, tmp_path: Path, zip_bytes: bytes) -> None: + # obstore's ReadableFile is not an io.IOBase and its read() returns a + # buffer-protocol object; ZipStore adapts it via _RawReaderAdapter + obstore = pytest.importorskip("obstore") + from obstore.store import LocalStore as ObstoreLocalStore + + (tmp_path / "obstore.zip").write_bytes(zip_bytes) + reader = obstore.open_reader(ObstoreLocalStore(str(tmp_path)), "obstore.zip") + store = ZipStore(reader, mode="r") + array = zarr.open_array(store, mode="r") + assert np.array_equal(array[...], np.arange(10)) + + def test_raw_reader_adapter_eof(self) -> None: + from zarr.storage._zip import _RawReaderAdapter + + class MinimalReader: + """Non-io.IOBase reader exposing only read/seek/tell, like obstore.""" + + def __init__(self, data: bytes) -> None: + self._buffer = io.BytesIO(data) + + def read(self, size: int, /) -> bytes: + return self._buffer.read(size) + + def seek(self, pos: int, whence: int = 0, /) -> int: + return self._buffer.seek(pos, whence) + + def tell(self) -> int: + return self._buffer.tell() + + # the adapter must clamp reads to EOF: some readers (obstore < 0.6) + # raise on short reads instead of returning fewer bytes + data = b"0123456789" + adapter = _RawReaderAdapter(MinimalReader(data)) # type: ignore[arg-type] + + # A read straddling EOF returns only the remaining bytes. + adapter.seek(len(data) - 3) + buf = bytearray(8) + assert adapter.readinto(buf) == 3 + assert bytes(buf[:3]) == data[-3:] + + # A read at EOF returns 0. + assert adapter.tell() == len(data) + assert adapter.readinto(bytearray(8)) == 0 + + def test_pickle_fileobj_raises(self, zip_bytes: bytes) -> None: + # an open file object cannot be reliably serialized, so pickling a + # file-object-backed store raises with a pointer at the alternative + store = ZipStore(io.BytesIO(zip_bytes), mode="r") + with pytest.raises(TypeError, match="cannot pickle a ZipStore backed by a file-like"): + pickle.dumps(store) + + def test_pickle_path_backed_roundtrip(self, tmp_path: Path, zip_bytes: bytes) -> None: + # path-backed stores remain picklable: the path is serialized and the + # archive is reopened on unpickling + path = tmp_path / "pickled.zip" + path.write_bytes(zip_bytes) + store = ZipStore(path, mode="r") + unpickled = pickle.loads(pickle.dumps(store)) + array = zarr.open_array(unpickled, mode="r") + assert np.array_equal(array[...], np.arange(10)) + + def test_str_and_eq(self, zip_bytes: bytes) -> None: + # file-object-backed stores stringify with the object repr and + # compare equal only when backed by the very same file object + fileobj = io.BytesIO(zip_bytes) + store = ZipStore(fileobj, mode="r") + assert str(store).startswith("zip://<") + assert store == ZipStore(fileobj, mode="r") + assert store != ZipStore(io.BytesIO(zip_bytes), mode="r") + + +class ZipStoreLifecycleMachine(RuleBasedStateMachine): + """Drive a ZipStore through construct / open / write / close transitions. + + Invariant under test: a constructed ZipStore can always be closed without + raising, regardless of whether it was ever opened or did any I/O. This is a + property-based generalization of the former example-based regression tests + for ZipStore.close() being called on a never-opened store (which raised + AttributeError because ``_lock`` is created lazily in ``_sync_open``). + """ + + def __init__(self, tmp_path: Path) -> None: + super().__init__() + self._tmp_path = tmp_path + self._counter = 0 + self.store: ZipStore | None = None + self._opened = False + + @initialize() + def start(self) -> None: + self.store = None + self._opened = False + + @precondition(lambda self: self.store is None) + @rule() + def construct(self) -> None: + # Fresh path each time so mode="w" never clobbers a closed archive. + self._counter += 1 + self.store = ZipStore(self._tmp_path / f"s{self._counter}.zip", mode="w") + self._opened = False + + @precondition(lambda self: self.store is not None and not self._opened) + @rule() + def open(self) -> None: + assert self.store is not None + self.store._sync_open() + self._opened = True + + @precondition(lambda self: self.store is not None and not self._opened) + @rule() + def write(self) -> None: + assert self.store is not None + # store.set auto-opens the store. + sync(self.store.set("a", cpu.Buffer.from_bytes(b"hi"))) + self._opened = True + + @precondition(lambda self: self.store is not None) + @rule() + def close(self) -> None: + assert self.store is not None + # The property under test: close() must never raise, even with no + # prior open or I/O. + self.store.close() + self.store = None + self._opened = False + + +def test_zipstore_close_lifecycle(tmp_path: Path) -> None: + run_state_machine_as_test( # type: ignore[no-untyped-call] + lambda: ZipStoreLifecycleMachine(tmp_path), + settings=settings(max_examples=50, deadline=None), + ) diff --git a/tests/test_unified_chunk_grid.py b/tests/test_unified_chunk_grid.py new file mode 100644 index 0000000000..f0b54519ab --- /dev/null +++ b/tests/test_unified_chunk_grid.py @@ -0,0 +1,2855 @@ +""" +Tests for the unified ChunkGrid design (POC). + +Tests the core ChunkGrid with FixedDimension/VaryingDimension internals, +ChunkSpec, serialization round-trips, indexing with rectilinear grids, +and end-to-end array creation + read/write. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr +from zarr.core.chunk_grids import ( + ChunkGrid, + ChunkSpec, + FixedDimension, + VaryingDimension, + _is_rectilinear_chunks, +) +from zarr.core.common import compress_rle, expand_rle +from zarr.core.metadata.v3 import ( + RectilinearChunkGridMetadata, + RectilinearChunkGridMetadataJSON, + RegularChunkGridMetadata, + parse_chunk_grid, +) +from zarr.errors import BoundsCheckError +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from collections.abc import Generator + from pathlib import Path + + +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None, None, None]: + """Enable rectilinear chunks for all tests in this module.""" + with zarr.config.set({"array.rectilinear_chunks": True}): + yield + + +def _edges(grid: ChunkGrid, dim: int) -> tuple[int, ...]: + """Extract the per-chunk edge lengths for *dim* from a ChunkGrid.""" + d = grid._dimensions[dim] + if isinstance(d, FixedDimension): + return tuple(d.size for _ in range(d.nchunks)) + if isinstance(d, VaryingDimension): + return tuple(d.edges) + raise TypeError(f"Unexpected dimension type: {type(d)}") + + +# --------------------------------------------------------------------------- +# Dimension index_to_chunk bounds tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("dim", "index", "match"), + [ + (VaryingDimension([10, 20, 30], extent=60), 60, "out of bounds"), + (VaryingDimension([10, 20, 30], extent=60), 100, "out of bounds"), + (FixedDimension(size=10, extent=95), 95, "out of bounds"), + (FixedDimension(size=10, extent=95), -1, "Negative"), + ], + ids=[ + "varying-at-extent", + "varying-past-extent", + "fixed-at-extent", + "fixed-negative", + ], +) +def test_dimension_index_to_chunk_bounds( + dim: FixedDimension | VaryingDimension, index: int, match: str +) -> None: + """Out-of-bounds or negative indices raise IndexError for both dimension types""" + with pytest.raises(IndexError, match=match): + dim.index_to_chunk(index) + + +@pytest.mark.parametrize( + ("dim", "index", "expected"), + [ + (VaryingDimension([10, 20, 30], extent=60), 59, 2), + (FixedDimension(size=10, extent=95), 94, 9), + ], + ids=["varying-last-valid", "fixed-last-valid"], +) +def test_dimension_index_to_chunk_last_valid( + dim: FixedDimension | VaryingDimension, index: int, expected: int +) -> None: + """Last valid index maps to the correct chunk for both dimension types""" + assert dim.index_to_chunk(index) == expected + + +# --------------------------------------------------------------------------- +# Rectilinear feature flag tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "action", + [ + lambda: RectilinearChunkGridMetadata(chunk_shapes=((10, 20), (25, 25))), + lambda: RectilinearChunkGridMetadata.from_dict( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20, 30], [50, 50]]}, + } + ), + lambda: zarr.create_array(MemoryStore(), shape=(30,), chunks=[[10, 20]], dtype="int32"), + ], + ids=["constructor", "from_dict", "create_array"], +) +def test_rectilinear_feature_flag_blocked(action: Any) -> None: + """Rectilinear chunk operations raise ValueError when the feature flag is disabled""" + with zarr.config.set({"array.rectilinear_chunks": False}): + with pytest.raises(ValueError, match="experimental and disabled by default"): + action() + + +def test_rectilinear_feature_flag_enabled() -> None: + """Rectilinear chunk grid construction succeeds when the feature flag is enabled""" + with zarr.config.set({"array.rectilinear_chunks": True}): + grid = RectilinearChunkGridMetadata(chunk_shapes=((10, 20), (25, 25))) + assert grid.ndim == 2 + + +# --------------------------------------------------------------------------- +# FixedDimension tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ( + "size", + "extent", + "chunk_ix", + "expected_nchunks", + "expected_chunk_size", + "expected_data_size", + "expected_offset", + ), + [ + (10, 100, 0, 10, 10, 10, 0), + (10, 100, 1, 10, 10, 10, 10), + (10, 100, 9, 10, 10, 10, 90), + (10, 95, 9, 10, 10, 5, 90), # boundary chunk + (0, 0, None, 0, None, None, None), # zero-size + ], + ids=["start", "middle", "end", "boundary", "zero-size"], +) +def test_fixed_dimension( + size: int, + extent: int, + chunk_ix: int | None, + expected_nchunks: int, + expected_chunk_size: int | None, + expected_data_size: int | None, + expected_offset: int | None, +) -> None: + """FixedDimension properties match expected values for various chunk/extent combinations""" + d = FixedDimension(size=size, extent=extent) + assert d.nchunks == expected_nchunks + if chunk_ix is not None: + assert d.chunk_size(chunk_ix) == expected_chunk_size + assert d.data_size(chunk_ix) == expected_data_size + assert d.chunk_offset(chunk_ix) == expected_offset + + +@pytest.mark.parametrize( + ("idx", "expected"), + [(0, 0), (9, 0), (10, 1), (25, 2)], +) +def test_fixed_dimension_index_to_chunk(idx: int, expected: int) -> None: + """FixedDimension.index_to_chunk maps element indices to correct chunk indices""" + d = FixedDimension(size=10, extent=100) + assert d.index_to_chunk(idx) == expected + + +def test_fixed_dimension_indices_to_chunks() -> None: + """FixedDimension.indices_to_chunks vectorizes index-to-chunk mapping over an array""" + d = FixedDimension(size=10, extent=100) + indices = np.array([0, 5, 10, 15, 99]) + np.testing.assert_array_equal(d.indices_to_chunks(indices), [0, 0, 1, 1, 9]) + + +@pytest.mark.parametrize( + ("size", "extent", "match"), + [(-1, 100, "must be >= 0"), (10, -1, "must be >= 0")], + ids=["negative-size", "negative-extent"], +) +def test_fixed_dimension_rejects_negative(size: int, extent: int, match: str) -> None: + """FixedDimension raises ValueError for negative size or extent""" + with pytest.raises(ValueError, match=match): + FixedDimension(size=size, extent=extent) + + +# --------------------------------------------------------------------------- +# VaryingDimension tests +# --------------------------------------------------------------------------- + + +def test_varying_dimension_construction() -> None: + """VaryingDimension stores edges, cumulative sums, nchunks, and extent correctly""" + d = VaryingDimension([10, 20, 30], extent=60) + assert d.edges == (10, 20, 30) + assert d.cumulative == (10, 30, 60) + assert d.nchunks == 3 + assert d.extent == 60 + + +@pytest.mark.parametrize( + ( + "chunk_idx", + "expected_offset", + "expected_size", + "expected_data", + "expected_chunk_for_first_idx", + ), + [ + (0, 0, 10, 10, 0), + (1, 10, 20, 20, 1), + (2, 30, 30, 30, 2), + ], +) +def test_varying_dimension( + chunk_idx: int, + expected_offset: int, + expected_size: int, + expected_data: int, + expected_chunk_for_first_idx: int, +) -> None: + """VaryingDimension chunk_offset, chunk_size, data_size, and index_to_chunk return correct values""" + d = VaryingDimension([10, 20, 30], extent=60) + assert d.chunk_offset(chunk_idx) == expected_offset + assert d.chunk_size(chunk_idx) == expected_size + assert d.data_size(chunk_idx) == expected_data + assert d.index_to_chunk(expected_offset) == expected_chunk_for_first_idx + + +def test_varying_dimension_indices_to_chunks() -> None: + """VaryingDimension.indices_to_chunks vectorizes index-to-chunk mapping over an array""" + d = VaryingDimension([10, 20, 30], extent=60) + indices = np.array([0, 9, 10, 29, 30, 59]) + np.testing.assert_array_equal(d.indices_to_chunks(indices), [0, 0, 1, 1, 2, 2]) + + +@pytest.mark.parametrize( + ("edges", "extent", "match"), + [ + ([], 0, "must not be empty"), + ([10, 0, 5], 15, "must be > 0"), + ], + ids=["empty", "zero-edge"], +) +def test_varying_dimension_rejects_invalid(edges: list[int], extent: int, match: str) -> None: + """VaryingDimension raises ValueError for empty edges or zero-length edges""" + with pytest.raises(ValueError, match=match): + VaryingDimension(edges, extent=extent) + + +# --------------------------------------------------------------------------- +# ChunkSpec tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("slices", "codec_shape", "expected_shape", "expected_boundary"), + [ + ((slice(0, 10), slice(0, 20)), (10, 20), (10, 20), False), + ((slice(90, 95), slice(0, 20)), (10, 20), (5, 20), True), + ((slice(10, 10),), (0,), (0,), False), + ((slice(0, 10), slice(0, 5)), (10, 10), (10, 5), True), + ], + ids=["basic", "boundary", "empty-slices", "multidim-boundary"], +) +def test_chunk_spec( + slices: tuple[slice, ...], + codec_shape: tuple[int, ...], + expected_shape: tuple[int, ...], + expected_boundary: bool, +) -> None: + """ChunkSpec reports correct shape and boundary status from slices and codec_shape""" + spec = ChunkSpec(slices=slices, codec_shape=codec_shape) + assert spec.shape == expected_shape + assert spec.is_boundary == expected_boundary + + +# --------------------------------------------------------------------------- +# ChunkGrid construction tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("array_shape", "chunk_sizes", "expected_regular", "expected_ndim", "expected_chunk_shape"), + [ + ((100, 200), (10, 20), True, 2, (10, 20)), + ((), (), True, 0, ()), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], False, 2, None), + ((30, 50), [[10, 10, 10], [25, 25]], True, 2, (10, 25)), # uniform edges → regular + ], + ids=["regular", "zero-dim", "rectilinear", "uniform-becomes-regular"], +) +def test_chunk_grid_construction( + array_shape: tuple[int, ...], + chunk_sizes: Any, + expected_regular: bool, + expected_ndim: int, + expected_chunk_shape: tuple[int, ...] | None, +) -> None: + """ChunkGrid.from_sizes produces grids with correct regularity, ndim, and chunk_shape""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + assert g.is_regular == expected_regular + assert g.ndim == expected_ndim + if expected_chunk_shape is not None: + assert g.chunk_shape == expected_chunk_shape + else: + with pytest.raises(ValueError, match="only available for regular"): + _ = g.chunk_shape + + +def test_chunk_grid_rectilinear_uniform_dim_is_fixed() -> None: + """A rectilinear grid with all-same sizes in one dim stores it as Fixed.""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]]) + assert isinstance(g._dimensions[0], VaryingDimension) + assert isinstance(g._dimensions[1], FixedDimension) + + +# --------------------------------------------------------------------------- +# ChunkGrid query tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected_grid_shape"), + [ + ((100, 200), (10, 20), (10, 10)), + ((95, 200), (10, 20), (10, 10)), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (3, 4)), + ], + ids=["regular", "regular-boundary", "rectilinear"], +) +def test_chunk_grid_shape( + shape: tuple[int, ...], + chunks: Any, + expected_grid_shape: tuple[int, ...], +) -> None: + """ChunkGrid.grid_shape returns the expected number of chunks per dimension""" + g = ChunkGrid.from_sizes(shape, chunks) + assert g.grid_shape == expected_grid_shape + + +@pytest.mark.parametrize( + ( + "array_shape", + "chunk_sizes", + "coords", + "expected_shape", + "expected_codec_shape", + "expected_boundary", + ), + [ + # regular interior + ((100, 200), (10, 20), (0, 0), (10, 20), (10, 20), False), + # regular boundary + ((95, 200), (10, 20), (9, 0), (5, 20), (10, 20), True), + # rectilinear + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (0, 0), (10, 25), (10, 25), False), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (1, 0), (20, 25), (20, 25), False), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (2, 3), (30, 25), (30, 25), False), + ], + ids=["regular", "regular-boundary", "rectilinear-0,0", "rectilinear-1,0", "rectilinear-2,3"], +) +def test_chunk_grid_getitem( + array_shape: tuple[int, ...], + chunk_sizes: Any, + coords: tuple[int, ...], + expected_shape: tuple[int, ...], + expected_codec_shape: tuple[int, ...], + expected_boundary: bool, +) -> None: + """ChunkGrid.__getitem__ returns a ChunkSpec with correct shape, codec_shape, and boundary flag""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + spec = g[coords] + assert spec is not None + assert spec.shape == expected_shape + assert spec.codec_shape == expected_codec_shape + assert spec.is_boundary == expected_boundary + + +@pytest.mark.parametrize( + ("array_shape", "chunk_sizes", "coords"), + [ + ((100, 200), (10, 20), (99, 0)), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (3, 0)), + ], + ids=["regular-oob", "rectilinear-oob"], +) +def test_chunk_grid_getitem_oob( + array_shape: tuple[int, ...], chunk_sizes: Any, coords: tuple[int, ...] +) -> None: + """Out-of-bounds chunk coordinates return None""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + assert g[coords] is None + + +def test_chunk_grid_getitem_slices() -> None: + """ChunkSpec.slices reflect the correct start/stop for a rectilinear chunk""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]]) + spec = g[(1, 2)] + assert spec is not None + assert spec.slices == (slice(10, 30, 1), slice(50, 75, 1)) + + +# -- all_chunk_coords tests -- + + +@pytest.mark.parametrize( + ("array_shape", "chunk_sizes", "origin", "selection_shape", "expected_coords"), + [ + # rectilinear grid + ( + (60, 100), + [[10, 20, 30], [50, 50]], + None, + None, + [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)], + ), + ((60, 100), [[10, 20, 30], [50, 50]], (1, 0), None, [(1, 0), (1, 1), (2, 0), (2, 1)]), + ((60, 100), [[10, 20, 30], [50, 50]], None, (2, 1), [(0, 0), (1, 0)]), + ((60, 100), [[10, 20, 30], [50, 50]], (1, 1), (2, 1), [(1, 1), (2, 1)]), + # regular grid + ((30, 40), (10, 20), (2, 1), None, [(2, 1)]), + ((30, 40), (10, 20), None, (0, 0), []), + ((60, 80), (20, 20), (0, 2), (3, 1), [(0, 2), (1, 2), (2, 2)]), + ], + ids=[ + "all", + "with-origin", + "with-sel-shape", + "origin+sel", + "last-chunk", + "zero-sel", + "single-dim", + ], +) +def test_all_chunk_coords( + array_shape: tuple[int, ...], + chunk_sizes: Any, + origin: tuple[int, ...] | None, + selection_shape: tuple[int, ...] | None, + expected_coords: list[tuple[int, ...]], +) -> None: + """all_chunk_coords yields the expected coordinates with optional origin and selection_shape""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + kwargs: dict[str, Any] = {} + if origin is not None: + kwargs["origin"] = origin + if selection_shape is not None: + kwargs["selection_shape"] = selection_shape + assert list(g.all_chunk_coords(**kwargs)) == expected_coords + + +def test_chunk_grid_get_nchunks() -> None: + """get_nchunks returns the total number of chunks across all dimensions""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + assert g.get_nchunks() == 6 + + +def test_chunk_grid_iter() -> None: + """Iterating a ChunkGrid yields the correct number of ChunkSpec objects""" + g = ChunkGrid.from_sizes((30, 40), (10, 20)) + specs = list(g) + assert len(specs) == 6 + assert all(isinstance(s, ChunkSpec) for s in specs) + + +# --------------------------------------------------------------------------- +# RLE tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("compressed", "expected"), + [ + ([[10, 3]], [10, 10, 10]), + ([[10, 2], [20, 1]], [10, 10, 20]), + ], +) +def test_rle_expand(compressed: list[Any], expected: list[int]) -> None: + """RLE-encoded edges expand correctly""" + assert expand_rle(compressed) == expected + + +@pytest.mark.parametrize( + ("original", "expected"), + [ + ([10, 10, 10], [[10, 3]]), + ([10, 10, 20], [[10, 2], 20]), + ([5], [5]), + ([10, 20, 30], [10, 20, 30]), + ], +) +def test_rle_compress(original: list[int], expected: list[Any]) -> None: + """compress_rle produces the expected RLE encoding for various input sequences""" + assert compress_rle(original) == expected + + +def test_rle_roundtrip() -> None: + """compress_rle followed by expand_rle recovers the original sequence""" + original = [10, 10, 10, 20, 20, 30] + compressed = compress_rle(original) + assert expand_rle(compressed) == original + + +@pytest.mark.parametrize( + ("rle_input", "match"), + [ + ([0], "Chunk edge length must be >= 1"), + ([-5], "Chunk edge length must be >= 1"), + ([[0, 3]], "Chunk edge length must be >= 1"), + ([[-10, 2]], "Chunk edge length must be >= 1"), + ([[5, 0]], "RLE repeat count must be >= 1"), + ([[5, -1]], "RLE repeat count must be >= 1"), + ], + ids=[ + "zero-edge", + "negative-edge", + "zero-rle-size", + "negative-rle-size", + "zero-rle-count", + "negative-rle-count", + ], +) +def test_rle_expand_rejects_invalid(rle_input: list[Any], match: str) -> None: + """expand_rle raises ValueError for zero/negative edge lengths or repeat counts""" + with pytest.raises(ValueError, match=match): + expand_rle(rle_input) + + +# -- expand_rle handles JSON floats -- + + +def test_expand_rle_bare_integer_floats_accepted() -> None: + """JSON parsers may emit 10.0 for the integer 10; expand_rle should handle it.""" + result = expand_rle([10.0, 20.0]) # type: ignore[list-item] + assert result == [10, 20] + + +def test_expand_rle_pair_with_float_count() -> None: + """expand_rle accepts float repeat counts that are integer-valued""" + result = expand_rle([[10, 3.0]]) # type: ignore[list-item] + assert result == [10, 10, 10] + + +# --------------------------------------------------------------------------- +# _is_rectilinear_chunks tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ([[10, 20], [5, 5]], True), + (((10, 20), (5, 5)), True), + ((10, 20), False), + ([10, 20], False), + (10, False), + ("auto", False), + ([], False), + ([[]], True), + (ChunkGrid.from_sizes((10,), (5,)), False), + (None, False), + (3.14, False), + ], + ids=[ + "nested-lists", + "nested-tuples", + "flat-tuple", + "flat-list", + "single-int", + "string", + "empty-list", + "empty-nested-list", + "chunk-grid-instance", + "none", + "float", + ], +) +def test_is_rectilinear_chunks(value: Any, expected: bool) -> None: + """_is_rectilinear_chunks correctly identifies nested sequences as rectilinear""" + assert _is_rectilinear_chunks(value) is expected + + +def test_is_rectilinear_chunks_handles_broken_iterable() -> None: + """_is_rectilinear_chunks returns False for objects that raise on iteration.""" + + class BrokenIter: + def __iter__(self) -> Any: + raise TypeError("cannot iterate") + + assert _is_rectilinear_chunks(BrokenIter()) is False + + +# --------------------------------------------------------------------------- +# Serialization tests +# --------------------------------------------------------------------------- + + +def test_serialization_error_non_regular_chunk_shape() -> None: + """Accessing chunk_shape on a non-regular grid raises ValueError.""" + grid = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]]) + with pytest.raises(ValueError, match="only available for regular"): + grid.chunk_shape # noqa: B018 + + +def test_serialization_error_zero_extent_rectilinear() -> None: + """RectilinearChunkGridMetadata rejects empty edge tuples.""" + with pytest.raises(ValueError, match="has no chunk edges"): + RectilinearChunkGridMetadata(chunk_shapes=((),)) + + +def test_serialization_unknown_name_parse() -> None: + """Parsing metadata with an unknown chunk grid name raises ValueError""" + with pytest.raises(ValueError, match="Unknown chunk grid"): + parse_chunk_grid({"name": "hexagonal", "configuration": {}}) + + +def test_from_metadata_unknown_chunk_grid_type() -> None: + """ChunkGrid.from_metadata raises TypeError for unrecognised chunk grid metadata.""" + from unittest.mock import MagicMock + + from zarr.core.metadata.v3 import ArrayV3Metadata + + mock_meta = MagicMock(spec=ArrayV3Metadata) + mock_meta.chunk_grid = MagicMock() # not Regular or Rectilinear + with pytest.raises(TypeError, match="Unknown chunk grid metadata type"): + ChunkGrid.from_metadata(mock_meta) + + +def test_from_sizes_rejects_empty_edge_list() -> None: + """ChunkGrid.from_sizes raises ValueError when a dimension has an empty edge list.""" + with pytest.raises(ValueError, match="at least one chunk"): + ChunkGrid.from_sizes((10,), ([],)) + + +# --------------------------------------------------------------------------- +# Spec compliance tests +# --------------------------------------------------------------------------- + + +def test_spec_kind_inline_required_on_deserialize() -> None: + """Deserialization requires kind: 'inline'.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"chunk_shapes": [[10, 20], [15, 15]]}, + } + with pytest.raises(ValueError, match="requires a 'kind' field"): + parse_chunk_grid(data) + + +def test_spec_kind_unknown_rejected() -> None: + """Unsupported rectilinear chunk grid kind raises ValueError on parse""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "reference", "chunk_shapes": [[10, 20], [15, 15]]}, + } + with pytest.raises(ValueError, match="Unsupported rectilinear chunk grid kind"): + parse_chunk_grid(data) + + +def test_spec_integer_shorthand_per_dimension() -> None: + """A bare integer in chunk_shapes means repeat until >= extent.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [4, [1, 2, 3]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6, 6), meta.chunk_shapes) + assert _edges(g, 0) == (4, 4) + assert _edges(g, 1) == (1, 2, 3) + + +def test_spec_mixed_rle_and_bare_integers() -> None: + """An array can mix bare integers and [value, count] RLE pairs.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[1, 3], 3]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6,), meta.chunk_shapes) + assert _edges(g, 0) == (1, 1, 1, 3) + + +def test_spec_overflow_chunks_allowed() -> None: + """Edge sum >= extent is valid (overflow chunks permitted).""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[4, 4, 4]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6,), meta.chunk_shapes) + assert _edges(g, 0) == (4, 4, 4) + + +def test_spec_example() -> None: + """The full example from the spec README.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + 4, + [1, 2, 3], + [[4, 2]], + [[1, 3], 3], + [4, 4, 4], + ], + }, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6, 6, 6, 6, 6), meta.chunk_shapes) + assert _edges(g, 0) == (4, 4) + assert _edges(g, 1) == (1, 2, 3) + assert _edges(g, 2) == (4, 4) + assert _edges(g, 3) == (1, 1, 1, 3) + assert _edges(g, 4) == (4, 4, 4) + + +# --------------------------------------------------------------------------- +# parse_chunk_grid validation tests +# --------------------------------------------------------------------------- + + +def test_parse_chunk_grid_varying_extent_mismatch_raises() -> None: + """Reconstructing a ChunkGrid with mismatched extents raises ValueError""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + with pytest.raises(ValueError, match="extent"): + ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (100, 100), strict=True) + ) + ) + + +def test_parse_chunk_grid_varying_extent_match_ok() -> None: + """Reconstructing a ChunkGrid with matching extents succeeds""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (60, 100), strict=True) + ) + ) + assert g2._dimensions[0].extent == 60 + + +@pytest.mark.parametrize( + ("chunk_shapes", "array_shape", "match"), + [ + ([[10, 20, 30], [25, 25]], (100, 50), "extent 100 exceeds sum of edges 60"), + ([[50, 50], [10, 20]], (100, 50), "extent 50 exceeds sum of edges 30"), + ], + ids=["first-dim-mismatch", "second-dim-mismatch"], +) +def test_parse_chunk_grid_rectilinear_extent_mismatch_raises( + chunk_shapes: list[list[int]], array_shape: tuple[int, ...], match: str +) -> None: + """Rectilinear grid raises ValueError when array extent exceeds sum of edges""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": chunk_shapes}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + with pytest.raises(ValueError, match=match): + ChunkGrid.from_sizes(array_shape, meta.chunk_shapes) + + +def test_parse_chunk_grid_rectilinear_extent_match_passes() -> None: + """Rectilinear grid with matching extents parses and builds successfully""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20, 30], [25, 25]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((60, 50), meta.chunk_shapes) + assert g.grid_shape == (3, 2) + + +def test_parse_chunk_grid_rectilinear_ndim_mismatch_raises() -> None: + """Mismatched ndim between array shape and chunk_sizes raises ValueError""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20], [25, 25]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + with pytest.raises(ValueError, match="3 dimensions but chunk_sizes has 2"): + ChunkGrid.from_sizes((30, 50, 100), meta.chunk_shapes) + + +def test_parse_chunk_grid_rectilinear_rle_extent_validated() -> None: + """RLE-encoded edges are expanded before validation.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[10, 5]], [[25, 2]]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((50, 50), meta.chunk_shapes) + assert g.grid_shape == (5, 2) + with pytest.raises(ValueError, match="extent 100 exceeds sum of edges 50"): + ChunkGrid.from_sizes((100, 50), meta.chunk_shapes) + + +def test_parse_chunk_grid_varying_dimension_extent_mismatch_on_chunkgrid_input() -> None: + """ChunkGrid constructor rejects VaryingDimension with extent exceeding sum of edges""" + g = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + with pytest.raises(ValueError, match="less than"): + ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (100, 50), strict=True) + ) + ) + + +# --------------------------------------------------------------------------- +# Rectilinear indexing tests +# --------------------------------------------------------------------------- + + +def test_basic_indexer_rectilinear() -> None: + """BasicIndexer produces correct projections for a full-slice rectilinear selection""" + from zarr.core.indexing import BasicIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = BasicIndexer( + selection=(slice(None), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 6 + + p0 = projections[0] + assert p0.chunk_coords == (0, 0) + assert p0.chunk_selection == (slice(0, 10, 1), slice(0, 50, 1)) + + p1 = projections[2] + assert p1.chunk_coords == (1, 0) + assert p1.chunk_selection == (slice(0, 20, 1), slice(0, 50, 1)) + + +def test_basic_indexer_int_selection() -> None: + """BasicIndexer with integer selection maps to the correct chunk and local offset""" + from zarr.core.indexing import BasicIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = BasicIndexer( + selection=(15, slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 2 + assert projections[0].chunk_coords == (1, 0) + assert projections[0].chunk_selection == (5, slice(0, 50, 1)) + + +def test_basic_indexer_slice_subset() -> None: + """BasicIndexer with partial slices spans the expected chunk dimensions""" + from zarr.core.indexing import BasicIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = BasicIndexer( + selection=(slice(5, 35), slice(0, 50)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + chunk_coords_dim0 = sorted({p.chunk_coords[0] for p in projections}) + assert chunk_coords_dim0 == [0, 1, 2] + + +def test_orthogonal_indexer_rectilinear() -> None: + """OrthogonalIndexer produces the expected number of projections for a rectilinear grid""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = OrthogonalIndexer( + selection=(slice(None), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 6 + + +def test_oob_block_raises_bounds_check_error() -> None: + """Out-of-bounds block index should raise BoundsCheckError, not IndexError.""" + store = MemoryStore() + a = zarr.create_array(store, shape=(30,), chunks=[[10, 20]], dtype="int32") + with pytest.raises(BoundsCheckError): + a.get_block_selection((2,)) + + +# --------------------------------------------------------------------------- +# End-to-end tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected_regular"), + [ + ((100, 200), (10, 20), True), + ((60, 100), [[10, 20, 30], [50, 50]], False), + ], + ids=["regular", "rectilinear"], +) +def test_e2e_create_array( + tmp_path: Path, shape: tuple[int, ...], chunks: Any, expected_regular: bool +) -> None: + """End-to-end array creation sets correct regularity and ndim on chunk_grid""" + arr = zarr.create_array( + store=tmp_path / "arr.zarr", + shape=shape, + chunks=chunks, + dtype="float32", + ) + assert ChunkGrid.from_metadata(arr.metadata).is_regular == expected_regular + assert ChunkGrid.from_metadata(arr.metadata).ndim == len(shape) + + +@pytest.mark.parametrize( + ("shape", "chunks", "grid_type_name", "grid_name"), + [ + ((100, 200), (10, 20), "RegularChunkGridMetadata", "regular"), + ((60, 100), [[10, 20, 30], [50, 50]], "RectilinearChunkGridMetadata", "rectilinear"), + ], + ids=["regular", "rectilinear"], +) +def test_e2e_chunk_grid_serializes( + tmp_path: Path, shape: tuple[int, ...], chunks: Any, grid_type_name: str, grid_name: str +) -> None: + """Array metadata serializes chunk_grid with the correct type and name""" + from zarr.core.metadata.v3 import ( + ArrayV3Metadata, + RectilinearChunkGridMetadata, + RegularChunkGridMetadata, + ) + + grid_type = ( + RegularChunkGridMetadata + if grid_type_name == "RegularChunkGridMetadata" + else RectilinearChunkGridMetadata + ) + arr = zarr.create_array( + store=tmp_path / "arr.zarr", + shape=shape, + chunks=chunks, + dtype="float32", + ) + assert isinstance(arr.metadata, ArrayV3Metadata) + assert isinstance(arr.metadata.chunk_grid, grid_type) + d = arr.metadata.to_dict() + chunk_grid_dict = d["chunk_grid"] + assert isinstance(chunk_grid_dict, dict) + assert chunk_grid_dict["name"] == grid_name + + +def test_e2e_chunk_grid_name_roundtrip_preserves_rectilinear(tmp_path: Path) -> None: + """A rectilinear grid with uniform edges stays 'rectilinear' through to_dict/from_dict.""" + from zarr.core.metadata.v3 import ArrayV3Metadata, RectilinearChunkGridMetadata + + meta_dict: dict[str, Any] = { + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "chunk_grid": { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[50, 2]], [[25, 4]]]}, + }, + "chunk_key_encoding": {"name": "default"}, + "data_type": "float32", + "fill_value": 0.0, + "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + } + meta = ArrayV3Metadata.from_dict(meta_dict) + assert isinstance(meta.chunk_grid, RectilinearChunkGridMetadata) + d = meta.to_dict() + chunk_grid_dict = d["chunk_grid"] + assert isinstance(chunk_grid_dict, dict) + assert chunk_grid_dict["name"] == "rectilinear" + + +def test_e2e_chunk_grid_name_regular_from_dict(tmp_path: Path) -> None: + """A 'regular' chunk grid name is preserved through from_dict.""" + from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGridMetadata + + meta_dict: dict[str, Any] = { + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [50, 25]}, + }, + "chunk_key_encoding": {"name": "default"}, + "data_type": "float32", + "fill_value": 0.0, + "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + } + meta = ArrayV3Metadata.from_dict(meta_dict) + assert isinstance(meta.chunk_grid, RegularChunkGridMetadata) + d = meta.to_dict() + chunk_grid_dict = d["chunk_grid"] + assert isinstance(chunk_grid_dict, dict) + assert chunk_grid_dict["name"] == "regular" + + +# --------------------------------------------------------------------------- +# Sharding compatibility tests +# --------------------------------------------------------------------------- + + +def test_sharding_accepts_rectilinear_outer_grid() -> None: + """ShardingCodec.validate should not reject rectilinear outer grids.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + codec = ShardingCodec(chunk_shape=(5, 5)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 20, 30), (50, 50))) + + codec.validate( + shape=(60, 100), + dtype=Float32(), + chunk_grid=grid_meta, + ) + + +def test_sharding_rejects_non_divisible_rectilinear() -> None: + """Rectilinear shard sizes not divisible by inner chunk_shape should raise.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + codec = ShardingCodec(chunk_shape=(5, 5)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 20, 17), (50, 50))) + + with pytest.raises(ValueError, match="divisible"): + codec.validate( + shape=(47, 100), + dtype=Float32(), + chunk_grid=grid_meta, + ) + + +def test_sharding_accepts_divisible_rectilinear() -> None: + """Rectilinear shard sizes all divisible by inner chunk_shape should pass.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + codec = ShardingCodec(chunk_shape=(5, 5)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 20, 30), (50, 50))) + + codec.validate( + shape=(60, 100), + dtype=Float32(), + chunk_grid=grid_meta, + ) + + +def test_sharding_rejects_non_divisible_among_repeated_edges() -> None: + """Shard validation catches a non-divisible edge even among many repeated valid ones.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + # edges (10, 10, 7) — 7 is not divisible by 5 + codec = ShardingCodec(chunk_shape=(5,)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 10, 7),)) + with pytest.raises(ValueError, match="divisible"): + codec.validate(shape=(27,), dtype=Float32(), chunk_grid=grid_meta) + + +def test_sharding_accepts_all_repeated_divisible_edges() -> None: + """Shard validation passes when all distinct edges are divisible by inner chunk size.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + # edges (10, 10, 20, 10) — unique values {10, 20}, both divisible by 5 + codec = ShardingCodec(chunk_shape=(5,)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 10, 20, 10),)) + codec.validate(shape=(50,), dtype=Float32(), chunk_grid=grid_meta) + + +# --------------------------------------------------------------------------- +# Edge cases +# --------------------------------------------------------------------------- + + +def test_edge_case_chunk_grid_boundary_getitem() -> None: + """ChunkGrid with boundary FixedDimension via direct construction.""" + g = ChunkGrid(dimensions=(FixedDimension(10, 95), FixedDimension(20, 40))) + spec = g[(9, 1)] + assert spec is not None + assert spec.shape == (5, 20) + assert spec.codec_shape == (10, 20) + assert spec.is_boundary + + +def test_edge_case_chunk_grid_boundary_iter() -> None: + """Iterating a boundary grid yields correct boundary ChunkSpecs.""" + g = ChunkGrid(dimensions=(FixedDimension(10, 25),)) + specs = list(g) + assert len(specs) == 3 + assert specs[0].shape == (10,) + assert specs[1].shape == (10,) + assert specs[2].shape == (5,) + assert specs[2].is_boundary + assert not specs[0].is_boundary + + +def test_edge_case_chunk_grid_boundary_shape() -> None: + """shape property with boundary extent.""" + g = ChunkGrid(dimensions=(FixedDimension(10, 95),)) + assert g.grid_shape == (10,) + + +# -- Zero-size and zero-extent -- + + +@pytest.mark.parametrize( + ("size", "extent"), + [(0, 0), (0, 5), (10, 0)], + ids=["zero-size-zero-extent", "zero-size-nonzero-extent", "zero-extent-nonzero-size"], +) +def test_edge_case_zero_size_or_extent(size: int, extent: int) -> None: + """FixedDimension with zero size or extent has zero chunks and getitem returns None""" + d = FixedDimension(size=size, extent=extent) + assert d.nchunks == 0 + g = ChunkGrid(dimensions=(d,)) + assert g[0] is None + + +def test_edge_case_zero_size_data_and_indices() -> None: + """FixedDimension(size=0) handles data_size, index_to_chunk, and indices_to_chunks safely.""" + d = FixedDimension(size=0, extent=0) + # Zero-sized chunks have zero data + assert d.data_size(0) == 0 + # Vectorized lookup maps every index to chunk 0 (avoids division by zero) + indices = np.array([0, 0, 0], dtype=np.intp) + np.testing.assert_array_equal(d.indices_to_chunks(indices), np.zeros(3, dtype=np.intp)) + + +def test_edge_case_zero_size_nonzero_extent_index() -> None: + """FixedDimension(size=0, extent>0) maps valid indices to chunk 0 without dividing by zero.""" + d = FixedDimension(size=0, extent=5) + assert d.nchunks == 0 + # index_to_chunk avoids division by zero and returns 0 + assert d.index_to_chunk(0) == 0 + assert d.index_to_chunk(4) == 0 + + +def test_edge_case_zero_size_data_and_index() -> None: + """FixedDimension(size=0) returns zero for data_size and maps indices to chunk 0.""" + d = FixedDimension(size=0, extent=0) + # data_size returns 0 for a zero-sized chunk + assert d.data_size(0) == 0 + # vectorized indices_to_chunks returns zeros + indices = np.array([0, 0, 0], dtype=np.intp) + np.testing.assert_array_equal(d.indices_to_chunks(indices), np.zeros(3, dtype=np.intp)) + + +# -- 0-d grid -- + + +def test_0d_grid_getitem() -> None: + """0-d grid has exactly one chunk at coords ().""" + g = ChunkGrid.from_sizes((), ()) + spec = g[()] + assert spec is not None + assert spec.shape == () + assert spec.codec_shape == () + assert not spec.is_boundary + + +def test_0d_grid_iter() -> None: + """0-d grid iteration yields a single ChunkSpec.""" + g = ChunkGrid.from_sizes((), ()) + specs = list(g) + assert len(specs) == 1 + + +def test_0d_grid_all_chunk_coords() -> None: + """0-d grid has one chunk coord: the empty tuple.""" + g = ChunkGrid.from_sizes((), ()) + coords = list(g.all_chunk_coords()) + assert coords == [()] + + +def test_0d_grid_nchunks() -> None: + """0-d grid reports exactly one chunk""" + g = ChunkGrid.from_sizes((), ()) + assert g.get_nchunks() == 1 + + +# -- parse_chunk_grid edge cases -- + + +def test_parse_chunk_grid_preserves_varying_extent() -> None: + """parse_chunk_grid does not overwrite VaryingDimension extent.""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + assert isinstance(g._dimensions[0], VaryingDimension) + assert g._dimensions[0].extent == 60 + + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (60, 100), strict=True) + ) + ) + assert isinstance(g2._dimensions[0], VaryingDimension) + assert g2._dimensions[0].extent == 60 + + +def test_parse_chunk_grid_rebinds_fixed_extent() -> None: + """parse_chunk_grid updates FixedDimension extent from array shape.""" + g = ChunkGrid.from_sizes((100, 200), (10, 20)) + assert g._dimensions[0].extent == 100 + + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (50, 100), strict=True) + ) + ) + assert isinstance(g2._dimensions[0], FixedDimension) + assert g2._dimensions[0].extent == 50 + assert g2.grid_shape == (5, 5) + + +# -- ChunkGrid.__getitem__ validation -- + + +def test_getitem_int_1d_regular() -> None: + """Integer indexing works for 1-d regular grids.""" + g = ChunkGrid.from_sizes((100,), (10,)) + spec = g[0] + assert spec is not None + assert spec.shape == (10,) + assert spec.slices == (slice(0, 10, 1),) + spec = g[9] + assert spec is not None + assert spec.shape == (10,) + + +def test_getitem_int_1d_rectilinear() -> None: + """Integer indexing works for 1-d rectilinear grids.""" + g = ChunkGrid.from_sizes((100,), [[20, 30, 50]]) + spec = g[0] + assert spec is not None + assert spec.shape == (20,) + spec = g[1] + assert spec is not None + assert spec.shape == (30,) + spec = g[2] + assert spec is not None + assert spec.shape == (50,) + + +@pytest.mark.parametrize( + ("shape", "chunks", "match"), + [ + ((), (), "Expected 0 coordinate.*got 1"), + ((100, 200), (10, 20), "Expected 2 coordinate.*got 1"), + ], + ids=["0d", "2d"], +) +def test_getitem_int_ndim_mismatch_raises( + shape: tuple[int, ...], chunks: tuple[int, ...], match: str +) -> None: + """Integer indexing on a multi-dim or 0-d grid raises ValueError for ndim mismatch""" + g = ChunkGrid.from_sizes(shape, chunks) + with pytest.raises(ValueError, match=match): + g[0] + + +@pytest.mark.parametrize( + "index", + [(10,), (99,), (-1,)], + ids=["oob-10", "oob-99", "negative"], +) +def test_getitem_oob_returns_none(index: tuple[int, ...]) -> None: + """Out-of-bounds or negative chunk indices return None""" + g = ChunkGrid.from_sizes((100,), (10,)) + assert g[index] is None + + +# -- Rectilinear with zero-nchunks FixedDimension -- + + +def test_zero_nchunks_fixed_dim_in_rectilinear() -> None: + """A rectilinear grid with a 0-extent FixedDimension still has valid size.""" + g = ChunkGrid( + dimensions=( + VaryingDimension([10, 20], extent=30), + FixedDimension(size=10, extent=0), + ) + ) + assert g.grid_shape == (2, 0) + + +# -- VaryingDimension data_size -- + + +def test_varying_dim_data_size_equals_chunk_size() -> None: + """For VaryingDimension, data_size == chunk_size (no padding).""" + d = VaryingDimension([10, 20, 5], extent=35) + for i in range(3): + assert d.data_size(i) == d.chunk_size(i) + + +# --------------------------------------------------------------------------- +# OrthogonalIndexer rectilinear tests +# --------------------------------------------------------------------------- + + +def test_orthogonal_int_array_selection_rectilinear() -> None: + """Integer array selection with rectilinear grid must produce correct + chunk-local selections.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = OrthogonalIndexer( + selection=(np.array([5, 15, 35]), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + chunk_coords = [p.chunk_coords for p in projections] + assert chunk_coords == [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)] + + +def test_orthogonal_bool_array_selection_rectilinear() -> None: + """Boolean array selection with rectilinear grid produces correct chunk projections.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + mask = np.zeros(60, dtype=bool) + mask[5] = True + mask[15] = True + mask[35] = True + indexer = OrthogonalIndexer( + selection=(mask, slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 6 + chunk_coords = [p.chunk_coords for p in projections] + assert (0, 0) in chunk_coords + assert (1, 0) in chunk_coords + assert (2, 0) in chunk_coords + assert (0, 1) in chunk_coords + assert (1, 1) in chunk_coords + assert (2, 1) in chunk_coords + + +def test_orthogonal_advanced_indexing_produces_correct_projections() -> None: + """Verify OrthogonalIndexer produces correct chunk projections + for advanced indexing with VaryingDimension.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = OrthogonalIndexer( + selection=(np.array([5, 15]), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 4 + coords = [p.chunk_coords for p in projections] + assert (0, 0) in coords + assert (0, 1) in coords + assert (1, 0) in coords + assert (1, 1) in coords + + +# --------------------------------------------------------------------------- +# Full pipeline rectilinear tests (helpers) +# --------------------------------------------------------------------------- + + +def _make_1d(tmp_path: Path) -> tuple[zarr.Array[Any], np.ndarray[Any, Any]]: + a = np.arange(30, dtype="int32") + z = zarr.create_array( + store=tmp_path / "arr1d.zarr", + shape=(30,), + chunks=[[5, 10, 15]], + dtype="int32", + ) + z[:] = a + return z, a + + +def _make_2d(tmp_path: Path) -> tuple[zarr.Array[Any], np.ndarray[Any, Any]]: + a = np.arange(6000, dtype="int32").reshape(60, 100) + z = zarr.create_array( + store=tmp_path / "arr2d.zarr", + shape=(60, 100), + chunks=[[10, 20, 30], [25, 25, 25, 25]], + dtype="int32", + ) + z[:] = a + return z, a + + +# --- Basic selection --- + + +def test_pipeline_basic_selection_1d(tmp_path: Path) -> None: + """1D rectilinear basic selections match numpy for ints, slices, and full-array reads""" + z, a = _make_1d(tmp_path) + sels: list[Any] = [0, 4, 5, 14, 15, 29, -1, slice(None), slice(3, 18), slice(0, 0)] + for sel in sels: + np.testing.assert_array_equal(z[sel], a[sel], err_msg=f"sel={sel}") + + +def test_pipeline_basic_selection_1d_strided(tmp_path: Path) -> None: + """1D rectilinear strided slice selections match numpy""" + z, a = _make_1d(tmp_path) + for sel in [slice(None, None, 2), slice(1, 25, 3), slice(0, 30, 7)]: + np.testing.assert_array_equal(z[sel], a[sel], err_msg=f"sel={sel}") + + +def test_pipeline_basic_selection_2d(tmp_path: Path) -> None: + """2D rectilinear basic selections match numpy across chunk boundaries""" + z, a = _make_2d(tmp_path) + selections: list[Any] = [ + 42, + -1, + (9, 24), + (10, 25), + (30, 50), + (59, 99), + slice(None), + (slice(5, 35), slice(20, 80)), + (slice(0, 10), slice(0, 25)), + (slice(10, 10), slice(None)), + (slice(None, None, 3), slice(None, None, 7)), + ] + for sel in selections: + np.testing.assert_array_equal(z[sel], a[sel], err_msg=f"sel={sel}") + + +# --- Orthogonal selection --- + + +def test_pipeline_orthogonal_selection_1d_bool(tmp_path: Path) -> None: + """1D boolean orthogonal indexing on rectilinear arrays matches numpy""" + z, a = _make_1d(tmp_path) + ix = np.zeros(30, dtype=bool) + ix[[0, 4, 5, 14, 15, 29]] = True + np.testing.assert_array_equal(z.oindex[ix], a[ix]) + + +def test_pipeline_orthogonal_selection_1d_int(tmp_path: Path) -> None: + """1D integer and negative-index orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_1d(tmp_path) + ix = np.array([0, 4, 5, 14, 15, 29]) + np.testing.assert_array_equal(z.oindex[ix], a[ix]) + ix_neg = np.array([0, -1, -15, -25]) + np.testing.assert_array_equal(z.oindex[ix_neg], a[ix_neg]) + + +def test_pipeline_orthogonal_selection_2d_bool(tmp_path: Path) -> None: + """2D boolean orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + ix0 = np.zeros(60, dtype=bool) + ix0[[0, 9, 10, 29, 30, 59]] = True + ix1 = np.zeros(100, dtype=bool) + ix1[[0, 24, 25, 49, 50, 99]] = True + np.testing.assert_array_equal(z.oindex[ix0, ix1], a[np.ix_(ix0, ix1)]) + + +def test_pipeline_orthogonal_selection_2d_int(tmp_path: Path) -> None: + """2D integer orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + ix0 = np.array([0, 9, 10, 29, 30, 59]) + ix1 = np.array([0, 24, 25, 49, 50, 99]) + np.testing.assert_array_equal(z.oindex[ix0, ix1], a[np.ix_(ix0, ix1)]) + + +def test_pipeline_orthogonal_selection_2d_mixed(tmp_path: Path) -> None: + """2D mixed int-array and slice orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + ix = np.array([0, 9, 10, 29, 30, 59]) + np.testing.assert_array_equal(z.oindex[ix, slice(25, 75)], a[np.ix_(ix, np.arange(25, 75))]) + np.testing.assert_array_equal( + z.oindex[slice(10, 30), ix[:4]], a[np.ix_(np.arange(10, 30), ix[:4])] + ) + + +# --- Coordinate (vindex) selection --- + + +def test_pipeline_coordinate_selection_1d(tmp_path: Path) -> None: + """1D coordinate (vindex) selection on rectilinear arrays matches numpy""" + z, a = _make_1d(tmp_path) + ix = np.array([0, 4, 5, 14, 15, 29]) + np.testing.assert_array_equal(z.vindex[ix], a[ix]) + + +def test_pipeline_coordinate_selection_2d(tmp_path: Path) -> None: + """2D coordinate (vindex) selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + r = np.array([0, 9, 10, 29, 30, 59]) + c = np.array([0, 24, 25, 49, 50, 99]) + np.testing.assert_array_equal(z.vindex[r, c], a[r, c]) + + +def test_pipeline_coordinate_selection_2d_bool_mask(tmp_path: Path) -> None: + """2D boolean mask vindex selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + mask = a > 3000 + np.testing.assert_array_equal(z.vindex[mask], a[mask]) + + +# --- Block selection --- + + +def test_pipeline_block_selection_1d(tmp_path: Path) -> None: + """1D block selection on rectilinear arrays returns correct chunk data""" + z, a = _make_1d(tmp_path) + np.testing.assert_array_equal(z.blocks[0], a[0:5]) + np.testing.assert_array_equal(z.blocks[1], a[5:15]) + np.testing.assert_array_equal(z.blocks[2], a[15:30]) + np.testing.assert_array_equal(z.blocks[-1], a[15:30]) + np.testing.assert_array_equal(z.blocks[0:2], a[0:15]) + np.testing.assert_array_equal(z.blocks[1:3], a[5:30]) + np.testing.assert_array_equal(z.blocks[:], a[:]) + + +def test_pipeline_block_selection_2d(tmp_path: Path) -> None: + """2D block selection on rectilinear arrays returns correct chunk data""" + z, a = _make_2d(tmp_path) + np.testing.assert_array_equal(z.blocks[0, 0], a[0:10, 0:25]) + np.testing.assert_array_equal(z.blocks[1, 2], a[10:30, 50:75]) + np.testing.assert_array_equal(z.blocks[2, 3], a[30:60, 75:100]) + np.testing.assert_array_equal(z.blocks[-1, -1], a[30:60, 75:100]) + np.testing.assert_array_equal(z.blocks[0:2, 1:3], a[0:30, 25:75]) + np.testing.assert_array_equal(z.blocks[:, :], a[:, :]) + + +def test_pipeline_set_block_selection_1d(tmp_path: Path) -> None: + """Writing via 1D block selection on rectilinear arrays persists correctly""" + z, a = _make_1d(tmp_path) + val = np.full(10, -1, dtype="int32") + z.blocks[1] = val + a[5:15] = val + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_set_block_selection_2d(tmp_path: Path) -> None: + """Writing via 2D block selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + val = np.full((30, 50), -99, dtype="int32") + z.blocks[0:2, 1:3] = val + a[0:30, 25:75] = val + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_block_selection_slice_stop_at_nchunks(tmp_path: Path) -> None: + """Block slice with stop == nchunks exercises the dim_len fallback.""" + z, a = _make_1d(tmp_path) + np.testing.assert_array_equal(z.blocks[1:3], a[5:30]) + np.testing.assert_array_equal(z.blocks[0:10], a[:]) + + +def test_pipeline_block_selection_slice_stop_at_nchunks_2d(tmp_path: Path) -> None: + """Same fallback test for 2D rectilinear arrays.""" + z, a = _make_2d(tmp_path) + np.testing.assert_array_equal(z.blocks[2:3, 3:4], a[30:60, 75:100]) + np.testing.assert_array_equal(z.blocks[0:99, 0:99], a[:, :]) + + +# --- Set coordinate selection --- + + +def test_pipeline_set_coordinate_selection_1d(tmp_path: Path) -> None: + """Writing via 1D coordinate selection on rectilinear arrays persists correctly""" + z, a = _make_1d(tmp_path) + ix = np.array([0, 4, 5, 14, 15, 29]) + val = np.full(len(ix), -7, dtype="int32") + z.vindex[ix] = val + a[ix] = val + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_set_coordinate_selection_2d(tmp_path: Path) -> None: + """Writing via 2D coordinate selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + r = np.array([0, 9, 10, 29, 30, 59]) + c = np.array([0, 24, 25, 49, 50, 99]) + val = np.full(len(r), -42, dtype="int32") + z.vindex[r, c] = val + a[r, c] = val + np.testing.assert_array_equal(z[:], a) + + +# --- Set selection --- + + +def test_pipeline_set_basic_selection(tmp_path: Path) -> None: + """Writing via basic slice selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + new_data = np.full((20, 50), -1, dtype="int32") + z[5:25, 10:60] = new_data + a[5:25, 10:60] = new_data + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_set_orthogonal_selection(tmp_path: Path) -> None: + """Writing via orthogonal selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + rows = np.array([0, 10, 30]) + cols = np.array([0, 25, 50, 75]) + val = np.full((3, 4), -99, dtype="int32") + z.oindex[rows, cols] = val + a[np.ix_(rows, cols)] = val + np.testing.assert_array_equal(z[:], a) + + +# --- Higher dimensions --- + + +def test_pipeline_3d_array(tmp_path: Path) -> None: + """3D rectilinear array write and read-back match numpy""" + shape = (12, 20, 15) + chunk_shapes = [[4, 8], [5, 5, 10], [5, 10]] + a = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + z = zarr.create_array( + store=tmp_path / "arr3d.zarr", + shape=shape, + chunks=chunk_shapes, + dtype="int32", + ) + z[:] = a + np.testing.assert_array_equal(z[:], a) + np.testing.assert_array_equal(z[2:10, 3:18, 4:14], a[2:10, 3:18, 4:14]) + + +def test_pipeline_1d_single_chunk(tmp_path: Path) -> None: + """Single-chunk rectilinear array write and read-back match numpy""" + a = np.arange(20, dtype="int32") + z = zarr.create_array( + store=tmp_path / "arr1c.zarr", + shape=(20,), + chunks=[[20]], + dtype="int32", + ) + z[:] = a + np.testing.assert_array_equal(z[:], a) + + +# --- Persistence roundtrip --- + + +def test_pipeline_persistence_roundtrip(tmp_path: Path) -> None: + """Rectilinear array survives close and reopen with correct data""" + _, a = _make_2d(tmp_path) + z2 = zarr.open_array(store=tmp_path / "arr2d.zarr", mode="r") + assert not ChunkGrid.from_metadata(z2.metadata).is_regular + np.testing.assert_array_equal(z2[:], a) + + +# --- Highly irregular chunks --- + + +def test_pipeline_highly_irregular_chunks(tmp_path: Path) -> None: + """Highly irregular chunk sizes produce correct write and partial-read results""" + shape = (100, 100) + chunk_shapes = [[5, 10, 15, 20, 50], [100]] + a = np.arange(10000, dtype="int32").reshape(shape) + z = zarr.create_array( + store=tmp_path / "irreg.zarr", + shape=shape, + chunks=chunk_shapes, + dtype="int32", + ) + z[:] = a + np.testing.assert_array_equal(z[:], a) + np.testing.assert_array_equal(z[3:97, 10:90], a[3:97, 10:90]) + + +# --- API validation --- + + +def test_pipeline_v2_rejects_rectilinear(tmp_path: Path) -> None: + """Creating a rectilinear array with zarr_format=2 raises ValueError""" + with pytest.raises(ValueError, match="Zarr format 2"): + zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(30,), + chunks=[[10, 20]], + dtype="int32", + zarr_format=2, + ) + + +def test_pipeline_sharding_rejects_rectilinear_chunks_with_shards(tmp_path: Path) -> None: + """Rectilinear chunks (inner) with sharding is not supported.""" + with pytest.raises(ValueError, match="Rectilinear chunks with sharding"): + zarr.create_array( + store=tmp_path / "shard.zarr", + shape=(60, 100), + chunks=[[10, 20, 30], [25, 25, 25, 25]], + shards=(30, 50), + dtype="int32", + ) + + +def test_pipeline_rectilinear_shards_roundtrip(tmp_path: Path) -> None: + """Rectilinear shards with uniform inner chunks: full write/read roundtrip.""" + data = np.arange(120 * 100, dtype="int32").reshape(120, 100) + arr = zarr.create_array( + store=tmp_path / "rect_shards.zarr", + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 40, 20], [50, 50]], + dtype="int32", + ) + arr[:] = data + result = arr[:] + np.testing.assert_array_equal(result, data) + + +def test_pipeline_rectilinear_shards_partial_read(tmp_path: Path) -> None: + """Partial reads across rectilinear shard boundaries.""" + data = np.arange(120 * 100, dtype="float64").reshape(120, 100) + arr = zarr.create_array( + store=tmp_path / "rect_shards.zarr", + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 40, 20], [50, 50]], + dtype="float64", + ) + arr[:] = data + result = arr[50:70, 40:60] + np.testing.assert_array_equal(result, data[50:70, 40:60]) + + +def test_pipeline_rectilinear_shards_validates_divisibility(tmp_path: Path) -> None: + """Inner chunk_shape must divide every shard's dimensions.""" + with pytest.raises(ValueError, match="divisible"): + zarr.create_array( + store=tmp_path / "bad.zarr", + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 45, 15], [50, 50]], + dtype="int32", + ) + + +def test_pipeline_nchunks(tmp_path: Path) -> None: + """Rectilinear array reports the correct total number of chunks""" + z, _ = _make_2d(tmp_path) + assert ChunkGrid.from_metadata(z.metadata).get_nchunks() == 12 + + +def test_pipeline_parse_chunk_grid_regular_from_dict() -> None: + """parse_chunk_grid constructs a regular grid from a metadata dict.""" + d: dict[str, Any] = {"name": "regular", "configuration": {"chunk_shape": [10, 20]}} + meta = parse_chunk_grid(d) + assert isinstance(meta, RegularChunkGridMetadata) + g = ChunkGrid.from_sizes((100, 200), tuple(meta.chunk_shape)) + assert g.is_regular + assert g.chunk_shape == (10, 20) + assert g.grid_shape == (10, 10) + assert g.get_nchunks() == 100 + + +# --------------------------------------------------------------------------- +# VaryingDimension boundary tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("edges", "extent", "chunk_idx", "expected_data_size"), + [ + ([10, 20, 30], 50, 0, 10), + ([10, 20, 30], 50, 1, 20), + ([10, 20, 30], 50, 2, 20), + ([10, 20, 30], 60, 2, 30), + ([10, 20, 30], 31, 0, 10), + ([10, 20, 30], 31, 1, 20), + ([10, 20, 30], 31, 2, 1), + ], + ids=[ + "interior-0", + "interior-1", + "boundary-clipped", + "exact-no-clip", + "single-element-boundary-0", + "single-element-boundary-1", + "single-element-boundary-2", + ], +) +def test_varying_dimension_boundary_data_size( + edges: list[int], extent: int, chunk_idx: int, expected_data_size: int +) -> None: + """VaryingDimension.data_size clips correctly at boundary chunks""" + d = VaryingDimension(edges, extent=extent) + assert d.data_size(chunk_idx) == expected_data_size + + +def test_varying_dimension_boundary_extent_parameter() -> None: + """VaryingDimension preserves extent and full chunk_size even when extent < sum of edges""" + d = VaryingDimension([10, 20, 30], extent=50) + assert d.extent == 50 + assert d.chunk_size(2) == 30 + + +def test_varying_dimension_extent_exceeds_sum_rejected() -> None: + """VaryingDimension rejects extent greater than sum of edges""" + with pytest.raises(ValueError, match="exceeds sum of edges"): + VaryingDimension([10, 20], extent=50) + + +def test_varying_dimension_negative_extent_rejected() -> None: + """VaryingDimension rejects negative extent""" + with pytest.raises(ValueError, match="must be >= 0"): + VaryingDimension([10, 20], extent=-1) + + +def test_varying_dimension_zero_extent() -> None: + """VaryingDimension with extent=0 has zero active chunks but retains all grid cells.""" + d = VaryingDimension([10, 20], extent=0) + assert d.nchunks == 0 + assert d.ngridcells == 2 + # No chunks overlap [0, 0), so the grid is structurally non-empty but logically empty + g = ChunkGrid(dimensions=(d,)) + assert g.grid_shape == (0,) + assert list(g) == [] + + +def test_varying_dimension_boundary_chunk_spec() -> None: + """ChunkGrid with a boundary VaryingDimension produces correct ChunkSpec.""" + g = ChunkGrid(dimensions=(VaryingDimension([10, 20, 30], extent=50),)) + spec = g[(2,)] + assert spec is not None + assert spec.codec_shape == (30,) + assert spec.shape == (20,) + assert spec.is_boundary is True + + +def test_varying_dimension_interior_chunk_spec() -> None: + """Interior VaryingDimension chunk has matching codec_shape and shape with no boundary""" + g = ChunkGrid(dimensions=(VaryingDimension([10, 20, 30], extent=50),)) + spec = g[(0,)] + assert spec is not None + assert spec.codec_shape == (10,) + assert spec.shape == (10,) + assert spec.is_boundary is False + + +# --------------------------------------------------------------------------- +# Multiple overflow chunks tests +# --------------------------------------------------------------------------- + + +def test_overflow_multiple_chunks_past_extent() -> None: + """Edges past extent are structural; nchunks counts active only.""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + d = g._dimensions[0] + assert d.ngridcells == 4 + assert d.nchunks == 3 + assert d.data_size(0) == 10 + assert d.data_size(1) == 20 + assert d.data_size(2) == 20 + assert d.chunk_size(2) == 30 + + +def test_overflow_chunk_spec_past_extent_is_oob() -> None: + """Chunk entirely past the extent is out of bounds (not active).""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + spec = g[(3,)] + assert spec is None + + +def test_overflow_chunk_spec_partial() -> None: + """ChunkSpec for a partially-overflowing chunk clips correctly.""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + spec = g[(2,)] + assert spec is not None + assert spec.shape == (20,) + assert spec.codec_shape == (30,) + assert spec.is_boundary is True + assert spec.slices == (slice(30, 50, 1),) + + +def test_overflow_chunk_sizes() -> None: + """chunk_sizes only includes active chunks.""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + assert g.chunk_sizes == ((10, 20, 20),) + + +def test_overflow_multidim() -> None: + """Overflow in multiple dimensions simultaneously.""" + g = ChunkGrid.from_sizes((45, 100), [[10, 20, 30], [40, 40, 40]]) + assert g.chunk_sizes == ((10, 20, 15), (40, 40, 20)) + spec = g[(2, 2)] + assert spec is not None + assert spec.shape == (15, 20) + assert spec.codec_shape == (30, 40) + + +def test_overflow_uniform_edges_collapses_to_fixed() -> None: + """Uniform edges where len == ceildiv(extent, edge) collapse to FixedDimension.""" + g = ChunkGrid.from_sizes((35,), [[10, 10, 10, 10]]) + assert isinstance(g._dimensions[0], FixedDimension) + assert g.is_regular + assert g.chunk_sizes == ((10, 10, 10, 5),) + assert g._dimensions[0].nchunks == 4 + + +def test_overflow_index_to_chunk_near_extent() -> None: + """Index lookup near and at the extent boundary.""" + d = VaryingDimension([10, 20, 30, 40], extent=50) + assert d.index_to_chunk(29) == 1 + assert d.index_to_chunk(30) == 2 + assert d.index_to_chunk(49) == 2 + + +# --------------------------------------------------------------------------- +# Boundary indexing tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ( + "dim", + "mask", + "dim_len", + "expected_chunk_ix", + "expected_sel_len", + "expected_first_two", + "expected_third", + ), + [ + ( + FixedDimension(size=5, extent=7), + np.array([False, False, False, False, False, True, True]), + 7, + 1, + 5, + (np.True_, np.True_), + np.False_, + ), + ( + VaryingDimension([5, 10], extent=7), + np.array([False, False, False, False, False, True, True]), + 7, + 1, + 10, + (np.True_, np.True_), + np.False_, + ), + ], + ids=["fixed-boundary", "varying-boundary"], +) +def test_bool_indexer_boundary( + dim: FixedDimension | VaryingDimension, + mask: np.ndarray[Any, Any], + dim_len: int, + expected_chunk_ix: int, + expected_sel_len: int, + expected_first_two: tuple[Any, Any], + expected_third: Any, +) -> None: + """BoolArrayDimIndexer pads to codec size for boundary chunks.""" + from zarr.core.indexing import BoolArrayDimIndexer + + indexer = BoolArrayDimIndexer(mask, dim_len, dim) + projections = list(indexer) + assert len(projections) == 1 + p = projections[0] + assert p.dim_chunk_ix == expected_chunk_ix + sel = p.dim_chunk_sel + assert isinstance(sel, np.ndarray) + assert sel.shape[0] == expected_sel_len + assert sel[0] is expected_first_two[0] + assert sel[1] is expected_first_two[1] + assert sel[2] is expected_third + + +def test_bool_indexer_no_padding_interior() -> None: + """No padding needed for interior chunks.""" + from zarr.core.indexing import BoolArrayDimIndexer + + dim = FixedDimension(size=5, extent=10) + mask = np.array([True, False, False, False, False, False, False, False, False, False]) + indexer = BoolArrayDimIndexer(mask, 10, dim) + projections = list(indexer) + assert len(projections) == 1 + p = projections[0] + assert p.dim_chunk_ix == 0 + sel = p.dim_chunk_sel + assert isinstance(sel, np.ndarray) + assert sel.shape[0] == 5 + + +def test_slice_indexer_varying_boundary() -> None: + """SliceDimIndexer clips to data_size at boundary for VaryingDimension.""" + from zarr.core.indexing import SliceDimIndexer + + dim = VaryingDimension([5, 10], extent=7) + indexer = SliceDimIndexer(slice(None), 7, dim) + projections = list(indexer) + assert len(projections) == 2 + assert projections[0].dim_chunk_sel == slice(0, 5, 1) + assert projections[1].dim_chunk_sel == slice(0, 2, 1) + + +def test_int_array_indexer_varying_boundary() -> None: + """IntArrayDimIndexer handles indices near boundary correctly.""" + from zarr.core.indexing import IntArrayDimIndexer + + dim = VaryingDimension([5, 10], extent=7) + indices = np.array([6]) + indexer = IntArrayDimIndexer(indices, 7, dim) + projections = list(indexer) + assert len(projections) == 1 + assert projections[0].dim_chunk_ix == 1 + sel = projections[0].dim_chunk_sel + assert isinstance(sel, np.ndarray) + np.testing.assert_array_equal(sel, [1]) + + +@pytest.mark.parametrize( + "dim", + [FixedDimension(size=2, extent=10), VaryingDimension([5, 5], extent=10)], + ids=["fixed", "varying"], +) +def test_slice_indexer_empty_slice_at_boundary(dim: FixedDimension | VaryingDimension) -> None: + """SliceDimIndexer yields no projections for an empty slice at the dimension boundary.""" + from zarr.core.indexing import SliceDimIndexer + + indexer = SliceDimIndexer(slice(10, 10), 10, dim) + projections = list(indexer) + assert len(projections) == 0 + + +def test_orthogonal_indexer_varying_boundary_advanced() -> None: + """OrthogonalIndexer with advanced indexing uses per-chunk chunk_size.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid( + dimensions=( + VaryingDimension([5, 10], extent=7), + FixedDimension(size=4, extent=8), + ) + ) + indexer = OrthogonalIndexer( + selection=(np.array([0, 6]), slice(None)), + shape=(7, 8), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 4 + coords = {p.chunk_coords for p in projections} + assert coords == {(0, 0), (0, 1), (1, 0), (1, 1)} + + +# --------------------------------------------------------------------------- +# update_shape tests +# --------------------------------------------------------------------------- + + +def test_update_shape_no_change() -> None: + """update_shape with the same shape preserves edges unchanged""" + grid = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + new_grid = grid.update_shape((60, 50)) + assert _edges(new_grid, 0) == (10, 20, 30) + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_grow_single_dim() -> None: + """Growing a single dimension appends a new edge chunk""" + grid = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + new_grid = grid.update_shape((80, 50)) + assert _edges(new_grid, 0) == (10, 20, 30, 20) + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_grow_multiple_dims() -> None: + """Growing multiple dimensions appends correctly sized edge chunks""" + grid = ChunkGrid.from_sizes((30, 50), [[10, 20], [20, 30]]) + new_grid = grid.update_shape((45, 65)) + assert _edges(new_grid, 0) == (10, 20, 15) + assert _edges(new_grid, 1) == (20, 30, 15) + + +def test_update_shape_shrink_single_dim() -> None: + """Shrinking a single dimension reduces nchunks while preserving edges""" + grid = ChunkGrid.from_sizes((100, 50), [[10, 20, 30, 40], [25, 25]]) + new_grid = grid.update_shape((35, 50)) + assert _edges(new_grid, 0) == (10, 20, 30, 40) + assert new_grid._dimensions[0].nchunks == 3 + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_shrink_to_single_chunk() -> None: + """Shrinking to fit within the first chunk reduces nchunks to 1""" + grid = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + new_grid = grid.update_shape((5, 50)) + assert _edges(new_grid, 0) == (10, 20, 30) + assert new_grid._dimensions[0].nchunks == 1 + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_shrink_multiple_dims() -> None: + """Shrinking multiple dimensions reduces nchunks in each dimension""" + grid = ChunkGrid.from_sizes((40, 60), [[10, 10, 15, 5], [20, 25, 15]]) + new_grid = grid.update_shape((25, 35)) + assert _edges(new_grid, 0) == (10, 10, 15, 5) + assert new_grid._dimensions[0].nchunks == 3 + assert _edges(new_grid, 1) == (20, 25, 15) + assert new_grid._dimensions[1].nchunks == 2 + + +def test_update_shape_dimension_mismatch_error() -> None: + """update_shape raises ValueError when new shape has different ndim""" + grid = ChunkGrid.from_sizes((30, 70), [[10, 20], [30, 40]]) + with pytest.raises(ValueError, match="dimensions"): + grid.update_shape((30, 70, 100)) + + +def test_update_shape_boundary_cases() -> None: + """update_shape handles grow-one-dim and shrink-both-dims edge cases correctly""" + grid = ChunkGrid.from_sizes((60, 40), [[10, 20, 30], [15, 25]]) + new_grid = grid.update_shape((60, 65)) + assert _edges(new_grid, 0) == (10, 20, 30) + assert _edges(new_grid, 1) == (15, 25, 25) + + grid2 = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [15, 25, 10]]) + new_grid2 = grid2.update_shape((30, 40)) + assert _edges(new_grid2, 0) == (10, 20, 30) + assert new_grid2._dimensions[0].nchunks == 2 + assert _edges(new_grid2, 1) == (15, 25, 10) + assert new_grid2._dimensions[1].nchunks == 2 + + +def test_update_shape_regular_preserves_extents(tmp_path: Path) -> None: + """Resize a regular array -- chunk_grid extents must match new shape.""" + z = zarr.create_array( + store=tmp_path / "regular.zarr", + shape=(100,), + chunks=(10,), + dtype="int32", + ) + z[:] = np.arange(100, dtype="int32") + z.resize(50) + assert z.shape == (50,) + assert ChunkGrid.from_metadata(z.metadata)._dimensions[0].extent == 50 + + +# --------------------------------------------------------------------------- +# update_shape boundary tests +# --------------------------------------------------------------------------- + + +def test_update_shape_shrink_creates_boundary() -> None: + """Shrinking extent into a chunk creates a boundary with clipped data_size""" + grid = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + new_grid = grid.update_shape((45,)) + dim = new_grid._dimensions[0] + assert isinstance(dim, VaryingDimension) + assert dim.edges == (10, 20, 30) + assert dim.extent == 45 + assert dim.chunk_size(2) == 30 + assert dim.data_size(2) == 15 + + +def test_update_shape_shrink_to_exact_boundary() -> None: + """Shrinking to an exact chunk boundary reduces nchunks without partial data""" + grid = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + new_grid = grid.update_shape((30,)) + dim = new_grid._dimensions[0] + assert isinstance(dim, VaryingDimension) + assert dim.edges == (10, 20, 30) + assert dim.nchunks == 2 + assert dim.ngridcells == 3 + assert dim.extent == 30 + assert dim.data_size(1) == 20 + + +def test_update_shape_shrink_chunk_spec() -> None: + """After shrink, ChunkSpec reflects boundary correctly.""" + grid = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + new_grid = grid.update_shape((45,)) + spec = new_grid[(2,)] + assert spec is not None + assert spec.codec_shape == (30,) + assert spec.shape == (15,) + assert spec.is_boundary is True + + +def test_update_shape_parse_chunk_grid_rebinds_extent() -> None: + """parse_chunk_grid re-binds VaryingDimension extent to array shape.""" + g = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (50,), strict=True) + ) + ) + dim = g2._dimensions[0] + assert isinstance(dim, VaryingDimension) + assert dim.extent == 50 + assert dim.data_size(2) == 20 + + +# --------------------------------------------------------------------------- +# Resize rectilinear tests +# --------------------------------------------------------------------------- + + +async def test_async_resize_grow() -> None: + """Async resize grow appends new edge chunks and preserves existing data""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(30, 40), + chunks=[[10, 20], [20, 20]], + dtype="i4", + zarr_format=3, + ) + data = np.arange(30 * 40, dtype="i4").reshape(30, 40) + await arr.setitem(slice(None), data) + + await arr.resize((50, 60)) + assert arr.shape == (50, 60) + assert _edges(ChunkGrid.from_metadata(arr.metadata), 0) == (10, 20, 20) + assert _edges(ChunkGrid.from_metadata(arr.metadata), 1) == (20, 20, 20) + result = await arr.getitem((slice(0, 30), slice(0, 40))) + np.testing.assert_array_equal(result, data) + + +async def test_async_resize_shrink() -> None: + """Async resize shrink truncates data to the new shape""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(60, 50), + chunks=[[10, 20, 30], [25, 25]], + dtype="f4", + zarr_format=3, + ) + data = np.arange(60 * 50, dtype="f4").reshape(60, 50) + await arr.setitem(slice(None), data) + + await arr.resize((25, 30)) + assert arr.shape == (25, 30) + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, data[:25, :30]) + + +def test_sync_resize_grow() -> None: + """Sync resize grow expands the array and preserves existing data""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(20, 30), + chunks=[[8, 12], [10, 20]], + dtype="u1", + zarr_format=3, + ) + data = np.arange(20 * 30, dtype="u1").reshape(20, 30) + arr[:] = data + arr.resize((35, 45)) + assert arr.shape == (35, 45) + np.testing.assert_array_equal(arr[:20, :30], data) + + +def test_sync_resize_shrink() -> None: + """Sync resize shrink truncates the array and returns correct data""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(40, 50), + chunks=[[10, 15, 15], [20, 30]], + dtype="i2", + zarr_format=3, + ) + data = np.arange(40 * 50, dtype="i2").reshape(40, 50) + arr[:] = data + arr.resize((15, 30)) + assert arr.shape == (15, 30) + np.testing.assert_array_equal(arr[:], data[:15, :30]) + + +# --------------------------------------------------------------------------- +# Append rectilinear tests +# --------------------------------------------------------------------------- + + +async def test_append_first_axis() -> None: + """Appending along axis 0 grows the array and concatenates data correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(30, 20), + chunks=[[10, 20], [10, 10]], + dtype="i4", + zarr_format=3, + ) + initial = np.arange(30 * 20, dtype="i4").reshape(30, 20) + await arr.setitem(slice(None), initial) + + append_data = np.arange(30 * 20, 45 * 20, dtype="i4").reshape(15, 20) + await arr.append(append_data, axis=0) + assert arr.shape == (45, 20) + + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, np.vstack([initial, append_data])) + + +async def test_append_second_axis() -> None: + """Appending along axis 1 grows the array and concatenates data correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(20, 30), + chunks=[[10, 10], [10, 20]], + dtype="f4", + zarr_format=3, + ) + initial = np.arange(20 * 30, dtype="f4").reshape(20, 30) + await arr.setitem(slice(None), initial) + + append_data = np.arange(20 * 30, 20 * 45, dtype="f4").reshape(20, 15) + await arr.append(append_data, axis=1) + assert arr.shape == (20, 45) + + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, np.hstack([initial, append_data])) + + +def test_sync_append() -> None: + """Sync append grows the array and preserves both initial and appended data""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(20, 20), + chunks=[[8, 12], [7, 13]], + dtype="u2", + zarr_format=3, + ) + initial = np.arange(20 * 20, dtype="u2").reshape(20, 20) + arr[:] = initial + + append_data = np.arange(20 * 20, 25 * 20, dtype="u2").reshape(5, 20) + arr.append(append_data, axis=0) + assert arr.shape == (25, 20) + np.testing.assert_array_equal(arr[:20, :], initial) + np.testing.assert_array_equal(arr[20:, :], append_data) + + +async def test_multiple_appends() -> None: + """Multiple sequential appends accumulate data correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(10, 10), + chunks=[[3, 7], [4, 6]], + dtype="i4", + zarr_format=3, + ) + initial = np.arange(10 * 10, dtype="i4").reshape(10, 10) + await arr.setitem(slice(None), initial) + + all_data = [initial] + for i in range(3): + chunk = np.full((5, 10), i + 100, dtype="i4") + await arr.append(chunk, axis=0) + all_data.append(chunk) + + assert arr.shape == (25, 10) + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, np.vstack(all_data)) + + +async def test_append_with_partial_edge_chunks() -> None: + """Appending data that creates partial edge chunks preserves all data""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(25, 30), + chunks=[[10, 15], [12, 18]], + dtype="f8", + zarr_format=3, + ) + initial = np.random.default_rng(42).random((25, 30)) + await arr.setitem(slice(None), initial) + + append_data = np.random.default_rng(43).random((10, 30)) + await arr.append(append_data, axis=0) + assert arr.shape == (35, 30) + + result = np.asarray(await arr.getitem(slice(None))) + np.testing.assert_array_almost_equal(result, np.vstack([initial, append_data])) + + +async def test_append_small_data() -> None: + """Appending a small amount of data smaller than a chunk works correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(20, 20), + chunks=[[8, 12], [7, 13]], + dtype="i4", + zarr_format=3, + ) + data = np.arange(20 * 20, dtype="i4").reshape(20, 20) + await arr.setitem(slice(None), data) + + small = np.full((3, 20), 999, dtype="i4") + await arr.append(small, axis=0) + assert arr.shape == (23, 20) + result = await arr.getitem((slice(20, 23), slice(None))) + np.testing.assert_array_equal(result, small) + + +# --------------------------------------------------------------------------- +# V2 regression tests +# --------------------------------------------------------------------------- + + +def test_v2_create_and_readback(tmp_path: Path) -> None: + """Basic V2 array: create, write, read back.""" + data = np.arange(60, dtype="float64").reshape(6, 10) + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=data.shape, + chunks=(3, 5), + dtype=data.dtype, + zarr_format=2, + ) + a[:] = data + np.testing.assert_array_equal(a[:], data) + + +def test_v2_chunk_grid_is_regular(tmp_path: Path) -> None: + """V2 chunk_grid produces a regular ChunkGrid with FixedDimensions.""" + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(20, 30), + chunks=(10, 15), + dtype="int32", + zarr_format=2, + ) + grid = ChunkGrid.from_metadata(a.metadata) + assert grid.is_regular + assert grid.chunk_shape == (10, 15) + assert grid.grid_shape == (2, 2) + assert all(isinstance(d, FixedDimension) for d in grid._dimensions) + + +def test_v2_boundary_chunks(tmp_path: Path) -> None: + """V2 boundary chunks: codec buffer size stays full, data is clipped.""" + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(25,), + chunks=(10,), + dtype="int32", + zarr_format=2, + ) + grid = ChunkGrid.from_metadata(a.metadata) + assert grid._dimensions[0].nchunks == 3 + assert grid._dimensions[0].chunk_size(2) == 10 + assert grid._dimensions[0].data_size(2) == 5 + + +def test_v2_slicing_with_boundary(tmp_path: Path) -> None: + """V2 array slicing across boundary chunks returns correct data.""" + data = np.arange(25, dtype="int32") + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(25,), + chunks=(10,), + dtype="int32", + zarr_format=2, + ) + a[:] = data + np.testing.assert_array_equal(a[18:25], data[18:25]) + np.testing.assert_array_equal(a[:], data) + + +def test_v2_metadata_roundtrip(tmp_path: Path) -> None: + """V2 metadata survives store close and reopen.""" + store_path = tmp_path / "v2.zarr" + data = np.arange(12, dtype="float32").reshape(3, 4) + a = zarr.create_array( + store=store_path, + shape=data.shape, + chunks=(2, 2), + dtype=data.dtype, + zarr_format=2, + ) + a[:] = data + + b = zarr.open_array(store=store_path, mode="r") + assert b.metadata.zarr_format == 2 + assert b.chunks == (2, 2) + assert ChunkGrid.from_metadata(b.metadata).chunk_shape == (2, 2) + np.testing.assert_array_equal(b[:], data) + + +def test_v2_chunk_spec_via_grid(tmp_path: Path) -> None: + """ChunkSpec from V2 grid has correct slices and codec_shape.""" + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(15, 20), + chunks=(10, 10), + dtype="int32", + zarr_format=2, + ) + grid = ChunkGrid.from_metadata(a.metadata) + spec = grid[(0, 0)] + assert spec is not None + assert spec.shape == (10, 10) + assert spec.codec_shape == (10, 10) + spec = grid[(1, 1)] + assert spec is not None + assert spec.shape == (5, 10) + assert spec.codec_shape == (10, 10) + + +# --------------------------------------------------------------------------- +# ChunkSizes tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected"), + [ + ((100, 80), (30, 40), ((30, 30, 30, 10), (40, 40))), + ((90, 80), (30, 40), ((30, 30, 30), (40, 40))), + ((60, 100), [[10, 20, 30], [50, 50]], ((10, 20, 30), (50, 50))), + ((10,), (10,), ((10,),)), + ], + ids=["regular", "regular-exact", "rectilinear", "single-chunk"], +) +def test_chunk_sizes( + shape: tuple[int, ...], chunks: Any, expected: tuple[tuple[int, ...], ...] +) -> None: + """chunk_sizes returns the per-dimension tuple of actual data sizes""" + grid = ChunkGrid.from_sizes(shape, chunks) + assert grid.chunk_sizes == expected + + +def test_array_read_chunk_sizes_regular() -> None: + """Regular array exposes correct read_chunk_sizes and write_chunk_sizes""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, shape=(100, 80), chunks=(30, 40), dtype="i4", zarr_format=3 + ) + assert arr.read_chunk_sizes == ((30, 30, 30, 10), (40, 40)) + assert arr.write_chunk_sizes == ((30, 30, 30, 10), (40, 40)) + + +def test_array_read_chunk_sizes_rectilinear() -> None: + """Rectilinear array exposes correct read_chunk_sizes and write_chunk_sizes""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, shape=(60, 100), chunks=[[10, 20, 30], [50, 50]], dtype="i4", zarr_format=3 + ) + assert arr.read_chunk_sizes == ((10, 20, 30), (50, 50)) + assert arr.write_chunk_sizes == ((10, 20, 30), (50, 50)) + + +def test_array_sharded_chunk_sizes() -> None: + """Sharded array read_chunk_sizes reflects inner chunks and write_chunk_sizes reflects shards""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(120, 80), + chunks=(60, 40), + shards=(120, 80), + dtype="i4", + zarr_format=3, + ) + assert arr.read_chunk_sizes == ((60, 60), (40, 40)) + assert arr.write_chunk_sizes == ((120,), (80,)) + + +# --------------------------------------------------------------------------- +# Info display test +# --------------------------------------------------------------------------- + + +def test_chunk_grid_repr_regular() -> None: + """ChunkGrid repr shows uniform chunk sizes and array shape for regular grids.""" + grid = ChunkGrid.from_sizes((100, 200), (10, 20)) + r = repr(grid) + assert r == "ChunkGrid(chunk_sizes=(10, 20), array_shape=(100, 200))" + + +def test_chunk_grid_repr_rectilinear() -> None: + """ChunkGrid repr shows per-chunk edge tuples for rectilinear dimensions.""" + grid = ChunkGrid.from_sizes((30,), ([10, 20],)) + r = repr(grid) + assert "(10, 20)" in r + assert "(30,)" in r + + +def test_info_display_rectilinear() -> None: + """Array.info should not crash for rectilinear grids.""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(30,), + chunks=[[10, 20]], + dtype="i4", + zarr_format=3, + ) + info = arr.info + text = repr(info) + assert "" in text + assert "Array" in text + + +# --------------------------------------------------------------------------- +# nchunks tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected"), + [ + ((30,), [[10, 20]], 2), + ((30, 40), [[10, 20], [15, 25]], 4), + ], + ids=["1d", "2d"], +) +def test_nchunks_rectilinear( + shape: tuple[int, ...], chunks: list[list[int]], expected: int +) -> None: + """Array.nchunks reports correct total chunk count for rectilinear arrays""" + store = MemoryStore() + a = zarr.create_array(store, shape=shape, chunks=chunks, dtype="int32") + assert a.nchunks == expected + + +# --------------------------------------------------------------------------- +# iter_chunk_regions test +# --------------------------------------------------------------------------- + + +def test_iter_chunk_regions_rectilinear() -> None: + """_iter_chunk_regions should work for rectilinear arrays.""" + from zarr.core.array import _iter_chunk_regions + + store = MemoryStore() + a = zarr.create_array(store, shape=(30,), chunks=[[10, 20]], dtype="int32") + regions = list(_iter_chunk_regions(a)) + assert len(regions) == 2 + assert regions[0] == (slice(0, 10, 1),) + assert regions[1] == (slice(10, 30, 1),) + + +# --------------------------------------------------------------------------- +# RectilinearChunkGridMetadata metadata object tests (already parametrized) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("json_input", "expected_chunk_shapes"), + [ + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [4, 8]}, + }, + (4, 8), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[1, 2, 3], [10, 20]]}, + }, + ((1, 2, 3), (10, 20)), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[4, 3]], [10, 20]]}, + }, + ((4, 4, 4), (10, 20)), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[1, 3], 3], [5]]}, + }, + ((1, 1, 1, 3), (5,)), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [4, [10, 20]]}, + }, + (4, (10, 20)), + ), + ], +) +def test_rectilinear_from_dict( + json_input: RectilinearChunkGridMetadataJSON, + expected_chunk_shapes: tuple[int | tuple[int, ...], ...], +) -> None: + """RectilinearChunkGridMetadata.from_dict correctly parses all spec forms.""" + grid = RectilinearChunkGridMetadata.from_dict(json_input) + assert grid.chunk_shapes == expected_chunk_shapes + + +@pytest.mark.parametrize( + ("chunk_shapes", "expected_json_shapes"), + [ + ((4, 8), [4, 8]), + (((4,), (8,)), [[4], [8]]), + (((10, 20), (5, 5)), [[10, 20], [[5, 2]]]), + (((4, 4, 4), (10, 20)), [[[4, 3]], [10, 20]]), + ((4, (10, 20)), [4, [10, 20]]), + ], +) +def test_rectilinear_to_dict( + chunk_shapes: tuple[int | tuple[int, ...], ...], + expected_json_shapes: list[Any], +) -> None: + """RectilinearChunkGridMetadata.to_dict serializes back to spec-compliant JSON.""" + grid = RectilinearChunkGridMetadata(chunk_shapes=chunk_shapes) + result = grid.to_dict() + assert result["name"] == "rectilinear" + assert result["configuration"]["kind"] == "inline" + assert list(result["configuration"]["chunk_shapes"]) == expected_json_shapes + + +@pytest.mark.parametrize( + "json_input", + [ + {"name": "rectilinear", "configuration": {"kind": "inline", "chunk_shapes": [4, 8]}}, + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[1, 2, 3], [10, 20]]}, + }, + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[4, 3]], [[5, 2]]]}, + }, + ], +) +def test_rectilinear_roundtrip(json_input: RectilinearChunkGridMetadataJSON) -> None: + """from_dict -> to_dict -> from_dict produces the same grid.""" + grid1 = RectilinearChunkGridMetadata.from_dict(json_input) + grid2 = RectilinearChunkGridMetadata.from_dict(grid1.to_dict()) + assert grid1.chunk_shapes == grid2.chunk_shapes + + +# --------------------------------------------------------------------------- +# Hypothesis property tests +# --------------------------------------------------------------------------- + + +pytest.importorskip("hypothesis") + +import hypothesis.strategies as st +from hypothesis import event, given, settings + + +@st.composite +def rectilinear_chunks_st(draw: st.DrawFn, *, shape: tuple[int, ...]) -> list[list[int]]: + """Generate valid rectilinear chunk shapes for a given array shape.""" + chunk_shapes: list[list[int]] = [] + for size in shape: + assert size > 0 + max_chunks = min(size, 10) + nchunks = draw(st.integers(min_value=1, max_value=max_chunks)) + if nchunks == 1: + chunk_shapes.append([size]) + else: + dividers = sorted( + draw( + st.lists( + st.integers(min_value=1, max_value=size - 1), + min_size=nchunks - 1, + max_size=nchunks - 1, + unique=True, + ) + ) + ) + chunk_shapes.append( + [a - b for a, b in zip(dividers + [size], [0] + dividers, strict=False)] + ) + return chunk_shapes + + +@st.composite +def rectilinear_arrays_st(draw: st.DrawFn) -> tuple[zarr.Array[Any], np.ndarray[Any, Any]]: + """Generate a rectilinear zarr array with random data, shape, and chunks.""" + from zarr.storage import MemoryStore + + ndim = draw(st.integers(min_value=1, max_value=3)) + shape = draw(st.tuples(*[st.integers(min_value=2, max_value=20) for _ in range(ndim)])) + chunk_shapes = draw(rectilinear_chunks_st(shape=shape)) + event(f"ndim={ndim}, shape={shape}") + + a = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + store = MemoryStore() + z = zarr.create_array(store=store, shape=shape, chunks=chunk_shapes, dtype="int32") + z[:] = a + return z, a + + +@settings(deadline=None, max_examples=50) +@given(data=st.data()) +def test_property_block_indexing_rectilinear(data: st.DataObject) -> None: + """Property test: block indexing on rectilinear arrays matches numpy.""" + z, a = data.draw(rectilinear_arrays_st()) + grid = ChunkGrid.from_metadata(z.metadata) + + for dim in range(a.ndim): + dim_grid = grid._dimensions[dim] + block_ix = data.draw(st.integers(min_value=0, max_value=dim_grid.nchunks - 1)) + sel = [slice(None)] * a.ndim + start = dim_grid.chunk_offset(block_ix) + stop = start + dim_grid.data_size(block_ix) + sel[dim] = slice(start, stop) + block_sel: list[slice | int] = [slice(None)] * a.ndim + block_sel[dim] = block_ix + np.testing.assert_array_equal( + z.blocks[tuple(block_sel)], + a[tuple(sel)], + err_msg=f"dim={dim}, block={block_ix}", + ) diff --git a/tests/test_v2.py b/tests/test_v2.py index cb990f6159..798687438b 100644 --- a/tests/test_v2.py +++ b/tests/test_v2.py @@ -14,8 +14,9 @@ from zarr import config from zarr.abc.store import Store from zarr.core.buffer.core import default_buffer_prototype -from zarr.core.dtype import FixedLengthUTF32, Structured, VariableLengthUTF8 +from zarr.core.dtype import FixedLengthUTF32, VariableLengthUTF8 from zarr.core.dtype.npy.bytes import NullTerminatedBytes +from zarr.core.dtype.npy.structured import Struct from zarr.core.dtype.wrapper import ZDType from zarr.core.group import Group from zarr.core.sync import sync @@ -283,7 +284,7 @@ def test_structured_dtype_roundtrip(fill_value: float | bytes, tmp_path: Path) - def test_parse_structured_fill_value_valid( fill_value: Any, dtype: np.dtype[Any], expected_result: Any ) -> None: - zdtype = Structured.from_native_dtype(dtype) + zdtype = Struct.from_native_dtype(dtype) result = zdtype.cast_scalar(fill_value) assert result.dtype == expected_result.dtype assert result == expected_result @@ -293,7 +294,7 @@ def test_parse_structured_fill_value_valid( @pytest.mark.parametrize("fill_value", [None, b"x"], ids=["no_fill", "fill"]) -def test_other_dtype_roundtrip(fill_value: None | bytes, tmp_path: Path) -> None: +def test_other_dtype_roundtrip(fill_value: bytes | None, tmp_path: Path) -> None: a = np.array([b"a\0\0", b"bb", b"ccc"], dtype="V7") array_path = tmp_path / "data.zarr" za = zarr.create( diff --git a/tests/test_version_derivation.py b/tests/test_version_derivation.py new file mode 100644 index 0000000000..b9e3e90551 --- /dev/null +++ b/tests/test_version_derivation.py @@ -0,0 +1,34 @@ +"""Sanity check that ``zarr.__version__`` looks like a v3-or-newer release. + +Background: zarr-python derives its version from ``git describe`` via +hatch-vcs. The repo also publishes a separate ``zarr-metadata`` subpackage +that uses ``zarr_metadata-v*`` tags. Without the ``--match v*`` filter in +``[tool.hatch] version.raw-options.git_describe_command``, ``git describe`` +walks back to those subpackage tags and reports a version like ``0.2.0`` for +a from-source build of zarr-python itself — see +https://github.com/zarr-developers/zarr-python/pull/3994. + +This test catches that class of regression: anything that makes zarr-python +report a version lower than the v3 release line. When 4.0 is released, +bump the floor; that's a deliberate, one-line edit at a planned boundary. +""" + +from __future__ import annotations + +from packaging.version import Version + +import zarr + + +def test_version_is_v3_or_newer() -> None: + # Use packaging.Version so we transparently handle hatch-vcs dev suffixes + # like "3.2.2.dev30+gdc5e1825" that appear on any source build past the + # latest v* tag — Version.major returns 3 for that string. + parsed = Version(zarr.__version__) + assert parsed.major >= 3, ( + f"zarr.__version__={zarr.__version__!r} is not on the v3 (or newer) " + f"release line. If this fires on a from-source build, check that " + f"[tool.hatch] version.raw-options.git_describe_command in " + f"pyproject.toml still includes ``--match v*`` so the " + f"``zarr_metadata-v*`` subpackage tags are excluded. See PR #3994." + ) diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000000..327d3e0822 --- /dev/null +++ b/uv.lock @@ -0,0 +1,3756 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" +resolution-markers = [ + "python_full_version >= '3.15'", + "python_full_version < '3.15'", +] + +[[package]] +name = "aiobotocore" +version = "3.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohttp" }, + { name = "aioitertools" }, + { name = "botocore" }, + { name = "jmespath" }, + { name = "multidict" }, + { name = "python-dateutil" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e7/75/42cce839c2ec263ff74b10b650fe36b066fbb124cbee6f247eac0983e1ab/aiobotocore-3.7.0.tar.gz", hash = "sha256:c64d871ed5491a6571948dd48eabd185b46c6c23b64e3afd0c059fc7593ada30", size = 127054, upload-time = "2026-05-09T10:02:52.332Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/5f/85535dfb3cfd6442d66d1df1694062c5d6df02f895329e7e120b2a3d2b8b/aiobotocore-3.7.0-py3-none-any.whl", hash = "sha256:680bde7c64679a821a9312641b759d9497f790ba8b2e88c6959e6273ee765b8e", size = 89539, upload-time = "2026-05-09T10:02:50.389Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/26/30/f84a107a9c4331c14b2b586036f40965c128aa4fee4dda5d3d51cb14ad54/aiohappyeyeballs-2.6.1.tar.gz", hash = "sha256:c3f9d0113123803ccadfdf3f0faa505bc78e6a72d1cc4806cbd719826e943558", size = 22760, upload-time = "2025-03-12T01:42:48.764Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0f/15/5bf3b99495fb160b63f95972b81750f18f7f4e02ad051373b669d17d44f2/aiohappyeyeballs-2.6.1-py3-none-any.whl", hash = "sha256:f349ba8f4b75cb25c99c5c2d84e997e485204d2902a9597802b0371f09331fb8", size = 15265, upload-time = "2025-03-12T01:42:47.083Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/d9/22ce5786ac0c1653ae8b6c23bded02c1686d11f0dbb45b31ce128e0df985/aiohttp-3.14.3.tar.gz", hash = "sha256:9491196535a88924a60afd5b5f434b5b203b6cc616250878dbdb223a8f7844bc", size = 7971213, upload-time = "2026-07-23T01:57:27.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/d4/eb96299230e20acf2efae207cb8d69051f1f68e357e5ea5e479bf6fb097a/aiohttp-3.14.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:39aded8c7f3b935b54aab1d8d73c70ec0ee2d3ec3b943e0e86611bc150ba47f5", size = 754690, upload-time = "2026-07-23T01:53:47.332Z" }, + { url = "https://files.pythonhosted.org/packages/88/11/e7a70a209eb9a067c0d3212b518a0134e3484f5178c7533878b6b514d469/aiohttp-3.14.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5bcb6ff3fdab1258a192679ff1a05d44f59626430aa05cd1a9d2447423599228", size = 509484, upload-time = "2026-07-23T01:53:51.159Z" }, + { url = "https://files.pythonhosted.org/packages/30/07/4bbc222cc8dbe31d4c3e8a5baad2286e4d42026ac0c570027b89afce6344/aiohttp-3.14.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:617105e2c3018ee38d0c8ce5ee3c84f621a6d8b9f723202aacaff28449ca91ee", size = 511949, upload-time = "2026-07-23T01:53:55.083Z" }, + { url = "https://files.pythonhosted.org/packages/54/b9/42e74c46b7b7c794b995bbc1f573fb48950c38b19d8600c62a6804ee2d67/aiohttp-3.14.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f631fe87a6f30df5fbe6d79640b25e4cffb38c31c7fb6f10871517b84b0f8c1a", size = 1765282, upload-time = "2026-07-23T01:53:59.662Z" }, + { url = "https://files.pythonhosted.org/packages/6b/ed/62bc4d74363ad346d518e0720363a949f63e2e23439a79eb5813d4d29bb3/aiohttp-3.14.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a94dbaae5ae27bd849c93570669bff91e0510f33a80805738e3de72a7be0447b", size = 1741511, upload-time = "2026-07-23T01:54:04.063Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9f/181e8a8bc79e47d13c7fc4540bd7a3b729d9505609c61f392a8dd2fbfe55/aiohttp-3.14.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8f2f1c4c032c7cedd7d8da6f54c97b70266c6570c3108d3fdffee7188bb70529", size = 1810680, upload-time = "2026-07-23T01:54:09.882Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9a/dec94d6ad694552fe3424e3f1928d7a606a5d9d9433a04e7ecdd9d38ae7f/aiohttp-3.14.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ea05e1f97ceea523942d9b2a7d7c0359d781d683d6b043f5943a602b14da4787", size = 1905646, upload-time = "2026-07-23T01:54:13.475Z" }, + { url = "https://files.pythonhosted.org/packages/52/b7/7cd31f29d6055bd711ae6e669367fba6f5ae9de463910a793e30556a8db7/aiohttp-3.14.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:543906c127fb1d929b95076db19b83fa2d46751006ff1e23b093aa5ac4d8db42", size = 1792122, upload-time = "2026-07-23T01:54:15.752Z" }, + { url = "https://files.pythonhosted.org/packages/66/73/10b1ef93afa61f4963c746257b70ced619cf31a4798671de5fdb2608501d/aiohttp-3.14.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0a5ff2dfbb9ce645fa5b8ef3e02c6c0b9cc3f6030ff863d0c51fffc50cb5541b", size = 1591127, upload-time = "2026-07-23T01:54:19.489Z" }, + { url = "https://files.pythonhosted.org/packages/49/ed/3b203fa6de1b338c14acdc06bf6ca9b043b7944f005966958c2ced932cde/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:041badb8f84396357c4d3ad26de6afd7a32b112f43d3c63045c0c8278cfd2043", size = 1725210, upload-time = "2026-07-23T01:54:24.129Z" }, + { url = "https://files.pythonhosted.org/packages/28/b7/1c2aab8c706436dcc28598452488ac9cd7c409da815237c28c27d58993e6/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:530125ee1163c4219af35dc3aa1206e541e7b31b6efc1a3f93b70a136f65d427", size = 1764848, upload-time = "2026-07-23T01:54:27.973Z" }, + { url = "https://files.pythonhosted.org/packages/54/50/94c28f08b131c4bf10984ea2c7a536c9920608bb2d6e7f95642c30cc87b7/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c8653fd547c93a61aadc612007790f5555cdd18946fa48cf45e26d8ea4ea473d", size = 1777102, upload-time = "2026-07-23T01:54:31.775Z" }, + { url = "https://files.pythonhosted.org/packages/13/d4/e7d09ba7d345fb2d74440fd2fa033c5e079fac05552927705986f41a364f/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:89176250f686cb9853c0fb7ead90e639e915b84a6f43eedc2a4e7ec21f1037f0", size = 1580205, upload-time = "2026-07-23T01:54:34.518Z" }, + { url = "https://files.pythonhosted.org/packages/a3/84/072a91d68e1e1eb587985b54baab94221277f877e8ef274fc213a0ceae28/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3a26434dafe408229ff3403458ca58de24fb51936504decac49ce6755f77e59d", size = 1797219, upload-time = "2026-07-23T01:54:36.995Z" }, + { url = "https://files.pythonhosted.org/packages/e0/eb/aad34e897e668424d6e995da5dff8a4a09af93363d3392488772957a63aa/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d1558173930a5a8d3069cee5c92fc91c87c4dbcb099debbb3622053717145a19", size = 1768629, upload-time = "2026-07-23T01:54:40.103Z" }, + { url = "https://files.pythonhosted.org/packages/b6/2b/6bb88ddba0fecd9122aa3ebcad25996cf6c083a4a7040dbb3a4f97972af6/aiohttp-3.14.3-cp312-cp312-win32.whl", hash = "sha256:16100ad3ab8d649fdfbee87602d9d2dcdca9df0b9eda8a1b5fdc0d41f96da559", size = 451481, upload-time = "2026-07-23T01:54:42.547Z" }, + { url = "https://files.pythonhosted.org/packages/76/9b/f2f8f108da17ecef2cc3efc424e8b7ad3782b1a8360f7b8eae8ced84f6ea/aiohttp-3.14.3-cp312-cp312-win_amd64.whl", hash = "sha256:33a2d7c28d33797a2e99923dffa63f83d908a19b6bf26cfe80fa790aa5e1a75a", size = 476845, upload-time = "2026-07-23T01:54:44.853Z" }, + { url = "https://files.pythonhosted.org/packages/3e/44/28dac80a8941b604f4da10ce21097614ca1bf905ce93dca28d8d7de9c1e7/aiohttp-3.14.3-cp312-cp312-win_arm64.whl", hash = "sha256:362a3fd481769cac1a824514bcd86fda51c65e8fe6e051099e008fddde6db17c", size = 448050, upload-time = "2026-07-23T01:54:47.087Z" }, + { url = "https://files.pythonhosted.org/packages/57/be/5afd201cc0ab139029aadb75392efe85a293403d9dd3a3226161c21ce00c/aiohttp-3.14.3-cp313-cp313-android_21_arm64_v8a.whl", hash = "sha256:2e9878ae68e4a5f1c0abe4dd497dbc3d51946f5837b56759e2a02e78fa90ef86", size = 506269, upload-time = "2026-07-23T01:54:49.075Z" }, + { url = "https://files.pythonhosted.org/packages/22/09/dec8189d62b45ade009f6792a2264b942a90cb88aeaf181239933cd72c3c/aiohttp-3.14.3-cp313-cp313-android_21_x86_64.whl", hash = "sha256:f3d2669fe7dec7fc359ecdb5984b29b50d85d5d00f8c1cb61de4f4a24ee42627", size = 515166, upload-time = "2026-07-23T01:54:51.894Z" }, + { url = "https://files.pythonhosted.org/packages/28/24/2854869d29ed8a8b19d74f9ec6629515f7e04d02dd329d9d179201e58e47/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:cc7cb243a68167172f48c1fd43cee91ec4b1d40cefd190edd43369d1a6bc9c82", size = 486263, upload-time = "2026-07-23T01:54:54.223Z" }, + { url = "https://files.pythonhosted.org/packages/d4/dd/57187c8be2a35aea65eaee3bd2c3dcbbcf0204f5106c89637e3610380cd1/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:78253b573e6ffab5028924fc98bc281aae05445969982a10864bc360dea2016c", size = 492299, upload-time = "2026-07-23T01:54:56.236Z" }, + { url = "https://files.pythonhosted.org/packages/b9/11/06ae6ed8f0d414edf4068861e233d8fe23ee699bfd4b3ceb8663db948a62/aiohttp-3.14.3-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7041d52c3a7fa20c9e8c182b534704abb19502c8bdcbde7ab23bfda6f642394f", size = 502235, upload-time = "2026-07-23T01:54:58.377Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a3/559639c34a345d2cf7c52dff6838119f2eaf29eb508227b5b83f573af813/aiohttp-3.14.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ac74facc01463f138b0da5580329cfcc82818dea5656e83ddcd11268fc12ff80", size = 750883, upload-time = "2026-07-23T01:55:00.65Z" }, + { url = "https://files.pythonhosted.org/packages/91/cd/41e131f13afd1e7b0172a9d9eda085ef90eb8439f41f0d279db81ed3ae60/aiohttp-3.14.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d6218d92e450824e9b4881f44e8c09f1853b490f9a64130801024a4793b1b3b0", size = 508473, upload-time = "2026-07-23T01:55:02.945Z" }, + { url = "https://files.pythonhosted.org/packages/bc/6b/e7f13410d391c6e55b4c007a8de024355389d7d459e3d64c42b2d33617e5/aiohttp-3.14.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:11fb37ef075669eee52ab1928fbf6e1741fada40409fa309ebde9607a962aebf", size = 509190, upload-time = "2026-07-23T01:55:05.173Z" }, + { url = "https://files.pythonhosted.org/packages/97/21/6464573e53d69672cc1eada3e5c5cb2d2efa82701e8305a0f2047a576967/aiohttp-3.14.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55bdcc472aafe2de4a253045cc128007a64f1e0264fb675791e132ea5edaa3bd", size = 1761478, upload-time = "2026-07-23T01:55:07.383Z" }, + { url = "https://files.pythonhosted.org/packages/1a/81/d217043a4c17fbce360905e3b2bdd20139ebc9a2de836d035d179c4da006/aiohttp-3.14.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c39846c3aad97a8530c89d7a3869a8f8e9e3762c6ac0504481e5c80948f7e807", size = 1735092, upload-time = "2026-07-23T01:55:09.803Z" }, + { url = "https://files.pythonhosted.org/packages/a1/66/e13a02d0eeb1a9a502402a977abb4e4abff9fe4051c26f80558c57a7c975/aiohttp-3.14.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5895ef58c4620afe02fa16044f023dc4dafec08158f9d08874a46a7dbc0341b8", size = 1800546, upload-time = "2026-07-23T01:55:12.012Z" }, + { url = "https://files.pythonhosted.org/packages/26/5e/57d42fca1d18cb5acc1cad945d017fabc5d6ae71d8a08ad66be8dc3ee544/aiohttp-3.14.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa9467a8113aa69d3d7c55a70ef0b7c636010a40993f3df9d9d0d73b3eb7ef24", size = 1895250, upload-time = "2026-07-23T01:55:14.357Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1c/7da8d08e74d56f00070822f9638ff3f1c563f8ad87d1efa996c87bfc8644/aiohttp-3.14.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7d2deec16eeedf55f2c7cf75b521ea3856a5177e123844f8fd0f114ce252cb5", size = 1789289, upload-time = "2026-07-23T01:55:16.668Z" }, + { url = "https://files.pythonhosted.org/packages/cd/0f/cf16bcf56896981c1a0319f5d5db9337994b5165730c48a8fa07e9b34be6/aiohttp-3.14.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dd54d0e8717de95939766febac482ac0474d8ac3b048115f9f2b1d23a16e7db4", size = 1586706, upload-time = "2026-07-23T01:55:18.913Z" }, + { url = "https://files.pythonhosted.org/packages/fe/6f/76eac12a7f2480e1e304f842efdb07db33256b0d9165b866b6ef0806c202/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df82f3787c940c94986b34222d59c9e38843fba85139f36e85255a82ad5355a9", size = 1724652, upload-time = "2026-07-23T01:55:21.296Z" }, + { url = "https://files.pythonhosted.org/packages/39/b6/19c8c592baeeb94b75f966547d40c02ac7590902306ec5863d5c027cf506/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:42a67efc36300d052fb4508a53e8b6901b9284b599ae63945c377569c5fcc1e1", size = 1756239, upload-time = "2026-07-23T01:55:23.705Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c9/4e9383150296f97f873b680c4de8fb2cd88608fb9f48c79edcb111611abc/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7a75aa63cbf9b21cfaf60dc2657e19df2c2867d91707d653fee171ffeedd1371", size = 1769161, upload-time = "2026-07-23T01:55:26.082Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1e/147bdc6cc5de5f3ab011be8bf5d6e786633249f22c20bae06f85e45f5387/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e92eb8acc45eb6a9f4935071a77edf5b85cc6f8dfad5cd99e97653c26593cdde", size = 1578759, upload-time = "2026-07-23T01:55:28.846Z" }, + { url = "https://files.pythonhosted.org/packages/fd/31/78388a9d6040ece2e11df62ea229a822cf5e52d238374b220ae9975b2623/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b014a6ed7cf912e787149fdc529166d3ceabac23f26efeea3158c9aba2354e7e", size = 1792025, upload-time = "2026-07-23T01:55:31.457Z" }, + { url = "https://files.pythonhosted.org/packages/03/51/a3d29fdf2c25d796746af8ad6fe56a45d6256c38b0a8a2ed752e1160b3a2/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3d4f72af88ac2474bb5bca640030320e3d38a0163a1d7533500e87be458eef71", size = 1768477, upload-time = "2026-07-23T01:55:33.87Z" }, + { url = "https://files.pythonhosted.org/packages/29/a6/442e18b5afeade534d877a2dc3c3e392aff8d49787890b0cf84790410267/aiohttp-3.14.3-cp313-cp313-win32.whl", hash = "sha256:5f08ec777f35ee70720233b8b9811d3bb5d728137f30ac91b7457709c3261ac0", size = 451069, upload-time = "2026-07-23T01:55:36.121Z" }, + { url = "https://files.pythonhosted.org/packages/9d/69/3d876ac02659f271cf7f6769f14a8e3de5b6e888ed8b5a7e998086a4cec8/aiohttp-3.14.3-cp313-cp313-win_amd64.whl", hash = "sha256:dff9461ec275f22135650d5ba4b4931a11f3958df7dfbb8db630000d4dee0883", size = 476518, upload-time = "2026-07-23T01:55:38.303Z" }, + { url = "https://files.pythonhosted.org/packages/b2/0e/50d6e6471cd31edce8b282bdec59375a3a69124d8a989a0b1313355cae52/aiohttp-3.14.3-cp313-cp313-win_arm64.whl", hash = "sha256:ddcac3c6b382e81f1dd0499199d4136b877beb4cb5ef770bbbfba56c4b8f55d2", size = 447676, upload-time = "2026-07-23T01:55:40.451Z" }, + { url = "https://files.pythonhosted.org/packages/c8/20/887fdcf832326571b370ffc347b3e70abe101096f3720126aac161b1d872/aiohttp-3.14.3-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:49f7325beb0f85ef4aef5f48f490269575f83e6e2acad00a1d80b807eb027062", size = 509067, upload-time = "2026-07-23T01:55:42.618Z" }, + { url = "https://files.pythonhosted.org/packages/ad/a3/92cec936f78cc4bf0fa5554ebe593b73459d94e3c62303e1902a4cccb6f7/aiohttp-3.14.3-cp314-cp314-android_24_x86_64.whl", hash = "sha256:e3be98a7c30b8c25d573dafba7171d66dfb05ee6a9070fc46535464ff97700a6", size = 514774, upload-time = "2026-07-23T01:55:44.937Z" }, + { url = "https://files.pythonhosted.org/packages/29/ba/2a0c38df3fc557620b6a5acd98364af050053b6285b4dc7ee74100c63c18/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:614c61d478b83953e261d02bb2df750f17227cd33ef8002945bf5aebbde21919", size = 488134, upload-time = "2026-07-23T01:55:47.135Z" }, + { url = "https://files.pythonhosted.org/packages/48/d6/d51b7d4bf309af3693940d8ffd2b9ed0b682434ef85959b7c9c137f60cf8/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:1caa7b0d05f3e3a36f87788c59e970a7ee1cefcfcbb924a9f138c4a6551c9cb7", size = 494201, upload-time = "2026-07-23T01:55:49.451Z" }, + { url = "https://files.pythonhosted.org/packages/3f/5a/8f624384e5f1efabb5229b94157eb966b021e97bdb188c62860c2ae243c2/aiohttp-3.14.3-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:dfa68deb2a443bdaa3ea5297b0699c1464f08aef3812b486d1348eee61b07dc0", size = 502766, upload-time = "2026-07-23T01:55:51.656Z" }, + { url = "https://files.pythonhosted.org/packages/a6/26/4ff0164370deec18fb19254ee4ab10b7a73304ac0c860b13f5f84663759b/aiohttp-3.14.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:e72ee89e28d907a18f46959b4eb0bb06701cc7f8cf4366e00029e2ccfaaf5924", size = 756557, upload-time = "2026-07-23T01:55:53.964Z" }, + { url = "https://files.pythonhosted.org/packages/97/a3/7056b86dc0d9ec709ea9777eae3b0161428f943372f8b98c01c11593b682/aiohttp-3.14.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ad4c8b7488d745d2ca4838ebd8ae5ba9b56341d30b1da43640e4ce87f9f49646", size = 510168, upload-time = "2026-07-23T01:55:56.22Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/0357a015892fd68058bf2d39d3fd1958e459b997a7db30aaa6aaa434ae96/aiohttp-3.14.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:db332af25642007330fca8be5c4d194caf2bea7a7fc84415aff3497af5dfee6b", size = 512957, upload-time = "2026-07-23T01:55:58.437Z" }, + { url = "https://files.pythonhosted.org/packages/47/d1/8aba53f15ccb2238405f5e9d30e2a8ca44f93878c26e7165ade00d374b1c/aiohttp-3.14.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:25bd2708db6bdf6a6630dd37bdcdfcb47c4434d22ac69c64665b802910140b30", size = 1750149, upload-time = "2026-07-23T01:56:00.856Z" }, + { url = "https://files.pythonhosted.org/packages/49/bd/40c3fee327529284375c6701cbb0fa4600cc2e8432af1378f897e2ef7d3a/aiohttp-3.14.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:cef89a58e628c4efcac3275c2d68083f82426dcdc89c1492a6f654f9f7ea6ab9", size = 1707685, upload-time = "2026-07-23T01:56:03.371Z" }, + { url = "https://files.pythonhosted.org/packages/2a/a3/ca0cc6724cca8114b05694abd916060758c79894c3aa5b012cdadc1bc28e/aiohttp-3.14.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c23ec8ee9d5ab2f5421f9c7fffce208435607af27fd46d4a44e031954352838f", size = 1803911, upload-time = "2026-07-23T01:56:05.817Z" }, + { url = "https://files.pythonhosted.org/packages/95/b5/85b099c299c3ffd38ad9b3e43694c8a346934e4a30c88c4fd5a841234f77/aiohttp-3.14.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e2667f0bbe7eb6c74eae5e9691441ad186e5845ca3cff63230fc09c4e7514f5d", size = 1876929, upload-time = "2026-07-23T01:56:08.413Z" }, + { url = "https://files.pythonhosted.org/packages/d5/b7/1da684a04175473fa4cddbf9a2f572e79514c3fd27a74597f43057d4f3da/aiohttp-3.14.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18cb43369747b2ae007bd2655fb8e63a099c2ff1d207962943636dac989b3147", size = 1761112, upload-time = "2026-07-23T01:56:10.918Z" }, + { url = "https://files.pythonhosted.org/packages/d1/16/bc4b55e3e5cb175fd69c53c90d60d2f47797cb343da5106e23863dc4dba4/aiohttp-3.14.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d77640cc618c1d99fc4f8589c0f24a730adfa54eb1e57ef7bf0c8dfb78da898c", size = 1583500, upload-time = "2026-07-23T01:56:13.613Z" }, + { url = "https://files.pythonhosted.org/packages/2a/e8/13a9d957a1ee40837f46aa30f0f4c657e673ad86a2e6362a9f9be20d26d9/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:53e5179d8abb5710f8e83ba207c41c8d1261fcffd4616500e15ca2b7a33be10a", size = 1713940, upload-time = "2026-07-23T01:56:15.969Z" }, + { url = "https://files.pythonhosted.org/packages/38/05/d33c680c1bcf1c7e130f9cbfc1fc02fe8bb0c4af2a94a53dd5fb56131e5c/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:cd817772b2fcf2b8c0905795318485f9ec16eae60b29feb7f4c77085311637f0", size = 1724413, upload-time = "2026-07-23T01:56:18.591Z" }, + { url = "https://files.pythonhosted.org/packages/85/1d/af798d306f7a74b6a632dbcabcf62a4c91391b7582d2a8c6d7712e2cc54e/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:4e3ac92d90e92773b2362d506068e9a948192bd553e743c5b2429e28527c8661", size = 1770748, upload-time = "2026-07-23T01:56:21.074Z" }, + { url = "https://files.pythonhosted.org/packages/a8/92/ad720d472556a995049206867765e9410969684f86ee09423ff9969044c1/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:3f42e9b78301f11c8f861746175d8b9c1ccef713fcad9eab396e2f6db8ed4a22", size = 1577564, upload-time = "2026-07-23T01:56:23.475Z" }, + { url = "https://files.pythonhosted.org/packages/60/ad/0ed7586cbef7a884e23a752fa2bb987a122e6a5dd50dab109258d0a95193/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:9d9edccfe496b476db5f398d97b865e9a6752bcf8aec4eef8390ce20fb64bb41", size = 1782080, upload-time = "2026-07-23T01:56:25.994Z" }, + { url = "https://files.pythonhosted.org/packages/97/ea/dbaed0d73e8a69aad653b045dab451c67c2454bb731a37b45a86593e9422/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:1c5ec8fb1bcc31a8466f74aaf26c345d5c386fa4bd08a3f0eb9c7a4a3fe8b5bf", size = 1745813, upload-time = "2026-07-23T01:56:28.604Z" }, + { url = "https://files.pythonhosted.org/packages/81/1b/6893d4bc57e434fc93a6c9217c637d967a0b651d989f6e3265179375754a/aiohttp-3.14.3-cp314-cp314-win32.whl", hash = "sha256:38901a84da3ce22249f6e860bf8f90d141bcab7da090cc398f8bb58c0e44b7da", size = 455872, upload-time = "2026-07-23T01:56:31.031Z" }, + { url = "https://files.pythonhosted.org/packages/f5/8b/c7baa1ba1eda4db6989baefe5de6d99834921b84ebd7918624febcb9f290/aiohttp-3.14.3-cp314-cp314-win_amd64.whl", hash = "sha256:8b3b60de05f3dcb6f6a00f818bb2ec781cee4de0645f59ccaf99b1d1823b6100", size = 481030, upload-time = "2026-07-23T01:56:33.365Z" }, + { url = "https://files.pythonhosted.org/packages/22/8c/c29d067df825a2df88ca432db848aa2fe8199598359cc06c12b09320cac9/aiohttp-3.14.3-cp314-cp314-win_arm64.whl", hash = "sha256:1576145bdceeb92382d899751e12743a3a5b8e460a841e3e50543859e54864dc", size = 453669, upload-time = "2026-07-23T01:56:35.731Z" }, + { url = "https://files.pythonhosted.org/packages/6a/a4/9c033beb355d39b6147980597ec9645e4729243f686ee4dc73945de72030/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:8800c996b01c2772a783e3e46f3e1abd5823029adca0df54231960de9bfefa5b", size = 791403, upload-time = "2026-07-23T01:56:37.972Z" }, + { url = "https://files.pythonhosted.org/packages/80/ca/87c32a0a7704583cfc49660bd817889bae5b830bf53b5dcb4e92145ac2da/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ebe8e504f058fe91223351cecd2d9d6946c9d241bb0250d898ffbdf584cc72b0", size = 526413, upload-time = "2026-07-23T01:56:40.523Z" }, + { url = "https://files.pythonhosted.org/packages/9e/d8/8ec0e471248c500acdce2be3f46db8fb62b5eb60efef072529cc85ee1d26/aiohttp-3.14.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:30402d03a7c0ff52bce290b57e564e9079fd9d0cb545c8aba73f86a103162d2e", size = 532135, upload-time = "2026-07-23T01:56:42.876Z" }, + { url = "https://files.pythonhosted.org/packages/fe/45/f8919fd936e8b79fcd9bda7b6d8e62613462a713f4f17987fd7c34399142/aiohttp-3.14.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9fc7b5bfec6573f3ae844f457fdde5adeb713f8b8e4a81ad64fc207b49383716", size = 1922742, upload-time = "2026-07-23T01:56:45.528Z" }, + { url = "https://files.pythonhosted.org/packages/f6/ec/9ca76b28a27525b0cc53e20842e0228b022f301ce1f436b7d814b4aaf2df/aiohttp-3.14.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8a5fd34f7f7410d1730d5c2ba873cacb2eed3fede366feb268a70ba22581ed8f", size = 1787371, upload-time = "2026-07-23T01:56:48.045Z" }, + { url = "https://files.pythonhosted.org/packages/b1/04/6acdbf17315f7b55f1937e3387acb89a3cddeb4995689553d064af8e92ab/aiohttp-3.14.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:270d3dace9ca2f10f0da5d8ebe519b7a310fc6112ed916e32df5866df0888553", size = 1912623, upload-time = "2026-07-23T01:56:50.605Z" }, + { url = "https://files.pythonhosted.org/packages/86/e6/438b0c79ca6f45eb9fd9817dd4c01a91919a38c0de5ee9e05e2b4dc0ece7/aiohttp-3.14.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3ae5b3a59436d089b5395d910121a390feed4d00578eb95a0fd1a329fe963100", size = 2005515, upload-time = "2026-07-23T01:56:53.153Z" }, + { url = "https://files.pythonhosted.org/packages/bb/6b/62cbd6577758699525f5c712d1ddef57d9875fbab0ae8d5f5a202fd598f8/aiohttp-3.14.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2498f0fe69ead802f9675beca44a7c21c62fdaa4ec5145ea1c3ad6edbee29f85", size = 1879906, upload-time = "2026-07-23T01:56:55.818Z" }, + { url = "https://files.pythonhosted.org/packages/00/95/18bcbf830a21dc3aae24d8f6b6feaf3db1d2090242d00a7868db2ffb0b67/aiohttp-3.14.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a0dc483c00da8b673abbb367eb6f8d8f4bcec30eb58529ea13cb42e7fd2dfa33", size = 1675849, upload-time = "2026-07-23T01:56:58.861Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/47f4968659c5e23606c3790c80fc624e691c153d036148449ee84d31b287/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c7d3a97c678d34fc5b59da671ee9cd630096ddc643e7b5a30d54a2a6f3574d3f", size = 1843496, upload-time = "2026-07-23T01:57:01.591Z" }, + { url = "https://files.pythonhosted.org/packages/64/af/38c33c4dd82fddcb4e56c4653b6f1072a8edbc6b7fa15809f14932c41e2d/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:f8fb78a83c9e5f741ca3a68cfb455c1f5bb83b4e7249a3848b3cd78d0a8563b0", size = 1827746, upload-time = "2026-07-23T01:57:05.131Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9d/0537cda4885ac8f5b7053d164dd06312f4c483a4edcb8ee5b8aaf2a989bf/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:74ab5b6a9fb13e873e5a90946588baecaf488745e1db1a4a5c433f971f035098", size = 1853810, upload-time = "2026-07-23T01:57:08.043Z" }, + { url = "https://files.pythonhosted.org/packages/19/fe/26f9c5e6458385aa86497836b0dea6fb2f027827d63f37c7856cce9286ee/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:bd52f811e65f6fb634b1047159657c98f52b407f8efec907bcfc09da9a4c0a25", size = 1668895, upload-time = "2026-07-23T01:57:10.837Z" }, + { url = "https://files.pythonhosted.org/packages/ec/4c/618b1db9b9ba079b8875d2cdf78e7c4a3bf72903bd5850fee7dd9544600a/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:f0f177d1b195b9e06376cfd7d308d8a1b920909a609d03ac82a8c73bbb16d3b9", size = 1883833, upload-time = "2026-07-23T01:57:13.672Z" }, + { url = "https://files.pythonhosted.org/packages/94/c6/bd959bd1e4771f9fd944e9e436224c48c77b018b73b519b5aad346335bcc/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:498c6c623134f8e09a3c4e60bcd607a0b4590dd7dbf08dd40851b27cbb520ccb", size = 1844251, upload-time = "2026-07-23T01:57:16.593Z" }, + { url = "https://files.pythonhosted.org/packages/5e/19/08d41839658bdd44a0ed2480f3891705ecb487ce28c0dde62c9040c997e0/aiohttp-3.14.3-cp314-cp314t-win32.whl", hash = "sha256:b304db572b4368edd8dda8a2274f73156fe15558fca4a917cb8a09fc47af5963", size = 474180, upload-time = "2026-07-23T01:57:19.306Z" }, + { url = "https://files.pythonhosted.org/packages/99/5d/3cd6ef0a2b2851f7ab913b5b079334781bd50ff56a323e4454063377a080/aiohttp-3.14.3-cp314-cp314t-win_amd64.whl", hash = "sha256:b20032766aedf6261c7a566585a40867d092ac03a0d81592d5370ef9b054f99b", size = 500528, upload-time = "2026-07-23T01:57:21.762Z" }, + { url = "https://files.pythonhosted.org/packages/a4/37/cfd1ed540a4d318da025590d96b728e63713c09e9377950fc655dadeb856/aiohttp-3.14.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2e1161602f45a54de2ce0905243a95f58cb42dcd378402f3697f5e0b21e9d2e7", size = 469280, upload-time = "2026-07-23T01:57:24.241Z" }, +] + +[[package]] +name = "aioitertools" +version = "0.13.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/3c/53c4a17a05fb9ea2313ee1777ff53f5e001aefd5cc85aa2f4c2d982e1e38/aioitertools-0.13.0.tar.gz", hash = "sha256:620bd241acc0bbb9ec819f1ab215866871b4bbd1f73836a55f799200ee86950c", size = 19322, upload-time = "2025-11-06T22:17:07.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/a1/510b0a7fadc6f43a6ce50152e69dbd86415240835868bb0bd9b5b88b1e06/aioitertools-0.13.0-py3-none-any.whl", hash = "sha256:0be0292b856f08dfac90e31f4739432f4cb6d7520ab9eb73e143f4f2fa5259be", size = 24182, upload-time = "2025-11-06T22:17:06.502Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "alabaster" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/f8/d9c74d0daf3f742840fd818d69cfae176fa332022fd44e3469487d5a9420/alabaster-1.0.0.tar.gz", hash = "sha256:c00dca57bca26fa62a6d7d0a9fcce65f3e026e9bfe33e9c538fd3fbb2144fd9e", size = 24210, upload-time = "2024-07-26T18:15:03.762Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/b3/6b4067be973ae96ba0d615946e314c5ae35f9f993eca561b356540bb0c2b/alabaster-1.0.0-py3-none-any.whl", hash = "sha256:fc6786402dc3fcb2de3cabd5fe455a2db534b371124f1f21de8731783dec828b", size = 13929, upload-time = "2024-07-26T18:15:02.05Z" }, +] + +[[package]] +name = "annotated-doc" +version = "0.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/57/ba/046ceea27344560984e26a590f90bc7f4a75b06701f653222458922b558c/annotated_doc-0.0.4.tar.gz", hash = "sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4", size = 7288, upload-time = "2025-11-10T22:07:42.062Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/d3/26bf1008eb3d2daa8ef4cacc7f3bfdc11818d111f7e2d0201bc6e3b49d45/annotated_doc-0.0.4-py3-none-any.whl", hash = "sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320", size = 5303, upload-time = "2025-11-10T22:07:40.673Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081, upload-time = "2024-05-20T21:33:25.928Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, +] + +[[package]] +name = "antlr4-python3-runtime" +version = "4.13.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/5f/2cdf6f7aca3b20d3f316e9f505292e1f256a32089bd702034c29ebde6242/antlr4_python3_runtime-4.13.2.tar.gz", hash = "sha256:909b647e1d2fc2b70180ac586df3933e38919c85f98ccc656a96cd3f25ef3916", size = 117467, upload-time = "2024-08-03T19:00:12.757Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/89/03/a851e84fcbb85214dc637b6378121ef9a0dd61b4c65264675d8a5c9b1ae7/antlr4_python3_runtime-4.13.2-py3-none-any.whl", hash = "sha256:fe3835eb8d33daece0e799090eda89719dbccee7aa39ef94eed3818cafa5a7e8", size = 144462, upload-time = "2024-08-03T19:00:11.134Z" }, +] + +[[package]] +name = "ast-serialize" +version = "0.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/58/ad/0d70a3a2d6e01968d985415259e8ec7ad3f777903f9b1c1f3c8c44642c60/ast_serialize-0.6.0.tar.gz", hash = "sha256:aadd3ffcf4858c9726bf3515f7b199c7eadbe504f96028e4a87172c0da65a8fe", size = 61489, upload-time = "2026-06-30T20:02:55.555Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/12/3e5f575f156555547c250a8b0d1347517a3a20fc7f4492e9703a69d4f45e/ast_serialize-0.6.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:a7520b672827885bafeae7501f684d14d47d17e5f45256f9df547686cca52264", size = 1177640, upload-time = "2026-06-30T20:02:06.708Z" }, + { url = "https://files.pythonhosted.org/packages/a2/a4/921a9e27951627983b0f368859ea00f8330a551dc0bf4c2fdcb11855a98b/ast_serialize-0.6.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a14191beec7e0c078d2fc1f6edc0aee88bcd4db9f18e1bc9f8052b559c22dddc", size = 1168111, upload-time = "2026-06-30T20:02:08.366Z" }, + { url = "https://files.pythonhosted.org/packages/00/69/950cf404de7b8782cf95e5c1237e25e2aa46177b287f39f9eeddf481fd6f/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:32ef62ec34cf6be20ad77d4799556638fbdf187f3ae10698dfb20ef9f2c89516", size = 1227656, upload-time = "2026-06-30T20:02:09.843Z" }, + { url = "https://files.pythonhosted.org/packages/4c/a8/46f8f6a6479d9d2273980957bb091a506c55f5b95d3c029ee58518a78407/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:13b7769970a39983b0adf2f38917b1cd3b8946f76df045756c3d741bc689f089", size = 1227706, upload-time = "2026-06-30T20:02:11.367Z" }, + { url = "https://files.pythonhosted.org/packages/b7/b9/9ac415bda0a40e49eab8fea3b2741c19c98bb84d57d62c4cfc6230eb67be/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6f7a408601bb3edaefb3bc67a4c01f5235e3253653b6a5729a2ee2382b35341c", size = 1431705, upload-time = "2026-06-30T20:02:12.737Z" }, + { url = "https://files.pythonhosted.org/packages/e5/06/8807115d441444879f7561b5eede5ac18fc80392f11826d61ccf31f503b1/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8670bfa51208a2c0c8d138928e40e998fab158f9200d53bb80c088b5b8eda7b8", size = 1249533, upload-time = "2026-06-30T20:02:14.571Z" }, + { url = "https://files.pythonhosted.org/packages/3e/c0/c2ba82ef9618650357d9421a1fdb27ffec862a7f57e8e2de82a3ccd11e12/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a4826809eb8597a8cd59fd924b6d7c285b8969a1e0007e2cb652cab62376270f", size = 1252619, upload-time = "2026-06-30T20:02:16.219Z" }, + { url = "https://files.pythonhosted.org/packages/0f/a7/fa31d52dd4102cede29fb9634e98d214129b2783b4f95528c6dc6a8f6587/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:577a6c189068686869f5f1ddc38363f3ae1808a4753b577266f9202071a7bb66", size = 1242983, upload-time = "2026-06-30T20:02:17.813Z" }, + { url = "https://files.pythonhosted.org/packages/b1/20/ddf742b5ad3c4bafd3466f2265037cfd99bc1b9a5ee46a5d58c90d523242/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:085de7f62dc9cc247eb01e965a362707d1d90b1d89a82c5bf78301a60a3c417b", size = 1296148, upload-time = "2026-06-30T20:02:19.146Z" }, + { url = "https://files.pythonhosted.org/packages/24/cb/9f6f217cce8b3b632c5568b478d195a35e79dce4dbe309438cb89ba6ea4f/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:9f8a8b78b13173de6a9ec22111d9be674874cd5bdccda04f14ae5ebc2bef403a", size = 1403826, upload-time = "2026-06-30T20:02:20.696Z" }, + { url = "https://files.pythonhosted.org/packages/2d/f8/9d16d4f0107a183924425cc0e7618d8bf76f96b45afa9ff19f924ed1ad57/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:f2ff3baffc3a29c1f15bc9098aa0c09763410262d5e6cef42116f7356c184554", size = 1502943, upload-time = "2026-06-30T20:02:22.034Z" }, + { url = "https://files.pythonhosted.org/packages/80/dd/bbc1c38756350dddf7e24acae1c9482ef42051c267417e019aecc1ed4075/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:0067b25fce104eaae5b88383de9ab803faeb671831e14ca698b771b356e2600f", size = 1497632, upload-time = "2026-06-30T20:02:23.517Z" }, + { url = "https://files.pythonhosted.org/packages/42/7e/9daffefcf5b97e6bb4c3e0b3c024c1aee9722f23d3cf7cd2ff80d6fb4a40/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c617417f9cbb0cb144f6283c3cbe0d2e0f01beaf9f608f662b21191058a626ec", size = 1448858, upload-time = "2026-06-30T20:02:24.889Z" }, + { url = "https://files.pythonhosted.org/packages/e5/1f/f9baaab81a677ea0af7d2458cac2f94ebcc85958f8a3c15ba9d9e5dab653/ast_serialize-0.6.0-cp314-cp314t-win32.whl", hash = "sha256:5337cb256dcea3df9288205213d1601581536526b8f4da44b6974f1180f3252a", size = 1052600, upload-time = "2026-06-30T20:02:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/9e/1f/41b535866519512d8cf6669cb2cff7823b7672bb6279c0333b4ff89d7d9f/ast_serialize-0.6.0-cp314-cp314t-win_amd64.whl", hash = "sha256:2d947e45cafc4b09bd7528917fa84c517654a43de173c79785574b7b3068ac24", size = 1095570, upload-time = "2026-06-30T20:02:27.639Z" }, + { url = "https://files.pythonhosted.org/packages/50/64/e472fe3e3a2d33d874b987e8518aedf24562919e3b6161a4fa1797e89c0f/ast_serialize-0.6.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6e15ec740436e1a0d62de848641abe5f3a2f89a7f94907d534795ac91bbacf14", size = 1067267, upload-time = "2026-06-30T20:02:28.949Z" }, + { url = "https://files.pythonhosted.org/packages/52/19/ac8348ae8711c9b5ae834634f635780cab62a0f5e6f988882e048b89c2ae/ast_serialize-0.6.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:093cb8bb91b720d8523580498d031791bb1bbaa048599c3d21085d380e11a596", size = 1185367, upload-time = "2026-06-30T20:02:30.427Z" }, + { url = "https://files.pythonhosted.org/packages/c1/f6/ec7ec652c51db77c2f61d8573338e13e4704303265ccc658cb4031d9f354/ast_serialize-0.6.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:e61580a69faf47e3689795367ed211f2a10fd741478cc0f36a0f128793360aad", size = 1178657, upload-time = "2026-06-30T20:02:31.964Z" }, + { url = "https://files.pythonhosted.org/packages/6f/02/613a7534a41d0122f37d1e0c64aa8ac78bfb831f8c92f6db057a311abb3c/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:305802f2ce2a7c4e87835078ea85c58b586ddda8095b92fe2ead9364ae19c80a", size = 1238620, upload-time = "2026-06-30T20:02:33.664Z" }, + { url = "https://files.pythonhosted.org/packages/4d/21/087957bba486242afc52f49b2d9e21c9dad00289356cf9efe67084015a9d/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c7b8b8f0c42f752ea00b2b7d7c090b3f80d9c1c5c75cadf16423790a0cc74081", size = 1236075, upload-time = "2026-06-30T20:02:34.936Z" }, + { url = "https://files.pythonhosted.org/packages/82/04/78128bbb170071c2c72a210a181f1c00e11cc1cec60a8beef747b07f9201/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cd5b91b9e6f2356ace3a556963b0cd783b395fbbb0bb17b4defc283415466e77", size = 1441348, upload-time = "2026-06-30T20:02:36.245Z" }, + { url = "https://files.pythonhosted.org/packages/64/64/62fb99d6faf199b4c3e5b08a07136e9a0d7664bb249c6de3670e5b63e9b6/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4d6ef91590258ada18909b9caea344dac4de2013906b035473cd674a43f4b790", size = 1258580, upload-time = "2026-06-30T20:02:37.53Z" }, + { url = "https://files.pythonhosted.org/packages/ca/87/b4d6c38e0ccd5e85dc54cecdf933a152c60b28fe5d993a6d8a72fa6d5896/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dcbed41e9386059fc0261d602445ede0976c2ecec2939688bcbcb9ed0b6f28b7", size = 1261693, upload-time = "2026-06-30T20:02:39.123Z" }, + { url = "https://files.pythonhosted.org/packages/0e/4b/3676ca2191f39bafb75f93f99b2f429ec464586158fece2165f3572805dc/ast_serialize-0.6.0-cp39-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:cdc4e6f930b9090c2f92c9036ad12ffb8e6e44d4a5ba06f1458a05d60f203f7b", size = 1252517, upload-time = "2026-06-30T20:02:40.511Z" }, + { url = "https://files.pythonhosted.org/packages/f3/58/494ef8c4b4acb2f4a265ac934caf45f792a08fe27d6b853de35ad991941a/ast_serialize-0.6.0-cp39-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:897ac47b5637be41c0c07061c8a912fafa967ef1dc73fa115e4bfa70882a093b", size = 1304843, upload-time = "2026-06-30T20:02:41.961Z" }, + { url = "https://files.pythonhosted.org/packages/b1/f2/13736d920ab3d49bbee80ef1a277dd7b7aaf3b3545efd9d2a8114fe05525/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c4af9a1386166e40ed01464991806f89038a2d89782576c7774876fa77034e32", size = 1413698, upload-time = "2026-06-30T20:02:44.179Z" }, + { url = "https://files.pythonhosted.org/packages/a8/5a/e046f3899e2acba4677d7427b76431443a1aa1a0e583dfb05b55b69d55cf/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:c901adbd750029b9ac4ad3d6aa56853e0ad4875119fbf52b7b8298afc223828b", size = 1512209, upload-time = "2026-06-30T20:02:45.584Z" }, + { url = "https://files.pythonhosted.org/packages/cc/c7/e42aaca7bb2d22a7c06d5a8c7930086c5a334e93d716e6fa5e6647a4515f/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae22a366b752ab4496191525b78b097b5b72d531752e3c1dd7e383a8f2c8a1a", size = 1508464, upload-time = "2026-06-30T20:02:46.942Z" }, + { url = "https://files.pythonhosted.org/packages/95/93/5524a3dc6c3f593de3228ed9cbef73afa047625b7000ec21b7f58e6eb4d4/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:4ed29121da8b3fdc291002801a1de0f76248fa07dce89157a5f277842cf6126e", size = 1457164, upload-time = "2026-06-30T20:02:48.294Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c0/36a6ffb4d653cf621427b4c4928671f53ad800c453474de2b82564a44ad9/ast_serialize-0.6.0-cp39-abi3-pyemscripten_2026_0_wasm32.whl", hash = "sha256:b1dac4e09d341c1300ba69cdcbe62867b32a8c75d90db9bf4d083bec3b039f0b", size = 863014, upload-time = "2026-06-30T20:02:49.742Z" }, + { url = "https://files.pythonhosted.org/packages/09/c7/7d5ad8b49e1278e1c2a1e0274bd7850560b3f09313aa00c13bc8d5544792/ast_serialize-0.6.0-cp39-abi3-win32.whl", hash = "sha256:82c312a7844d2fdeb4d5c48bd3d215bf940dafd4704e1a9bcf252a99010a99b1", size = 1063165, upload-time = "2026-06-30T20:02:50.98Z" }, + { url = "https://files.pythonhosted.org/packages/47/ae/6710c14ecb276031cf10249f6adf5a59e2d3fdb3b5183bd59f70524067ee/ast_serialize-0.6.0-cp39-abi3-win_amd64.whl", hash = "sha256:113b58346f9ceb664352032770caca817d4a3c86f611c6088e6ef65ddaa70f0e", size = 1101444, upload-time = "2026-06-30T20:02:52.554Z" }, + { url = "https://files.pythonhosted.org/packages/66/40/c53deb2cd0c9b0fb636d24d9f40924cf2e65028e6b20b10cd5c1eeb2c730/ast_serialize-0.6.0-cp39-abi3-win_arm64.whl", hash = "sha256:ccd132fe8db56f61fe743b1f644d01b8d65b83248a8da506f3132bda86d6ed5e", size = 1072965, upload-time = "2026-06-30T20:02:54.097Z" }, +] + +[[package]] +name = "astor" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/21/75b771132fee241dfe601d39ade629548a9626d1d39f333fde31bc46febe/astor-0.8.1.tar.gz", hash = "sha256:6a6effda93f4e1ce9f618779b2dd1d9d84f1e32812c23a29b3fff6fd7f63fa5e", size = 35090, upload-time = "2019-12-10T01:50:35.51Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/88/97eef84f48fa04fbd6750e62dcceafba6c63c81b7ac1420856c8dcc0a3f9/astor-0.8.1-py2.py3-none-any.whl", hash = "sha256:070a54e890cefb5b3739d19f30f5a5ec840ffc9c50ffa7d23cc9fc1a38ebbfc5", size = 27488, upload-time = "2019-12-10T01:50:33.628Z" }, +] + +[[package]] +name = "astroid" +version = "4.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/a0/fc1c9f396c354456d859eb09fa13186bda34cb5b000f47a7103fcf84fe66/astroid-4.3.0.tar.gz", hash = "sha256:2b5b5048d6edc40e748e2728790e444b81c3d358e19cc89db6e973236192362f", size = 438804, upload-time = "2026-08-07T20:28:28.363Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/0a/f277a39699ac334e332c991b6ce9e47a30bb2bdac6d2141fdbd2d39835a9/astroid-4.3.0-py3-none-any.whl", hash = "sha256:47f329c1f4709c479f84f824c4f3a132816603a749cd4aa6ee9030e69951491a", size = 286532, upload-time = "2026-08-07T20:28:26.602Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "aws-sam-translator" +version = "1.109.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "boto3" }, + { name = "jsonschema" }, + { name = "pydantic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/09/f62aa8d076f6ba85080ec6291e61af345e9be0daf8a4094101555e054ec7/aws_sam_translator-1.109.0.tar.gz", hash = "sha256:0c5e60223ae8434ce0c6bdb9a491d69ba3ec97e15c0d825d3803f7806382d804", size = 369016, upload-time = "2026-04-08T23:34:32.535Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/89/29/db13205af6bbebdc8dae9dd603ef97ee10a23cd8a3e26d9de728948b2e33/aws_sam_translator-1.109.0-py3-none-any.whl", hash = "sha256:9a6376e7c6d4fee173342b8b557035a8e3ec36e795e175e870411c8e4238873d", size = 432447, upload-time = "2026-04-08T23:34:30.881Z" }, +] + +[[package]] +name = "aws-xray-sdk" +version = "2.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/14/25/0cbd7a440080def5e6f063720c3b190a25f8aa2938c1e34415dc18241596/aws_xray_sdk-2.15.0.tar.gz", hash = "sha256:794381b96e835314345068ae1dd3b9120bd8b4e21295066c37e8814dbb341365", size = 76315, upload-time = "2025-10-29T20:59:45Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/c3/f30a7a63e664acc7c2545ca0491b6ce8264536e0e5cad3965f1d1b91e960/aws_xray_sdk-2.15.0-py2.py3-none-any.whl", hash = "sha256:422d62ad7d52e373eebb90b642eb1bb24657afe03b22a8df4a8b2e5108e278a3", size = 103228, upload-time = "2025-10-29T21:00:24.12Z" }, +] + +[[package]] +name = "babel" +version = "2.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/b2/51899539b6ceeeb420d40ed3cd4b7a40519404f9baf3d4ac99dc413a834b/babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d", size = 9959554, upload-time = "2026-02-01T12:30:56.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, +] + +[[package]] +name = "backrefs" +version = "7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5e/a7/a7dd63622beef68cc0d3c3c36d472e143dd95443d5ebf14cd1a5b4dfbf11/backrefs-7.0.tar.gz", hash = "sha256:4989bb9e1e99eb23647c7160ed51fb21d0b41b5d200f2d3017da41e023097e82", size = 7012453, upload-time = "2026-04-28T16:28:04.215Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/39/39a31d7eae729ea14ed10c3ccef79371197177b9355a86cb3525709e8502/backrefs-7.0-py310-none-any.whl", hash = "sha256:b57cd227ea556b0aed3dc9b8da4628db4eabc0402c6d7fcfc69283a93955f7e9", size = 380824, upload-time = "2026-04-28T16:27:55.647Z" }, + { url = "https://files.pythonhosted.org/packages/c9/b5/9302644225ba7dfa934a2ff2b9c7bb85701313a90dddb3dfaf693fa5bae2/backrefs-7.0-py311-none-any.whl", hash = "sha256:a0fa7360c63509e9e077e174ef4e6d3c21c8db94189b9d957289ae6d794b9475", size = 392626, upload-time = "2026-04-28T16:27:57.42Z" }, + { url = "https://files.pythonhosted.org/packages/36/da/87912ddec6e06feffbaa3d7aa18fc6352bee2e8f1fee185d7d1690f8f4e8/backrefs-7.0-py312-none-any.whl", hash = "sha256:ca42ce6a49ace3d75684dfa9937f3373902a63284ecb385ce36d15e5dcb41c12", size = 398537, upload-time = "2026-04-28T16:27:58.913Z" }, + { url = "https://files.pythonhosted.org/packages/00/bb/90ba423612b6aa0adccc6b1874bcd4a9b44b660c0c16f346611e00f64ac3/backrefs-7.0-py313-none-any.whl", hash = "sha256:f2c52955d631b9e1ac4cd56209f0a3a946d592b98e7790e77699339ae01c102a", size = 400491, upload-time = "2026-04-28T16:28:00.928Z" }, + { url = "https://files.pythonhosted.org/packages/3e/5c/fb93d3092640a24dfb7bd7727a24016d7c01774ca013e60efd3f683c8002/backrefs-7.0-py314-none-any.whl", hash = "sha256:a6448b28180e3ca01134c9cf09dcebafad8531072e09903c5451748a05f24bc9", size = 412349, upload-time = "2026-04-28T16:28:02.412Z" }, +] + +[[package]] +name = "blinker" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460, upload-time = "2024-11-08T17:25:47.436Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, +] + +[[package]] +name = "boto3" +version = "1.43.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "jmespath" }, + { name = "s3transfer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b7/65/47670987f2f9e181397872c7ee6415b7b95156d711b7eab6c55f66e575bc/boto3-1.43.0.tar.gz", hash = "sha256:80d44a943ef90aba7958ab31d30c155c198acc8a9581b5846b3878b2c8951086", size = 113143, upload-time = "2026-04-29T22:07:49.084Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/a0/3e6a0b1c1ea6bec76f71473727ef27abf3cd40e9709b3ebcbfbcfaae6f79/boto3-1.43.0-py3-none-any.whl", hash = "sha256:8ebe03754a4b73a5cb6ec2f14cca03ac33bd4760d0adea53da4724845130258b", size = 140497, upload-time = "2026-04-29T22:07:46.216Z" }, +] + +[[package]] +name = "botocore" +version = "1.43.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jmespath" }, + { name = "python-dateutil" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/79/2f4be1896db3db7ccf44504253a175d56b6bd6b669619edc5147d1aa21ea/botocore-1.43.0.tar.gz", hash = "sha256:e933b31a2d644253e1d029d7d39e99ba41b87e29300534f189744cc438cdf928", size = 15286817, upload-time = "2026-04-29T22:07:31.723Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bf/4b/afc1fef8a43bafb139f57f73bbd70df82807af5934321e8112ae50668827/botocore-1.43.0-py3-none-any.whl", hash = "sha256:cc5b15eaec3c6eac05d8012cb5ef17ebe891beb88a16ca13c374bfaece1241e6", size = 14970102, upload-time = "2026-04-29T22:07:27Z" }, +] + +[[package]] +name = "cairocffi" +version = "1.7.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/70/c5/1a4dc131459e68a173cbdab5fad6b524f53f9c1ef7861b7698e998b837cc/cairocffi-1.7.1.tar.gz", hash = "sha256:2e48ee864884ec4a3a34bfa8c9ab9999f688286eb714a15a43ec9d068c36557b", size = 88096, upload-time = "2024-06-18T10:56:06.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/93/d8/ba13451aa6b745c49536e87b6bf8f629b950e84bd0e8308f7dc6883b67e2/cairocffi-1.7.1-py3-none-any.whl", hash = "sha256:9803a0e11f6c962f3b0ae2ec8ba6ae45e957a146a004697a1ac1bbf16b073b3f", size = 75611, upload-time = "2024-06-18T10:55:59.489Z" }, +] + +[[package]] +name = "cairosvg" +version = "2.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cairocffi" }, + { name = "cssselect2" }, + { name = "defusedxml" }, + { name = "pillow" }, + { name = "tinycss2" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/38/07/e8412a13019b3f737972dea23a2c61ca42becafc16c9338f4ca7a0caa993/cairosvg-2.9.0.tar.gz", hash = "sha256:1debb00cd2da11350d8b6f5ceb739f1b539196d71d5cf5eb7363dbd1bfbc8dc5", size = 40877, upload-time = "2026-03-13T15:42:00.564Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bf/e0/5011747466414c12cac8a8df77aa235068669a6a5a5df301a96209db6054/cairosvg-2.9.0-py3-none-any.whl", hash = "sha256:4b82d07d145377dffdfc19d9791bd5fb65539bb4da0adecf0bdbd9cd4ffd7c68", size = 45962, upload-time = "2026-03-14T13:56:33.512Z" }, +] + +[[package]] +name = "cast-value-rs" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/a4/634d1917ac49ea69291471e87eee9c1aa45d71d6da9b2cd5e1bfe82729de/cast_value_rs-0.4.2.tar.gz", hash = "sha256:fd621b8dd4f7e93bbffdb119882d85e2731c2f0fb1d30de85f29e8e04c044822", size = 86862, upload-time = "2026-08-13T09:16:59.199Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/c7/9db59d415df2d1c9f905c4da951fe023c6259a162584ef68bd81c171d448/cast_value_rs-0.4.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:6d8e1c6d7b0fec6b1060f83867d20ebd0cb1ac6fa2954cd82f418a31a96ac504", size = 494354, upload-time = "2026-08-13T09:14:41.627Z" }, + { url = "https://files.pythonhosted.org/packages/8f/53/10ece0b4ba4a0c156674c2db7e5d05ce9b04efe72e191417546e111d645c/cast_value_rs-0.4.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8c953321ff7954e0fe1b25c1baf96f0a9cae0961b8a56ce63dc7b94e2ea7d85c", size = 458463, upload-time = "2026-08-13T09:14:43.371Z" }, + { url = "https://files.pythonhosted.org/packages/91/0b/e50ac2eb271eb6c34402b4abe317c795bc7d650d332d0bf422ae868aa2cd/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:68492eef745691c80754cd027e216dbd5f7a4ce2e07fddfded3ee59bd947afb5", size = 487628, upload-time = "2026-08-13T09:14:44.86Z" }, + { url = "https://files.pythonhosted.org/packages/a9/0f/69befc7905af2e73a2739b26444787cd528331c041f37235f3853bf15f75/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fbf145ed6f724fa7f5ddc9715f78e0d450ac141fc05299c83b2e7d627793ddaf", size = 555538, upload-time = "2026-08-13T09:14:46.305Z" }, + { url = "https://files.pythonhosted.org/packages/4a/1b/4105fabec3268139bda3555422808211ec29428e17fa56566c1af7957c04/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73fb23256dda16e4e9f49bfedebe0e068f00ece85091b526c102618f66144216", size = 650896, upload-time = "2026-08-13T09:14:48.049Z" }, + { url = "https://files.pythonhosted.org/packages/83/2a/452cf37675af02c3ac8bfa01fc962cb744a1392c51bccfb6d1faca423067/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8184135c78ebcabb904574a1b3bc5704c131140feae1b58d65c888fe08b46029", size = 561036, upload-time = "2026-08-13T09:14:49.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/87/edb215d17da304a6b36489fc51b8eb785c5b041c2fcc5f200f16adde3133/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:686ea86aad1ffebd0b6793549043108600593a85032457eb88a3a0513a4100f5", size = 549187, upload-time = "2026-08-13T09:14:50.801Z" }, + { url = "https://files.pythonhosted.org/packages/63/82/0f9963ef0bcb434cd1244cb2620123c2d71763d429d017ceb98fbb6faf48/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d6c425d2803e13408755a0022faa9efd0ab0becdf3573a1a8a7af64b1adee4ba", size = 591027, upload-time = "2026-08-13T09:14:52.281Z" }, + { url = "https://files.pythonhosted.org/packages/90/97/b489f8048491f2ece21bf99d5a1fea3bbfaf3cd0e9f555ac4a0352c11d81/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:92556f1bb9d6b222736d967228565ec745c640c29bc291d1cb730a1011d3dcac", size = 665201, upload-time = "2026-08-13T09:14:53.769Z" }, + { url = "https://files.pythonhosted.org/packages/ce/9f/fabffd9788f0b2d3f49ca4582b8859ab58b929b1b8837ec0be1263399279/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1b0881c23a8f5ff1dc6c70542179f2fc9191e0b7fa7a02f65316fb48904cd8d1", size = 831085, upload-time = "2026-08-13T09:14:55.244Z" }, + { url = "https://files.pythonhosted.org/packages/b5/66/ca653bf9b51eb624615623611db28ec9428a351259fcf5625c5520faf759/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:8a67648bf47d9b740388efaf6f05185f22dea783e97eba895efdd1dbafe8e3cc", size = 788462, upload-time = "2026-08-13T09:14:56.666Z" }, + { url = "https://files.pythonhosted.org/packages/f1/54/3a9280f791c8765a54f7814a010d2f460c7d5f5483be3e5634f4d9b38d75/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:decf297bc576675fff2139885fb88f84844e27b99e5d28eaa01909db7a327c4b", size = 753055, upload-time = "2026-08-13T09:14:58.302Z" }, + { url = "https://files.pythonhosted.org/packages/06/26/09f4618dbab2de8ea427e817c349b8391b4d559316de899e9b54dde6143e/cast_value_rs-0.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:79a8c13af39bf65014dd6567dc5fa7c42dfda246e4335ab52814f3dd6fb42cac", size = 442068, upload-time = "2026-08-13T09:15:00.414Z" }, + { url = "https://files.pythonhosted.org/packages/fc/49/7def5933625ff3c98e7d20cbd7de0aa1e83098ffa425a9df087764657767/cast_value_rs-0.4.2-cp312-cp312-win_arm64.whl", hash = "sha256:b8af7de3639271ad9e62aba4d15ddd22819c706bd7c7859663fdbb022397bdad", size = 397846, upload-time = "2026-08-13T09:15:02.022Z" }, + { url = "https://files.pythonhosted.org/packages/6f/fc/1f48ae9ea1f10caf3bbc31b288d08137835d8965188f6ddcccdb3c7d398e/cast_value_rs-0.4.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:297445abc64891a2e62af93e4f35bb280f874ac548646d0a6b04a86d45e636a5", size = 494394, upload-time = "2026-08-13T09:15:03.604Z" }, + { url = "https://files.pythonhosted.org/packages/7f/f3/d633218979cd8839fcfbade64a277c0ff9d8ff59d21bbd8a59f1467085b4/cast_value_rs-0.4.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:b8b6e0781b4ce61a559cc050d836a52157bd30b1f59d63fdeee79fbc19ab7e57", size = 458677, upload-time = "2026-08-13T09:15:04.947Z" }, + { url = "https://files.pythonhosted.org/packages/97/e4/96d72ccf5e00dd7af7bf55c96313df2ffba1f34a224f10430716232775c0/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8399dc89570c01537c07adc03fc2fc0e43a517be8a198e2f9e3f8a70dd003be0", size = 487289, upload-time = "2026-08-13T09:15:06.493Z" }, + { url = "https://files.pythonhosted.org/packages/93/30/18313de8c1d3826e9a6abd883b7a7981b19391f674dcd52ff2635d19f8ee/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:939417d72c9945ce24eb959e6b2cd32f7aa7d0a50a06a0fac484056b10b650dd", size = 555221, upload-time = "2026-08-13T09:15:08.28Z" }, + { url = "https://files.pythonhosted.org/packages/e9/1f/ed22b2e536ccbd4c5b234d869fc8f478347a45f7b940273023a0d6013134/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:101318e594ee998a5ccbc5ea7ed045cbd9fd22d45cac467c745fbd30309f1343", size = 650972, upload-time = "2026-08-13T09:15:10.103Z" }, + { url = "https://files.pythonhosted.org/packages/d7/d2/39f9ff9b678dfb01d206aec6be0f486137d5e9669ebadf0d1f356d2a7324/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d23bac26b2c2fe6a2368d10fbb072a71671f6e0d4d8cf9e893f62ed3530bbd1b", size = 560869, upload-time = "2026-08-13T09:15:11.602Z" }, + { url = "https://files.pythonhosted.org/packages/60/18/f63e8378db66b5a99e96c1422c68ba02a4e35de34355b90cf6d169d99ae6/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b9d799a20d7517974d61d7c4dd54e5d7ef439e726012c087bada31bc644b1535", size = 548885, upload-time = "2026-08-13T09:15:13.18Z" }, + { url = "https://files.pythonhosted.org/packages/98/af/12349007b670b11e16d3be51c29ab2398550b2653dae692a5d788d3dda87/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b9f0f04815efcc47592474e91f61f24810139396696f0690f3d0bf0e6ff3bb4a", size = 590846, upload-time = "2026-08-13T09:15:14.67Z" }, + { url = "https://files.pythonhosted.org/packages/a3/cf/6a39df104923bc397ae58f90e21d1e87edd62d17f24fe3d6777e6c4d3e5f/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e69f81dab0b47c74c1f30c79198c412938b6c41510b8124dbd08fb36d13a8807", size = 665064, upload-time = "2026-08-13T09:15:16.527Z" }, + { url = "https://files.pythonhosted.org/packages/36/df/0a9ac5bae4e1d3b7b4a79795054d822c26bdbc3bedad71fe13e8ce666c4b/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:59e15ec495e8707447180e0111e65e083464da60236edd5c3387efedce3da997", size = 830909, upload-time = "2026-08-13T09:15:18.088Z" }, + { url = "https://files.pythonhosted.org/packages/2f/7d/9e99c969dd76087dbf731667982d8bb6b390d29c8f37c09dd330657b0487/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:f9e787397588fabb28a146a28159150f44e8ef85a25abe364f989044f1b7159d", size = 788217, upload-time = "2026-08-13T09:15:19.706Z" }, + { url = "https://files.pythonhosted.org/packages/21/a9/5d7410d37be26bed1dc740c885a0c7fdb213b93e9b13ac76fb3282aa50ea/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:5c66ca6ad21758993830a9f4d24263065727bf767e4524d79ded0c0b61e3da9d", size = 752817, upload-time = "2026-08-13T09:15:21.197Z" }, + { url = "https://files.pythonhosted.org/packages/65/10/9c18cb01104bb211c9b0d9a956fae3f1a40f743c35bbc6763d0114ec36a7/cast_value_rs-0.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:26fe305d5bd35d21c5ee72c5651892895447e175ba3019a24713c565d965c0ef", size = 442025, upload-time = "2026-08-13T09:15:22.575Z" }, + { url = "https://files.pythonhosted.org/packages/64/49/42a0b48a71aca3ebb0abd0948fa9d484723c3562af30a8d6904b874abb2f/cast_value_rs-0.4.2-cp313-cp313-win_arm64.whl", hash = "sha256:9ce6678fc4b1bdc459178225347acd8019f1d22bca1e13ab86cc2a3e4ecb2f46", size = 397871, upload-time = "2026-08-13T09:15:23.906Z" }, + { url = "https://files.pythonhosted.org/packages/be/e9/baf39cd3991962705ffd055fce071e23e7707f62df3fb44af2ffe0e84d11/cast_value_rs-0.4.2-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:cefdcfd4d2b95e3b35fd98b3d3d865be9b3ef1bc1264db3bc1b8c50c5e8ac999", size = 495672, upload-time = "2026-08-13T09:15:25.168Z" }, + { url = "https://files.pythonhosted.org/packages/ed/9f/7ac6bf95d160f3fd89020aa952ffb4a49216b85a3fda02f84bc2c2612a2f/cast_value_rs-0.4.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:cbcec2cfd199c1e404f5bda71b273b4a7470762f4b55c1c21f09d60d2762e339", size = 458480, upload-time = "2026-08-13T09:15:26.647Z" }, + { url = "https://files.pythonhosted.org/packages/65/e5/46c2985ccbae41c8140f04f2acc9080761f10e8d2f8101c46083e632f812/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c224a9b30c2521cd06eac4bb1ac3860f41c902695e6f806344bc039d7a8a1d93", size = 486807, upload-time = "2026-08-13T09:15:28.129Z" }, + { url = "https://files.pythonhosted.org/packages/18/13/97851c45b275fbc9d42b5d5a340fd5ea430525b60c2eacfe6a36399d69ef/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1eaa7c3d5fe418a74928f78514f9baeaeb8e31b93db96b1761edd6144f0d2eff", size = 555335, upload-time = "2026-08-13T09:15:29.648Z" }, + { url = "https://files.pythonhosted.org/packages/7f/b3/c84c1e820786ddb062b162112b80e5dfc1b5b54b11125618f38c1e18d075/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3bddec46b36f29964c8d4bbe82b8270575fbe1c0fb41c404bb3da1778f390a24", size = 650347, upload-time = "2026-08-13T09:15:31.044Z" }, + { url = "https://files.pythonhosted.org/packages/60/38/52b4cc31570384e0286e28a03164a357d53a8aba7421ef83e500843d5449/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ab3fd77144d26e2da2a113f862c05ea1cf465df347daf5deb6cf1689253fddfa", size = 561498, upload-time = "2026-08-13T09:15:32.485Z" }, + { url = "https://files.pythonhosted.org/packages/41/c8/313e1d016b0adfccd1ead2bb28d2c94313ab62534bd6e11db19a480d3b55/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e4affe8668a2f17764ed978c2dddb2b49554f36a71389e6928a8a5523c1a4173", size = 548676, upload-time = "2026-08-13T09:15:33.912Z" }, + { url = "https://files.pythonhosted.org/packages/81/8b/a11f8e514598ebfc084507b0db390ecbdc6bfcffbf91ae666e0de93e6c25/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a67316b00ca01a78865d222badef2b1cb6c60ad5ebd360bf4fa3b224e87b8ffa", size = 590803, upload-time = "2026-08-13T09:15:35.384Z" }, + { url = "https://files.pythonhosted.org/packages/94/1e/ed86da6fe69eff312cc83e348cf4715d4168ab2699783febd24bfd477cd8/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9946054c77d7c5df579e9e99ebebd4d8a220cb04a6af1b6467112dfe07eee72d", size = 664118, upload-time = "2026-08-13T09:15:36.797Z" }, + { url = "https://files.pythonhosted.org/packages/0b/01/58a3eadff1233bd98d5809e2f6b5dc6d1b8c4c770664145f57fd0bdce756/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:95b064458233a7ef0525481eccfd2d37e86620d877ab1535ae809d37355cf131", size = 830686, upload-time = "2026-08-13T09:15:38.645Z" }, + { url = "https://files.pythonhosted.org/packages/e6/40/a234d9d06013a0bee08f662ab083b3a55decfa2dbb315094fdf06693d425/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:d7de068a1dcc65d1aaf4e93228198b588776bd25b62ef42478ab7efe5245a6f3", size = 787835, upload-time = "2026-08-13T09:15:40.078Z" }, + { url = "https://files.pythonhosted.org/packages/d6/72/93f906345d03972de52e3e74dd4ed12b56aab53bec85cc96020690ba6dbe/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ae0cbdd44290a74e34519eb990b33bf0f8e96f0fde95ffc799913ff1aab27719", size = 753039, upload-time = "2026-08-13T09:15:41.702Z" }, + { url = "https://files.pythonhosted.org/packages/e3/a5/47b6db4f68da086db3f3768775f545b9b7f660cab8f61039c91de1f813c4/cast_value_rs-0.4.2-cp314-cp314-win32.whl", hash = "sha256:d438517530d3a8d6bc810ab6dee831c48b45287435513fea1b0476b5d4fda07d", size = 387092, upload-time = "2026-08-13T09:15:43.218Z" }, + { url = "https://files.pythonhosted.org/packages/d3/9c/5f71a5e94875bb999646227a583792dbbe9a2b257df0d961e8a2da879f9e/cast_value_rs-0.4.2-cp314-cp314-win_amd64.whl", hash = "sha256:7e7bb9faa4820b7eb0d99074fd61efff3a7392e72b6abe4b41c9d6b6d14fe457", size = 442126, upload-time = "2026-08-13T09:15:44.623Z" }, + { url = "https://files.pythonhosted.org/packages/95/1c/8e7546a044da8e92eafbb12594169301cc94e2a071fd3e34204595d0a05f/cast_value_rs-0.4.2-cp314-cp314-win_arm64.whl", hash = "sha256:1f57e762a06102d61e940548a6ab841e05ad1f51f1c4e2aa26bc27a8c59a5abc", size = 398200, upload-time = "2026-08-13T09:15:46.117Z" }, + { url = "https://files.pythonhosted.org/packages/a0/09/527646deeb622e5a597e4271e9e06d9d7cd24d64de77b8cb4ce250128c18/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:230f6440db74d2d11e513060d0e72aa3f897546465bc778d30aaeac90f8e733e", size = 485197, upload-time = "2026-08-13T09:15:47.622Z" }, + { url = "https://files.pythonhosted.org/packages/b9/79/aaa713cb151a902439b670a4774ea76d0a5dadf1f03954f6a34af2a6cb1e/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:37538170dc1fedbfd62dd56670e443b881474e7eda7f583a3c989c83a9ff15fc", size = 538669, upload-time = "2026-08-13T09:15:49.148Z" }, + { url = "https://files.pythonhosted.org/packages/d3/b1/2cf4f4f13f74caaa4dab4ddf4924fdeeffb39920d5ec30a80112aa041efa/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:86d00b9cef0d38d0c5631ba63270c38c5d7c85aa87c609644f204919f939f0c9", size = 649341, upload-time = "2026-08-13T09:15:50.614Z" }, + { url = "https://files.pythonhosted.org/packages/39/8b/1faa6b27cda3dd793635c7945118e49188b6714d6bf23bb072efd718e467/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:89434eebb7a12f66e99382e08c32648f055e24d9fce66274adef6620af2aebbd", size = 555253, upload-time = "2026-08-13T09:15:52.252Z" }, + { url = "https://files.pythonhosted.org/packages/8b/c2/d31f177025b51a3fda70c5888b92f5fd30ec53bc2df2c046fc9a2717cd36/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:704171aec75f417f5a70a3eb5f107fbfc79183620093c9d9074290920a5981f1", size = 547964, upload-time = "2026-08-13T09:15:53.669Z" }, + { url = "https://files.pythonhosted.org/packages/64/99/521c2d6347ca39deef237909dfee61c6d2cb806dcc20d74636e209bc646e/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2add2599d299436ec161661a8e119a69742c763a0936e542db92b1ce9d6e0c04", size = 574778, upload-time = "2026-08-13T09:15:55.479Z" }, + { url = "https://files.pythonhosted.org/packages/f0/70/35c7cb37839454aeb93b9576b42daebd8249dd59e3834cd1be020b4b0660/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:da5df79a926bdcc1f5494612f621027970a9702eb49d556068025166d4c0ace2", size = 662461, upload-time = "2026-08-13T09:15:56.97Z" }, + { url = "https://files.pythonhosted.org/packages/24/4f/a71bfaea1286bd12cc912733d650bd89a07c4430ee715202551c6e3eb0b0/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:5552e3c80d43de7a8a821793cb57da0dd3720a377051a5bf86bcabe094e87777", size = 814743, upload-time = "2026-08-13T09:15:58.652Z" }, + { url = "https://files.pythonhosted.org/packages/94/a3/b04e0f42dafeae30604abca079cce303ebb69ba24f3c4debbf211ecc781c/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:73978c6dd2ce45a05a59ec7090df8b3f2a579ee86db9b1c7df21ede17f32189e", size = 782340, upload-time = "2026-08-13T09:16:00.135Z" }, + { url = "https://files.pythonhosted.org/packages/3a/6c/913de75054092de796509dc04b92fc6ac1bf83dc86901f1f482667dead16/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:45d630592afb18880d4df0d7afb28b8cfc0ba6aa742d8db115f616df284b453a", size = 754068, upload-time = "2026-08-13T09:16:01.572Z" }, +] + +[[package]] +name = "certifi" +version = "2026.4.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/25/ee/6caf7a40c36a1220410afe15a1cc64993a1f864871f698c0f93acb72842a/certifi-2026.4.22.tar.gz", hash = "sha256:8d455352a37b71bf76a79caa83a3d6c25afee4a385d632127b6afb3963f1c580", size = 137077, upload-time = "2026-04-22T11:26:11.191Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/30/7cd8fdcdfbc5b869528b079bfb76dcdf6056b1a2097a662e5e8c04f42965/certifi-2026.4.22-py3-none-any.whl", hash = "sha256:3cb2210c8f88ba2318d29b0388d1023c8492ff72ecdde4ebdaddbb13a31b1c4a", size = 135707, upload-time = "2026-04-22T11:26:09.372Z" }, +] + +[[package]] +name = "cffi" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" }, + { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" }, + { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" }, + { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" }, + { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" }, + { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" }, + { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" }, + { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" }, + { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" }, + { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" }, + { url = "https://files.pythonhosted.org/packages/4b/8d/a0a47a0c9e413a658623d014e91e74a50cdd2c423f7ccfd44086ef767f90/cffi-2.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", size = 185230, upload-time = "2025-09-08T23:23:00.879Z" }, + { url = "https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", size = 181043, upload-time = "2025-09-08T23:23:02.231Z" }, + { url = "https://files.pythonhosted.org/packages/b0/1e/d22cc63332bd59b06481ceaac49d6c507598642e2230f201649058a7e704/cffi-2.0.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", size = 212446, upload-time = "2025-09-08T23:23:03.472Z" }, + { url = "https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", size = 220101, upload-time = "2025-09-08T23:23:04.792Z" }, + { url = "https://files.pythonhosted.org/packages/f2/7f/e6647792fc5850d634695bc0e6ab4111ae88e89981d35ac269956605feba/cffi-2.0.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", size = 207948, upload-time = "2025-09-08T23:23:06.127Z" }, + { url = "https://files.pythonhosted.org/packages/cb/1e/a5a1bd6f1fb30f22573f76533de12a00bf274abcdc55c8edab639078abb6/cffi-2.0.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", size = 206422, upload-time = "2025-09-08T23:23:07.753Z" }, + { url = "https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", size = 219499, upload-time = "2025-09-08T23:23:09.648Z" }, + { url = "https://files.pythonhosted.org/packages/50/e1/a969e687fcf9ea58e6e2a928ad5e2dd88cc12f6f0ab477e9971f2309b57c/cffi-2.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", size = 222928, upload-time = "2025-09-08T23:23:10.928Z" }, + { url = "https://files.pythonhosted.org/packages/36/54/0362578dd2c9e557a28ac77698ed67323ed5b9775ca9d3fe73fe191bb5d8/cffi-2.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", size = 221302, upload-time = "2025-09-08T23:23:12.42Z" }, + { url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909, upload-time = "2025-09-08T23:23:14.32Z" }, + { url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402, upload-time = "2025-09-08T23:23:15.535Z" }, + { url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780, upload-time = "2025-09-08T23:23:16.761Z" }, + { url = "https://files.pythonhosted.org/packages/92/c4/3ce07396253a83250ee98564f8d7e9789fab8e58858f35d07a9a2c78de9f/cffi-2.0.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", size = 185320, upload-time = "2025-09-08T23:23:18.087Z" }, + { url = "https://files.pythonhosted.org/packages/59/dd/27e9fa567a23931c838c6b02d0764611c62290062a6d4e8ff7863daf9730/cffi-2.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", size = 181487, upload-time = "2025-09-08T23:23:19.622Z" }, + { url = "https://files.pythonhosted.org/packages/d6/43/0e822876f87ea8a4ef95442c3d766a06a51fc5298823f884ef87aaad168c/cffi-2.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", size = 220049, upload-time = "2025-09-08T23:23:20.853Z" }, + { url = "https://files.pythonhosted.org/packages/b4/89/76799151d9c2d2d1ead63c2429da9ea9d7aac304603de0c6e8764e6e8e70/cffi-2.0.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", size = 207793, upload-time = "2025-09-08T23:23:22.08Z" }, + { url = "https://files.pythonhosted.org/packages/bb/dd/3465b14bb9e24ee24cb88c9e3730f6de63111fffe513492bf8c808a3547e/cffi-2.0.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", size = 206300, upload-time = "2025-09-08T23:23:23.314Z" }, + { url = "https://files.pythonhosted.org/packages/47/d9/d83e293854571c877a92da46fdec39158f8d7e68da75bf73581225d28e90/cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", size = 219244, upload-time = "2025-09-08T23:23:24.541Z" }, + { url = "https://files.pythonhosted.org/packages/2b/0f/1f177e3683aead2bb00f7679a16451d302c436b5cbf2505f0ea8146ef59e/cffi-2.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", size = 222828, upload-time = "2025-09-08T23:23:26.143Z" }, + { url = "https://files.pythonhosted.org/packages/c6/0f/cafacebd4b040e3119dcb32fed8bdef8dfe94da653155f9d0b9dc660166e/cffi-2.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", size = 220926, upload-time = "2025-09-08T23:23:27.873Z" }, + { url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328, upload-time = "2025-09-08T23:23:44.61Z" }, + { url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650, upload-time = "2025-09-08T23:23:45.848Z" }, + { url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687, upload-time = "2025-09-08T23:23:47.105Z" }, + { url = "https://files.pythonhosted.org/packages/3e/61/c768e4d548bfa607abcda77423448df8c471f25dbe64fb2ef6d555eae006/cffi-2.0.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", size = 188773, upload-time = "2025-09-08T23:23:29.347Z" }, + { url = "https://files.pythonhosted.org/packages/2c/ea/5f76bce7cf6fcd0ab1a1058b5af899bfbef198bea4d5686da88471ea0336/cffi-2.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", size = 185013, upload-time = "2025-09-08T23:23:30.63Z" }, + { url = "https://files.pythonhosted.org/packages/be/b4/c56878d0d1755cf9caa54ba71e5d049479c52f9e4afc230f06822162ab2f/cffi-2.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", size = 221593, upload-time = "2025-09-08T23:23:31.91Z" }, + { url = "https://files.pythonhosted.org/packages/e0/0d/eb704606dfe8033e7128df5e90fee946bbcb64a04fcdaa97321309004000/cffi-2.0.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", size = 209354, upload-time = "2025-09-08T23:23:33.214Z" }, + { url = "https://files.pythonhosted.org/packages/d8/19/3c435d727b368ca475fb8742ab97c9cb13a0de600ce86f62eab7fa3eea60/cffi-2.0.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", size = 208480, upload-time = "2025-09-08T23:23:34.495Z" }, + { url = "https://files.pythonhosted.org/packages/d0/44/681604464ed9541673e486521497406fadcc15b5217c3e326b061696899a/cffi-2.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", size = 221584, upload-time = "2025-09-08T23:23:36.096Z" }, + { url = "https://files.pythonhosted.org/packages/25/8e/342a504ff018a2825d395d44d63a767dd8ebc927ebda557fecdaca3ac33a/cffi-2.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", size = 224443, upload-time = "2025-09-08T23:23:37.328Z" }, + { url = "https://files.pythonhosted.org/packages/e1/5e/b666bacbbc60fbf415ba9988324a132c9a7a0448a9a8f125074671c0f2c3/cffi-2.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", size = 223437, upload-time = "2025-09-08T23:23:38.945Z" }, + { url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487, upload-time = "2025-09-08T23:23:40.423Z" }, + { url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726, upload-time = "2025-09-08T23:23:41.742Z" }, + { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" }, +] + +[[package]] +name = "cfn-lint" +version = "1.51.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aws-sam-translator" }, + { name = "jsonpatch" }, + { name = "networkx" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "sympy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5e/ea/bc4954dcbff3ecb500e2593e4b64d0e9a552973249b2a27dd22eee3fb5b0/cfn_lint-1.51.0.tar.gz", hash = "sha256:05d2a59708c99363afe3af6ac7325de95a5b37f8eef7728f41ae567d088a61f1", size = 4088652, upload-time = "2026-05-12T20:34:25.712Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/48/12/016d6b4a43bb7eb2e430770e04325ef159d73d4183dce94c6fa6dc144902/cfn_lint-1.51.0-py3-none-any.whl", hash = "sha256:116d4f9c7c7d039e69c01c31fe9ff309ff79f0884c859ea92b353507903dd89e", size = 6065464, upload-time = "2026-05-12T20:34:22.885Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/a1/67fe25fac3c7642725500a3f6cfe5821ad557c3abb11c9d20d12c7008d3e/charset_normalizer-3.4.7.tar.gz", hash = "sha256:ae89db9e5f98a11a4bf50407d4363e7b09b31e55bc117b4f7d80aab97ba009e5", size = 144271, upload-time = "2026-04-02T09:28:39.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/eb/4fc8d0a7110eb5fc9cc161723a34a8a6c200ce3b4fbf681bc86feee22308/charset_normalizer-3.4.7-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:eca9705049ad3c7345d574e3510665cb2cf844c2f2dcfe675332677f081cbd46", size = 311328, upload-time = "2026-04-02T09:26:24.331Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e3/0fadc706008ac9d7b9b5be6dc767c05f9d3e5df51744ce4cc9605de7b9f4/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6178f72c5508bfc5fd446a5905e698c6212932f25bcdd4b47a757a50605a90e2", size = 208061, upload-time = "2026-04-02T09:26:25.568Z" }, + { url = "https://files.pythonhosted.org/packages/42/f0/3dd1045c47f4a4604df85ec18ad093912ae1344ac706993aff91d38773a2/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e1421b502d83040e6d7fb2fb18dff63957f720da3d77b2fbd3187ceb63755d7b", size = 229031, upload-time = "2026-04-02T09:26:26.865Z" }, + { url = "https://files.pythonhosted.org/packages/dc/67/675a46eb016118a2fbde5a277a5d15f4f69d5f3f5f338e5ee2f8948fcf43/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:edac0f1ab77644605be2cbba52e6b7f630731fc42b34cb0f634be1a6eface56a", size = 225239, upload-time = "2026-04-02T09:26:28.044Z" }, + { url = "https://files.pythonhosted.org/packages/4b/f8/d0118a2f5f23b02cd166fa385c60f9b0d4f9194f574e2b31cef350ad7223/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5649fd1c7bade02f320a462fdefd0b4bd3ce036065836d4f42e0de958038e116", size = 216589, upload-time = "2026-04-02T09:26:29.239Z" }, + { url = "https://files.pythonhosted.org/packages/b1/f1/6d2b0b261b6c4ceef0fcb0d17a01cc5bc53586c2d4796fa04b5c540bc13d/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:203104ed3e428044fd943bc4bf45fa73c0730391f9621e37fe39ecf477b128cb", size = 202733, upload-time = "2026-04-02T09:26:30.5Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c0/7b1f943f7e87cc3db9626ba17807d042c38645f0a1d4415c7a14afb5591f/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:298930cec56029e05497a76988377cbd7457ba864beeea92ad7e844fe74cd1f1", size = 212652, upload-time = "2026-04-02T09:26:31.709Z" }, + { url = "https://files.pythonhosted.org/packages/38/dd/5a9ab159fe45c6e72079398f277b7d2b523e7f716acc489726115a910097/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:708838739abf24b2ceb208d0e22403dd018faeef86ddac04319a62ae884c4f15", size = 211229, upload-time = "2026-04-02T09:26:33.282Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ff/531a1cad5ca855d1c1a8b69cb71abfd6d85c0291580146fda7c82857caa1/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0f7eb884681e3938906ed0434f20c63046eacd0111c4ba96f27b76084cd679f5", size = 203552, upload-time = "2026-04-02T09:26:34.845Z" }, + { url = "https://files.pythonhosted.org/packages/c1/4c/a5fb52d528a8ca41f7598cb619409ece30a169fbdf9cdce592e53b46c3a6/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4dc1e73c36828f982bfe79fadf5919923f8a6f4df2860804db9a98c48824ce8d", size = 230806, upload-time = "2026-04-02T09:26:36.152Z" }, + { url = "https://files.pythonhosted.org/packages/59/7a/071feed8124111a32b316b33ae4de83d36923039ef8cf48120266844285b/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:aed52fea0513bac0ccde438c188c8a471c4e0f457c2dd20cdbf6ea7a450046c7", size = 212316, upload-time = "2026-04-02T09:26:37.672Z" }, + { url = "https://files.pythonhosted.org/packages/fd/35/f7dba3994312d7ba508e041eaac39a36b120f32d4c8662b8814dab876431/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:fea24543955a6a729c45a73fe90e08c743f0b3334bbf3201e6c4bc1b0c7fa464", size = 227274, upload-time = "2026-04-02T09:26:38.93Z" }, + { url = "https://files.pythonhosted.org/packages/8a/2d/a572df5c9204ab7688ec1edc895a73ebded3b023bb07364710b05dd1c9be/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb6d88045545b26da47aa879dd4a89a71d1dce0f0e549b1abcb31dfe4a8eac49", size = 218468, upload-time = "2026-04-02T09:26:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/86/eb/890922a8b03a568ca2f336c36585a4713c55d4d67bf0f0c78924be6315ca/charset_normalizer-3.4.7-cp312-cp312-win32.whl", hash = "sha256:2257141f39fe65a3fdf38aeccae4b953e5f3b3324f4ff0daf9f15b8518666a2c", size = 148460, upload-time = "2026-04-02T09:26:41.416Z" }, + { url = "https://files.pythonhosted.org/packages/35/d9/0e7dffa06c5ab081f75b1b786f0aefc88365825dfcd0ac544bdb7b2b6853/charset_normalizer-3.4.7-cp312-cp312-win_amd64.whl", hash = "sha256:5ed6ab538499c8644b8a3e18debabcd7ce684f3fa91cf867521a7a0279cab2d6", size = 159330, upload-time = "2026-04-02T09:26:42.554Z" }, + { url = "https://files.pythonhosted.org/packages/9e/5d/481bcc2a7c88ea6b0878c299547843b2521ccbc40980cb406267088bc701/charset_normalizer-3.4.7-cp312-cp312-win_arm64.whl", hash = "sha256:56be790f86bfb2c98fb742ce566dfb4816e5a83384616ab59c49e0604d49c51d", size = 147828, upload-time = "2026-04-02T09:26:44.075Z" }, + { url = "https://files.pythonhosted.org/packages/c1/3b/66777e39d3ae1ddc77ee606be4ec6d8cbd4c801f65e5a1b6f2b11b8346dd/charset_normalizer-3.4.7-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f496c9c3cc02230093d8330875c4c3cdfc3b73612a5fd921c65d39cbcef08063", size = 309627, upload-time = "2026-04-02T09:26:45.198Z" }, + { url = "https://files.pythonhosted.org/packages/2e/4e/b7f84e617b4854ade48a1b7915c8ccfadeba444d2a18c291f696e37f0d3b/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ea948db76d31190bf08bd371623927ee1339d5f2a0b4b1b4a4439a65298703c", size = 207008, upload-time = "2026-04-02T09:26:46.824Z" }, + { url = "https://files.pythonhosted.org/packages/c4/bb/ec73c0257c9e11b268f018f068f5d00aa0ef8c8b09f7753ebd5f2880e248/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a277ab8928b9f299723bc1a2dabb1265911b1a76341f90a510368ca44ad9ab66", size = 228303, upload-time = "2026-04-02T09:26:48.397Z" }, + { url = "https://files.pythonhosted.org/packages/85/fb/32d1f5033484494619f701e719429c69b766bfc4dbc61aa9e9c8c166528b/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3bec022aec2c514d9cf199522a802bd007cd588ab17ab2525f20f9c34d067c18", size = 224282, upload-time = "2026-04-02T09:26:49.684Z" }, + { url = "https://files.pythonhosted.org/packages/fa/07/330e3a0dda4c404d6da83b327270906e9654a24f6c546dc886a0eb0ffb23/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e044c39e41b92c845bc815e5ae4230804e8e7bc29e399b0437d64222d92809dd", size = 215595, upload-time = "2026-04-02T09:26:50.915Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7c/fc890655786e423f02556e0216d4b8c6bcb6bdfa890160dc66bf52dee468/charset_normalizer-3.4.7-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:f495a1652cf3fbab2eb0639776dad966c2fb874d79d87ca07f9d5f059b8bd215", size = 201986, upload-time = "2026-04-02T09:26:52.197Z" }, + { url = "https://files.pythonhosted.org/packages/d8/97/bfb18b3db2aed3b90cf54dc292ad79fdd5ad65c4eae454099475cbeadd0d/charset_normalizer-3.4.7-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e712b419df8ba5e42b226c510472b37bd57b38e897d3eca5e8cfd410a29fa859", size = 211711, upload-time = "2026-04-02T09:26:53.49Z" }, + { url = "https://files.pythonhosted.org/packages/6f/a5/a581c13798546a7fd557c82614a5c65a13df2157e9ad6373166d2a3e645d/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:7804338df6fcc08105c7745f1502ba68d900f45fd770d5bdd5288ddccb8a42d8", size = 210036, upload-time = "2026-04-02T09:26:54.975Z" }, + { url = "https://files.pythonhosted.org/packages/8c/bf/b3ab5bcb478e4193d517644b0fb2bf5497fbceeaa7a1bc0f4d5b50953861/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:481551899c856c704d58119b5025793fa6730adda3571971af568f66d2424bb5", size = 202998, upload-time = "2026-04-02T09:26:56.303Z" }, + { url = "https://files.pythonhosted.org/packages/e7/4e/23efd79b65d314fa320ec6017b4b5834d5c12a58ba4610aa353af2e2f577/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:f59099f9b66f0d7145115e6f80dd8b1d847176df89b234a5a6b3f00437aa0832", size = 230056, upload-time = "2026-04-02T09:26:57.554Z" }, + { url = "https://files.pythonhosted.org/packages/b9/9f/1e1941bc3f0e01df116e68dc37a55c4d249df5e6fa77f008841aef68264f/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:f59ad4c0e8f6bba240a9bb85504faa1ab438237199d4cce5f622761507b8f6a6", size = 211537, upload-time = "2026-04-02T09:26:58.843Z" }, + { url = "https://files.pythonhosted.org/packages/80/0f/088cbb3020d44428964a6c97fe1edfb1b9550396bf6d278330281e8b709c/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:3dedcc22d73ec993f42055eff4fcfed9318d1eeb9a6606c55892a26964964e48", size = 226176, upload-time = "2026-04-02T09:27:00.437Z" }, + { url = "https://files.pythonhosted.org/packages/6a/9f/130394f9bbe06f4f63e22641d32fc9b202b7e251c9aef4db044324dac493/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:64f02c6841d7d83f832cd97ccf8eb8a906d06eb95d5276069175c696b024b60a", size = 217723, upload-time = "2026-04-02T09:27:02.021Z" }, + { url = "https://files.pythonhosted.org/packages/73/55/c469897448a06e49f8fa03f6caae97074fde823f432a98f979cc42b90e69/charset_normalizer-3.4.7-cp313-cp313-win32.whl", hash = "sha256:4042d5c8f957e15221d423ba781e85d553722fc4113f523f2feb7b188cc34c5e", size = 148085, upload-time = "2026-04-02T09:27:03.192Z" }, + { url = "https://files.pythonhosted.org/packages/5d/78/1b74c5bbb3f99b77a1715c91b3e0b5bdb6fe302d95ace4f5b1bec37b0167/charset_normalizer-3.4.7-cp313-cp313-win_amd64.whl", hash = "sha256:3946fa46a0cf3e4c8cb1cc52f56bb536310d34f25f01ca9b6c16afa767dab110", size = 158819, upload-time = "2026-04-02T09:27:04.454Z" }, + { url = "https://files.pythonhosted.org/packages/68/86/46bd42279d323deb8687c4a5a811fd548cb7d1de10cf6535d099877a9a9f/charset_normalizer-3.4.7-cp313-cp313-win_arm64.whl", hash = "sha256:80d04837f55fc81da168b98de4f4b797ef007fc8a79ab71c6ec9bc4dd662b15b", size = 147915, upload-time = "2026-04-02T09:27:05.971Z" }, + { url = "https://files.pythonhosted.org/packages/97/c8/c67cb8c70e19ef1960b97b22ed2a1567711de46c4ddf19799923adc836c2/charset_normalizer-3.4.7-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:c36c333c39be2dbca264d7803333c896ab8fa7d4d6f0ab7edb7dfd7aea6e98c0", size = 309234, upload-time = "2026-04-02T09:27:07.194Z" }, + { url = "https://files.pythonhosted.org/packages/99/85/c091fdee33f20de70d6c8b522743b6f831a2f1cd3ff86de4c6a827c48a76/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c2aed2e5e41f24ea8ef1590b8e848a79b56f3a5564a65ceec43c9d692dc7d8a", size = 208042, upload-time = "2026-04-02T09:27:08.749Z" }, + { url = "https://files.pythonhosted.org/packages/87/1c/ab2ce611b984d2fd5d86a5a8a19c1ae26acac6bad967da4967562c75114d/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:54523e136b8948060c0fa0bc7b1b50c32c186f2fceee897a495406bb6e311d2b", size = 228706, upload-time = "2026-04-02T09:27:09.951Z" }, + { url = "https://files.pythonhosted.org/packages/a8/29/2b1d2cb00bf085f59d29eb773ce58ec2d325430f8c216804a0a5cd83cbca/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:715479b9a2802ecac752a3b0efa2b0b60285cf962ee38414211abdfccc233b41", size = 224727, upload-time = "2026-04-02T09:27:11.175Z" }, + { url = "https://files.pythonhosted.org/packages/47/5c/032c2d5a07fe4d4855fea851209cca2b6f03ebeb6d4e3afdb3358386a684/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bd6c2a1c7573c64738d716488d2cdd3c00e340e4835707d8fdb8dc1a66ef164e", size = 215882, upload-time = "2026-04-02T09:27:12.446Z" }, + { url = "https://files.pythonhosted.org/packages/2c/c2/356065d5a8b78ed04499cae5f339f091946a6a74f91e03476c33f0ab7100/charset_normalizer-3.4.7-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:c45e9440fb78f8ddabcf714b68f936737a121355bf59f3907f4e17721b9d1aae", size = 200860, upload-time = "2026-04-02T09:27:13.721Z" }, + { url = "https://files.pythonhosted.org/packages/0c/cd/a32a84217ced5039f53b29f460962abb2d4420def55afabe45b1c3c7483d/charset_normalizer-3.4.7-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3534e7dcbdcf757da6b85a0bbf5b6868786d5982dd959b065e65481644817a18", size = 211564, upload-time = "2026-04-02T09:27:15.272Z" }, + { url = "https://files.pythonhosted.org/packages/44/86/58e6f13ce26cc3b8f4a36b94a0f22ae2f00a72534520f4ae6857c4b81f89/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e8ac484bf18ce6975760921bb6148041faa8fef0547200386ea0b52b5d27bf7b", size = 211276, upload-time = "2026-04-02T09:27:16.834Z" }, + { url = "https://files.pythonhosted.org/packages/8f/fe/d17c32dc72e17e155e06883efa84514ca375f8a528ba2546bee73fc4df81/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:a5fe03b42827c13cdccd08e6c0247b6a6d4b5e3cdc53fd1749f5896adcdc2356", size = 201238, upload-time = "2026-04-02T09:27:18.229Z" }, + { url = "https://files.pythonhosted.org/packages/6a/29/f33daa50b06525a237451cdb6c69da366c381a3dadcd833fa5676bc468b3/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:2d6eb928e13016cea4f1f21d1e10c1cebd5a421bc57ddf5b1142ae3f86824fab", size = 230189, upload-time = "2026-04-02T09:27:19.445Z" }, + { url = "https://files.pythonhosted.org/packages/b6/6e/52c84015394a6a0bdcd435210a7e944c5f94ea1055f5cc5d56c5fe368e7b/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e74327fb75de8986940def6e8dee4f127cc9752bee7355bb323cc5b2659b6d46", size = 211352, upload-time = "2026-04-02T09:27:20.79Z" }, + { url = "https://files.pythonhosted.org/packages/8c/d7/4353be581b373033fb9198bf1da3cf8f09c1082561e8e922aa7b39bf9fe8/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:d6038d37043bced98a66e68d3aa2b6a35505dc01328cd65217cefe82f25def44", size = 227024, upload-time = "2026-04-02T09:27:22.063Z" }, + { url = "https://files.pythonhosted.org/packages/30/45/99d18aa925bd1740098ccd3060e238e21115fffbfdcb8f3ece837d0ace6c/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:7579e913a5339fb8fa133f6bbcfd8e6749696206cf05acdbdca71a1b436d8e72", size = 217869, upload-time = "2026-04-02T09:27:23.486Z" }, + { url = "https://files.pythonhosted.org/packages/5c/05/5ee478aa53f4bb7996482153d4bfe1b89e0f087f0ab6b294fcf92d595873/charset_normalizer-3.4.7-cp314-cp314-win32.whl", hash = "sha256:5b77459df20e08151cd6f8b9ef8ef1f961ef73d85c21a555c7eed5b79410ec10", size = 148541, upload-time = "2026-04-02T09:27:25.146Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/72dcb0921b2ce86420b2d79d454c7022bf5be40202a2a07906b9f2a35c97/charset_normalizer-3.4.7-cp314-cp314-win_amd64.whl", hash = "sha256:92a0a01ead5e668468e952e4238cccd7c537364eb7d851ab144ab6627dbbe12f", size = 159634, upload-time = "2026-04-02T09:27:26.642Z" }, + { url = "https://files.pythonhosted.org/packages/c6/a3/c2369911cd72f02386e4e340770f6e158c7980267da16af8f668217abaa0/charset_normalizer-3.4.7-cp314-cp314-win_arm64.whl", hash = "sha256:67f6279d125ca0046a7fd386d01b311c6363844deac3e5b069b514ba3e63c246", size = 148384, upload-time = "2026-04-02T09:27:28.271Z" }, + { url = "https://files.pythonhosted.org/packages/94/09/7e8a7f73d24dba1f0035fbbf014d2c36828fc1bf9c88f84093e57d315935/charset_normalizer-3.4.7-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:effc3f449787117233702311a1b7d8f59cba9ced946ba727bdc329ec69028e24", size = 330133, upload-time = "2026-04-02T09:27:29.474Z" }, + { url = "https://files.pythonhosted.org/packages/8d/da/96975ddb11f8e977f706f45cddd8540fd8242f71ecdb5d18a80723dcf62c/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbccdc05410c9ee21bbf16a35f4c1d16123dcdeb8a1d38f33654fa21d0234f79", size = 216257, upload-time = "2026-04-02T09:27:30.793Z" }, + { url = "https://files.pythonhosted.org/packages/e5/e8/1d63bf8ef2d388e95c64b2098f45f84758f6d102a087552da1485912637b/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:733784b6d6def852c814bce5f318d25da2ee65dd4839a0718641c696e09a2960", size = 234851, upload-time = "2026-04-02T09:27:32.44Z" }, + { url = "https://files.pythonhosted.org/packages/9b/40/e5ff04233e70da2681fa43969ad6f66ca5611d7e669be0246c4c7aaf6dc8/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a89c23ef8d2c6b27fd200a42aa4ac72786e7c60d40efdc76e6011260b6e949c4", size = 233393, upload-time = "2026-04-02T09:27:34.03Z" }, + { url = "https://files.pythonhosted.org/packages/be/c1/06c6c49d5a5450f76899992f1ee40b41d076aee9279b49cf9974d2f313d5/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6c114670c45346afedc0d947faf3c7f701051d2518b943679c8ff88befe14f8e", size = 223251, upload-time = "2026-04-02T09:27:35.369Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9f/f2ff16fb050946169e3e1f82134d107e5d4ae72647ec8a1b1446c148480f/charset_normalizer-3.4.7-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:a180c5e59792af262bf263b21a3c49353f25945d8d9f70628e73de370d55e1e1", size = 206609, upload-time = "2026-04-02T09:27:36.661Z" }, + { url = "https://files.pythonhosted.org/packages/69/d5/a527c0cd8d64d2eab7459784fb4169a0ac76e5a6fc5237337982fd61347e/charset_normalizer-3.4.7-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3c9a494bc5ec77d43cea229c4f6db1e4d8fe7e1bbffa8b6f0f0032430ff8ab44", size = 220014, upload-time = "2026-04-02T09:27:38.019Z" }, + { url = "https://files.pythonhosted.org/packages/7e/80/8a7b8104a3e203074dc9aa2c613d4b726c0e136bad1cc734594b02867972/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8d828b6667a32a728a1ad1d93957cdf37489c57b97ae6c4de2860fa749b8fc1e", size = 218979, upload-time = "2026-04-02T09:27:39.37Z" }, + { url = "https://files.pythonhosted.org/packages/02/9a/b759b503d507f375b2b5c153e4d2ee0a75aa215b7f2489cf314f4541f2c0/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cf1493cd8607bec4d8a7b9b004e699fcf8f9103a9284cc94962cb73d20f9d4a3", size = 209238, upload-time = "2026-04-02T09:27:40.722Z" }, + { url = "https://files.pythonhosted.org/packages/c2/4e/0f3f5d47b86bdb79256e7290b26ac847a2832d9a4033f7eb2cd4bcf4bb5b/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:0c96c3b819b5c3e9e165495db84d41914d6894d55181d2d108cc1a69bfc9cce0", size = 236110, upload-time = "2026-04-02T09:27:42.33Z" }, + { url = "https://files.pythonhosted.org/packages/96/23/bce28734eb3ed2c91dcf93abeb8a5cf393a7b2749725030bb630e554fdd8/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:752a45dc4a6934060b3b0dab47e04edc3326575f82be64bc4fc293914566503e", size = 219824, upload-time = "2026-04-02T09:27:43.924Z" }, + { url = "https://files.pythonhosted.org/packages/2c/6f/6e897c6984cc4d41af319b077f2f600fc8214eb2fe2d6bcb79141b882400/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:8778f0c7a52e56f75d12dae53ae320fae900a8b9b4164b981b9c5ce059cd1fcb", size = 233103, upload-time = "2026-04-02T09:27:45.348Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/ef7bd0fe480a0ae9b656189ec00744b60933f68b4f42a7bb06589f6f576a/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ce3412fbe1e31eb81ea42f4169ed94861c56e643189e1e75f0041f3fe7020abe", size = 225194, upload-time = "2026-04-02T09:27:46.706Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a7/0e0ab3e0b5bc1219bd80a6a0d4d72ca74d9250cb2382b7c699c147e06017/charset_normalizer-3.4.7-cp314-cp314t-win32.whl", hash = "sha256:c03a41a8784091e67a39648f70c5f97b5b6a37f216896d44d2cdcb82615339a0", size = 159827, upload-time = "2026-04-02T09:27:48.053Z" }, + { url = "https://files.pythonhosted.org/packages/7a/1d/29d32e0fb40864b1f878c7f5a0b343ae676c6e2b271a2d55cc3a152391da/charset_normalizer-3.4.7-cp314-cp314t-win_amd64.whl", hash = "sha256:03853ed82eeebbce3c2abfdbc98c96dc205f32a79627688ac9a27370ea61a49c", size = 174168, upload-time = "2026-04-02T09:27:49.795Z" }, + { url = "https://files.pythonhosted.org/packages/de/32/d92444ad05c7a6e41fb2036749777c163baf7a0301a040cb672d6b2b1ae9/charset_normalizer-3.4.7-cp314-cp314t-win_arm64.whl", hash = "sha256:c35abb8bfff0185efac5878da64c45dafd2b37fb0383add1be155a763c1f083d", size = 153018, upload-time = "2026-04-02T09:27:51.116Z" }, + { url = "https://files.pythonhosted.org/packages/db/8f/61959034484a4a7c527811f4721e75d02d653a35afb0b6054474d8185d4c/charset_normalizer-3.4.7-py3-none-any.whl", hash = "sha256:3dce51d0f5e7951f8bb4900c257dad282f49190fdbebecd4ba99bcc41fef404d", size = 61958, upload-time = "2026-04-02T09:28:37.794Z" }, +] + +[[package]] +name = "click" +version = "8.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bb/63/f9e1ea081ce35720d8b92acde70daaedace594dc93b693c869e0d5910718/click-8.3.3.tar.gz", hash = "sha256:398329ad4837b2ff7cbe1dd166a4c0f8900c3ca3a218de04466f38f6497f18a2", size = 328061, upload-time = "2026-04-22T15:11:27.506Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/44/c1221527f6a71a01ec6fbad7fa78f1d50dfa02217385cf0fa3eec7087d59/click-8.3.3-py3-none-any.whl", hash = "sha256:a2bf429bb3033c89fa4936ffb35d5cb471e3719e1f3c8a7c3fff0b8314305613", size = 110502, upload-time = "2026-04-22T15:11:25.044Z" }, +] + +[[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 = "coverage" +version = "7.15.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/be/c3/4f2195f512fb172aa425a8803a874b2baa9ba7f80ff7b6080998761fc701/coverage-7.15.4.tar.gz", hash = "sha256:0548198fff07ccf4faf469520bce1c2eceb1ce3e62891921138dec10907f9d00", size = 936952, upload-time = "2026-08-06T13:50:24.442Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1d/48/bc8d4ba7b37551a767bd863f15b3f80182b271c2f55975356f5f7dbe94c2/coverage-7.15.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d4fedd1f7f428f9fe83b1ead5e7cc87a43427be31aadafbac3ac0636dc7abb22", size = 222543, upload-time = "2026-08-06T13:47:37.562Z" }, + { url = "https://files.pythonhosted.org/packages/20/dd/88d6f83f1fffc974a3691a34a97951c5b12df7512a6782c5963883cbc058/coverage-7.15.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:37e2f0cdf58e2e1fed4e4d5a8f8786ae2f7eb80b478016876667dc4a01d60a97", size = 222905, upload-time = "2026-08-06T13:47:38.927Z" }, + { url = "https://files.pythonhosted.org/packages/bd/5c/54ee0d4748585bb0acab9891cd8d92f2d3593165b4e59fc9de113bfb3140/coverage-7.15.4-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fb55d0e70bb15f2e81477613627286581414693d74ac7963c93a790dd453ca9d", size = 254407, upload-time = "2026-08-06T13:47:40.488Z" }, + { url = "https://files.pythonhosted.org/packages/8c/3f/f0642a372f494bd0d7dad3b497083b910194a5f1c88be2c94fef707c3b59/coverage-7.15.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:899b9da30f3c6c336566e3707495bb23e8302d39d862f01fa78c48b99b9437e2", size = 257145, upload-time = "2026-08-06T13:47:41.931Z" }, + { url = "https://files.pythonhosted.org/packages/71/17/8b46d0ed68251016002ec972c8fc0119961a765d0984cafb8bf317c43758/coverage-7.15.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d15715e8c46552827e5e4f30a35575a2dbcad14454cf3284c54483946bd16931", size = 258257, upload-time = "2026-08-06T13:47:43.527Z" }, + { url = "https://files.pythonhosted.org/packages/30/b8/8498a0e72d0adbe15477dd07463d2b3bb2c9f6a4815e8589e50939e2c3ae/coverage-7.15.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:002a438859f7b430bc99afeaf01a6d187dad1d0dc907b64cdeffc632a5db8fd8", size = 260517, upload-time = "2026-08-06T13:47:45.121Z" }, + { url = "https://files.pythonhosted.org/packages/41/e1/7dce19c3bdb1e3dd63e769508216500edad81bd5f69a26d724e32aceaf78/coverage-7.15.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e4193a04b518f7968f3099755f5509ee7cccc6dc2b92a6b14841934d22e222c9", size = 254785, upload-time = "2026-08-06T13:47:46.541Z" }, + { url = "https://files.pythonhosted.org/packages/dd/b1/e1494703c675a2561723cd9b89f45c9168782c31280c611b1f767851e57c/coverage-7.15.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e98dcc55d572b38e69d117da7e8e8efb8500f1f5eaf81ecd460a63220790b839", size = 256176, upload-time = "2026-08-06T13:47:48.155Z" }, + { url = "https://files.pythonhosted.org/packages/73/76/a5629d270fb638a43a4b10466f51e2f49d532c1aa4da2913cbbb150bbe0a/coverage-7.15.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:af6c538498ce66c10d3fd541c2a8d5b03da5850355add34e6cba564210cb9e72", size = 254321, upload-time = "2026-08-06T13:47:49.757Z" }, + { url = "https://files.pythonhosted.org/packages/ff/4f/9c44447218435d5766b911534f9d798144a5560f85e9a54ebe5f3f5d19f9/coverage-7.15.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1d10025d96ea89fc2f73714dbc4cbd433fe012c1ac9e23f895d7728b238b6e52", size = 258390, upload-time = "2026-08-06T13:47:51.248Z" }, + { url = "https://files.pythonhosted.org/packages/de/36/c1e127616fb3fa18a9ff71e76c417f2fd7424332a4870015ac224ef4c039/coverage-7.15.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d802e1947603162ded419bff83ac7489820355d2b856dfb09206574e3a37ac0c", size = 253894, upload-time = "2026-08-06T13:47:52.816Z" }, + { url = "https://files.pythonhosted.org/packages/e9/b9/fdb92c8ae7a8bb9b850cc253b7b3b9c8526f68130002048b5671cd510d09/coverage-7.15.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c2de40895718f91951b86712b4c5b694acaf9a0a49be13874896f599a1eed3f4", size = 255763, upload-time = "2026-08-06T13:47:54.296Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c0/a7d51b2587c7bdb76e71b0896d2565bf7d60436b5122fc83e511adb1f7cd/coverage-7.15.4-cp312-cp312-win32.whl", hash = "sha256:5c3431b2161279b7db5c2a1aa58ae02e5cb8c3c42d93a5094be3f5537bd5b11b", size = 224597, upload-time = "2026-08-06T13:47:56.074Z" }, + { url = "https://files.pythonhosted.org/packages/49/b9/5c5f80cc55f5acaaca6dee677626bfcec8c87204a7809b438b08e84f4571/coverage-7.15.4-cp312-cp312-win_amd64.whl", hash = "sha256:6befeab5fb2b51c958ca4ac6c5d141a1e8240f4f76e46350f1911963deda49cd", size = 225135, upload-time = "2026-08-06T13:47:57.52Z" }, + { url = "https://files.pythonhosted.org/packages/47/e4/2a4561f89ff6bf7c925c287d0f2cce8bdf139c3a33735c87e3203401cf94/coverage-7.15.4-cp312-cp312-win_arm64.whl", hash = "sha256:67bc345491ab55b837277d76f5775d057e8c7f1ac44d890d8c2c82adde258c6f", size = 224515, upload-time = "2026-08-06T13:47:58.977Z" }, + { url = "https://files.pythonhosted.org/packages/f1/84/651a9310859673aaa3b3203f1aa1641ca60fcf2494683e1c9474c7172780/coverage-7.15.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c705b28feb2775dc82a25f1d473a370bc37ff93f5177f4e29ce2425f560f6921", size = 222565, upload-time = "2026-08-06T13:48:00.796Z" }, + { url = "https://files.pythonhosted.org/packages/82/f9/4dcf700137e8af550670f4d74d1b63828ce93e1e2b05e5f10710eb2ea987/coverage-7.15.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3ff205ab5e3ecc670f6a4dd19d9cbf12ede53dd41cfc1e15716ec961ea6d314e", size = 222936, upload-time = "2026-08-06T13:48:02.391Z" }, + { url = "https://files.pythonhosted.org/packages/07/4a/612ff1e780b3fbfd637486f542f84adc5503873d8b5d279dec1ffeef9414/coverage-7.15.4-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5172326e861a38b48b48befca15e0f477a26b283337a33a739c8fed229934e36", size = 253926, upload-time = "2026-08-06T13:48:04.382Z" }, + { url = "https://files.pythonhosted.org/packages/b0/04/d1cff1c2ead4708a6a79c01d3736b6a25bd38a36678398f72a8dd33dfad9/coverage-7.15.4-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:12b59c90084e3234fb11184886bf4a40f4f16a8c8f867be2e087b81f8e8868d4", size = 256523, upload-time = "2026-08-06T13:48:05.996Z" }, + { url = "https://files.pythonhosted.org/packages/b9/80/d34e13fb4b293cbdb9665838cf5522077b8ad14ef947550631a4bced36a5/coverage-7.15.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:349062d66f00b40fa2c1c222438bad25fabf755631b5d82937fe985c8008615c", size = 257759, upload-time = "2026-08-06T13:48:08.036Z" }, + { url = "https://files.pythonhosted.org/packages/0f/e7/2c5fe7636fdb0732fe0f09f308a5b066864078b7fc61f6678e8478554f2e/coverage-7.15.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4256ced708e598e05209bc1a8ab4074e04a51dba4c62fb45926a229af675ace7", size = 259890, upload-time = "2026-08-06T13:48:09.834Z" }, + { url = "https://files.pythonhosted.org/packages/92/28/9689f0858dfff59c2ea688938ab9fa2925631235df67126a42b6c5c70ae1/coverage-7.15.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d80f974b20782d9612c8b4c9beeca867074c7cf4079d1419843fa25a26428b25", size = 254121, upload-time = "2026-08-06T13:48:11.459Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e2/785077c230c157243eb5aa9a26c3be260ecd02001bead54a3cada3df8e03/coverage-7.15.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2e179f19bfe1d31f8eeeaa12990194d761c4f62f0759661000bca6cd8729f40b", size = 255891, upload-time = "2026-08-06T13:48:13.209Z" }, + { url = "https://files.pythonhosted.org/packages/d4/90/e20371b17b40f912f21305c2db2f30efa3de306f7320fc916804872c85a4/coverage-7.15.4-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:8bc16bb47b7679670eceff71d78bfb7d6e5b143f6c2cd117487ec7c75e0d4b78", size = 253859, upload-time = "2026-08-06T13:48:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/05/49/25371987ee459a5f67c0427fb75c74f9358e65f2c71fe75bf41c1b6c5fcb/coverage-7.15.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1cd685005cd2c4200adfc14cf39a603b9320efab3f18a8f7f156d20c9cc3345f", size = 258011, upload-time = "2026-08-06T13:48:16.464Z" }, + { url = "https://files.pythonhosted.org/packages/30/6e/32e67467f6154bf4f1c4f63b05acc5097cba4237d45bbeeea446b52e8ac1/coverage-7.15.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:337399ad2c93b3acd2a937627dae8b3e86b66707cd3d3e856347999aadf1ef8d", size = 253676, upload-time = "2026-08-06T13:48:18.493Z" }, + { url = "https://files.pythonhosted.org/packages/03/c1/8b24192e89286399765155251f99ee9f070a9d637109018ac23d99b99f6f/coverage-7.15.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:96e257121228ec5cd2bb919276e94ac11074471bc37d68dbae0e8308cce15fff", size = 255453, upload-time = "2026-08-06T13:48:20.057Z" }, + { url = "https://files.pythonhosted.org/packages/16/6f/8b41ebdf67c87854e17c035336a90f1cfbad0c14c2a584301be6ff148718/coverage-7.15.4-cp313-cp313-win32.whl", hash = "sha256:c65a9e0dfc6143491879da4e13b5e30f8be192055de508d737fb14601edbd22c", size = 224605, upload-time = "2026-08-06T13:48:21.655Z" }, + { url = "https://files.pythonhosted.org/packages/e0/e2/2946c7f0b42b152ecb21ff1bdad72e3d301e790c0c487e4a86e8c9f69347/coverage-7.15.4-cp313-cp313-win_amd64.whl", hash = "sha256:2ff8f5e9b8f7a94f0c11c45631eee103dbcb7d63274edd12c56efe1be690b3b4", size = 225148, upload-time = "2026-08-06T13:48:23.376Z" }, + { url = "https://files.pythonhosted.org/packages/9e/83/3f4a69957f48ae7a0aba76c34743f88963d607b19e03f3f8e66f91cae0f9/coverage-7.15.4-cp313-cp313-win_arm64.whl", hash = "sha256:6e0a8a5083b096487d6cfced94cdd514d8f5db6f113610fb36c0620edb1028cf", size = 224536, upload-time = "2026-08-06T13:48:25.117Z" }, + { url = "https://files.pythonhosted.org/packages/ea/ac/748cf29eeb2d6be34a3176ce26a4f49e38085ee08e8935f05f6f26ed7e0f/coverage-7.15.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:770e9325ab5ea6d56f77e59b29ecfe0ac20b57a82a601876f90494a4dda0386f", size = 222608, upload-time = "2026-08-06T13:48:26.806Z" }, + { url = "https://files.pythonhosted.org/packages/0b/02/1abbf5c984677b0aa439cdacaccbf38d248939d8ef8fe1cc7a50d73edb77/coverage-7.15.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d12b33a3a50a1676b7784dc8d00a0c6d66a9f2add4b85a041c19b6a7e53ef23c", size = 222940, upload-time = "2026-08-06T13:48:28.432Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e1/ff8f9f53d9fcf586125b55d0b1f04ec1c14955fee41e83d5814bee141bb5/coverage-7.15.4-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5669c8378ebde86f5def7a25d29586631b58acc27ffde04399f678f3dfc6e082", size = 253985, upload-time = "2026-08-06T13:48:29.995Z" }, + { url = "https://files.pythonhosted.org/packages/a1/26/595759762e514e81be1d7d01ed03444303bcd152226a6529998d253f9201/coverage-7.15.4-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ff97a14362eef486483ed44042ca2027ea257df6ff768e62358ee0c9776925ac", size = 256492, upload-time = "2026-08-06T13:48:31.634Z" }, + { url = "https://files.pythonhosted.org/packages/24/68/b79aabac54d482be23b5fcdd4f4662bff24a78edc4ee29201726929936d5/coverage-7.15.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5a325e815318638aed1655d9c06e6d7c2d3d46c09231ce988070428a8762d734", size = 257837, upload-time = "2026-08-06T13:48:33.186Z" }, + { url = "https://files.pythonhosted.org/packages/09/0f/bf7f297885a5bf6fd71e5782404e0ff059ca09e8711ceb3a08544abde45a/coverage-7.15.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:474223409d88eb20d2d6a0d37ea60e8647a65a90cc008dc1f0410af5f64f1e0d", size = 260152, upload-time = "2026-08-06T13:48:34.75Z" }, + { url = "https://files.pythonhosted.org/packages/fd/f1/296744e854ff8368542343457414380465e9ceefb9192342feb9d3bc461d/coverage-7.15.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7f2f62ae3cd189dd2e13aece758c57b3eecbd27be070dbd4cbd10936049e5dbf", size = 253978, upload-time = "2026-08-06T13:48:36.434Z" }, + { url = "https://files.pythonhosted.org/packages/55/b0/bbdb2e9057493e66220a2e149ca2d301ba0e3a58a83bd6b90de9826d16f3/coverage-7.15.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:39ece820e29e0a2ba34b3ecb3be83c27e997eed8926f2ba6fe7ce7a0bda5843b", size = 255846, upload-time = "2026-08-06T13:48:38.317Z" }, + { url = "https://files.pythonhosted.org/packages/96/e4/38015b2b6d21258713bd17e76b59d033b191efb5703589cffd037dfbca20/coverage-7.15.4-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:f21b56dcace11dfe013014201f577dcd592b2a9b72182d930361b47cf6f73f25", size = 253808, upload-time = "2026-08-06T13:48:39.993Z" }, + { url = "https://files.pythonhosted.org/packages/0b/64/0d515c1e60ee6fbfd1a0e79c07cd87d388a233b7adc37758735677203808/coverage-7.15.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:93a3a0b662abcc10c73a47cbc72cd60f63618d6989fb2d1286e50eacd974f303", size = 258081, upload-time = "2026-08-06T13:48:41.971Z" }, + { url = "https://files.pythonhosted.org/packages/91/71/04d9e7a3642146c6351338aef4ef85ab11dbbb54744c13245caba1aad1c0/coverage-7.15.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:141fae2cabf5569b782c10afc4c850ce10f618c13f8db54765cba99cc839da1f", size = 253624, upload-time = "2026-08-06T13:48:43.731Z" }, + { url = "https://files.pythonhosted.org/packages/b4/a7/6c28b74c81ebff66987b0e2522ba5cffa3e90b0c33cb6a2eb264d4ee8cf1/coverage-7.15.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:81294c7e6ab30c5f74c0353b11b2fd6320e72d9bee6ac73b357caa8b916323a5", size = 255280, upload-time = "2026-08-06T13:48:45.58Z" }, + { url = "https://files.pythonhosted.org/packages/52/af/bc19996a7014b98d7bbb0f0939453c67074af65784a3aa16a789a07381fa/coverage-7.15.4-cp314-cp314-win32.whl", hash = "sha256:7bbd7d6418e0dab31a206af5203bd43ae36edb8e7fba1940b055d3e9249290d7", size = 224768, upload-time = "2026-08-06T13:48:47.525Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/219484e476d6e101ba0a444852579e05f5b75c37c611a42ed1190f73ef62/coverage-7.15.4-cp314-cp314-win_amd64.whl", hash = "sha256:f0204ed122758782970526057093f448051a39db9d810d4e344bb87a3546f425", size = 225259, upload-time = "2026-08-06T13:48:49.513Z" }, + { url = "https://files.pythonhosted.org/packages/b7/66/fa77daf4e383e5f776dac62c2409b6af81910ae6fe326bd5170dba74cc63/coverage-7.15.4-cp314-cp314-win_arm64.whl", hash = "sha256:9e71e7bc71c686a123347ae47a0de33a175e797a85bb57b791492adf4eec8ed8", size = 224684, upload-time = "2026-08-06T13:48:51.235Z" }, + { url = "https://files.pythonhosted.org/packages/58/5b/f03bf0ce362bbf3f785fa5219620d00778d4ac6fc9e407734828e9c672f6/coverage-7.15.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7c922735321eef3f87c280a3d39afff6b646723a2880b862cda4ac7a093b8aa8", size = 223338, upload-time = "2026-08-06T13:48:52.896Z" }, + { url = "https://files.pythonhosted.org/packages/0f/76/e77d0ae22501831cc9f92193e8a957a5caa1dd177f90a6d1d9b106242d92/coverage-7.15.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f41c17c4668a655ce96d090d8d5ffdc24ef64b5a02f9753884d08483e8a4a41a", size = 223609, upload-time = "2026-08-06T13:48:54.688Z" }, + { url = "https://files.pythonhosted.org/packages/82/1a/b1f089da8d38ac612fa2dd6dc7f4a1a7657d12f3e261d2996edd3a838d0b/coverage-7.15.4-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:46822e9b6ff1c6a72b518c162c44a8f45a61a1d609c51084bf5b16c023c5037b", size = 264970, upload-time = "2026-08-06T13:48:56.403Z" }, + { url = "https://files.pythonhosted.org/packages/bf/31/e66d98d6e9c7fcc88470f1e234eaf6b1950dc0dfbf797f7282c1c861da24/coverage-7.15.4-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3d6f4955b73b5445271379a59e3792b0d978f42d4a01e0cf7a67d9c33a3bb0a5", size = 267088, upload-time = "2026-08-06T13:48:58.41Z" }, + { url = "https://files.pythonhosted.org/packages/59/a1/ae94eb2c541add426378408379f233591e069040b1e2cdb33df9498a0682/coverage-7.15.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3fc9e047706fb4a9abb54f719d3aa643e80e5bb3818182c40aee01ac0f0247ba", size = 269508, upload-time = "2026-08-06T13:49:00.42Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c7/88a10694a1c6a213569766aba9f25847b28155d4ac731b13226db216356d/coverage-7.15.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:05e491d4f3165d62d4f5c8fd48dfeabf2ae8f42cbbd484319af33ea851b78982", size = 270629, upload-time = "2026-08-06T13:49:02.234Z" }, + { url = "https://files.pythonhosted.org/packages/b3/34/d8b8232e5e55169933b59aabcef2fedfa4b9d8897361bb80fcbda146505f/coverage-7.15.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:226c66e80ec0598d3b9b4874123df167ccca342aca8714f77cac6829688ee09c", size = 264043, upload-time = "2026-08-06T13:49:04.102Z" }, + { url = "https://files.pythonhosted.org/packages/7e/35/58b009dbf8c471c7224716478b9fed4a7e1af15320e1ed41660978504663/coverage-7.15.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ac41cc14bebda0dbfb0628036b7f75706935c95bcc07fefe9a0f93614aa60a57", size = 266963, upload-time = "2026-08-06T13:49:05.821Z" }, + { url = "https://files.pythonhosted.org/packages/62/aa/57fbda1b42c892968273c56b6ee9dc0f1310850859230a507bc7873b1f65/coverage-7.15.4-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:8af623e5cd92080acddd02b38f2f406a2c3a0893c38950b211890361448fbf26", size = 264569, upload-time = "2026-08-06T13:49:07.706Z" }, + { url = "https://files.pythonhosted.org/packages/98/8a/360e6e7f24d477b7e889703af0afa878d15b6d4d8d2a822b2835c169a879/coverage-7.15.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:07545711d4f0f32852a18f18ad11f76f0109909d09e78b9008b4cfc67e829429", size = 268299, upload-time = "2026-08-06T13:49:09.587Z" }, + { url = "https://files.pythonhosted.org/packages/4e/89/6f701261aee21b6b5fa8f7872229406dc917e125069448292223bf213606/coverage-7.15.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:a0865421cfdc53654b342d515e5a233187590882d20b95752150e53f65460017", size = 263413, upload-time = "2026-08-06T13:49:11.604Z" }, + { url = "https://files.pythonhosted.org/packages/3f/0f/6f04036edc260ed425af83e834f627fad48941ce97b50bfe6edd8b6fa623/coverage-7.15.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:460115e32ee40566476db5048f9bec1e842c127ad8e6f8be745aad3ac9cbc839", size = 265725, upload-time = "2026-08-06T13:49:13.38Z" }, + { url = "https://files.pythonhosted.org/packages/c4/ce/d19b5d4d5c49a7bfb925fd74310fee7d28bc99520ac3367ccbc54e662518/coverage-7.15.4-cp314-cp314t-win32.whl", hash = "sha256:cbde877ef9dd7baf272b9bfef2b8a25edd45d9170fc326951dd20eb480335e85", size = 225079, upload-time = "2026-08-06T13:49:15.265Z" }, + { url = "https://files.pythonhosted.org/packages/26/bb/7aa1b3b173faee0679037ca950bbbe1247273656697994d8d13f80f8d4b4/coverage-7.15.4-cp314-cp314t-win_amd64.whl", hash = "sha256:3da9e92d1c551fd7563833e9ade686efb0c4b7363ab7681a94283958c950bf5e", size = 225911, upload-time = "2026-08-06T13:49:17.279Z" }, + { url = "https://files.pythonhosted.org/packages/81/1c/4ea9e47426d80038d9222db3c4534cb6021a74b237d3ff97ffd33b6600dd/coverage-7.15.4-cp314-cp314t-win_arm64.whl", hash = "sha256:3a54f5a0d85050c73a38f6793090ee83974531e67fe5e57a1da9bee11398aa5e", size = 225219, upload-time = "2026-08-06T13:49:19.293Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c4/dc5d2ac8f9142e7ec7de66e7bf0591db29d78955a040bd915870d9c0e657/coverage-7.15.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:2c9872e4d9dc5d3cf616bf4b382f5a00359305a5be666a3dd0b5cdb4e49597f9", size = 222604, upload-time = "2026-08-06T13:49:21.279Z" }, + { url = "https://files.pythonhosted.org/packages/70/39/33e63df81fe2ee100897451841c821467635923e58e37c6bd4b46dd8106c/coverage-7.15.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:e101dbb4b9b72f0cddd8cdc8c9c5b47f456766f5e0ac82dbfb75e5c55409b78a", size = 222944, upload-time = "2026-08-06T13:49:23.187Z" }, + { url = "https://files.pythonhosted.org/packages/99/1f/ef3ffb5557febc75a0d97aa459d0266d7d741110265121cc6d8539343d44/coverage-7.15.4-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7d1abebdb047729e852b9c77a00497dfbeb11eb3a117e037d7dbc3ac8e5f5c54", size = 254050, upload-time = "2026-08-06T13:49:25.008Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f5/1f0f6f77698c3601ca0ae7431e34b24c62ca2f06fecb23b73ed1f651d2be/coverage-7.15.4-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d28a4a899354d0ea6214cc59b4fa19eefbce1b9ff1688ab579acf49e894bd3fb", size = 256967, upload-time = "2026-08-06T13:49:26.896Z" }, + { url = "https://files.pythonhosted.org/packages/03/7a/2ed9bed79925f4367c83c77f66a89e5ca7229c288d2d19ad5f36d1ca0070/coverage-7.15.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ffb3c2aacea411cc7e1d27712490c11108e2de1d39019ae32915493a59a8b9ed", size = 258587, upload-time = "2026-08-06T13:49:28.692Z" }, + { url = "https://files.pythonhosted.org/packages/45/8c/fa34044f71b7cc4ecb6da9c2408770959b0591fa9b5fb6fb6bca38f94298/coverage-7.15.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a9447978a92f405d301123cfd39ff49895490efb769a758fe2734c7f631bf8ce", size = 260785, upload-time = "2026-08-06T13:49:30.472Z" }, + { url = "https://files.pythonhosted.org/packages/4f/54/d5727ce36b4524a7394ab9f5f1df378e1f23affcdab01037dc8655185cc7/coverage-7.15.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:050467a7983b8e2fe7dd41a78bb30c3e7f8c0b8cafda14b1c46f8b5e3cf2dd3c", size = 254545, upload-time = "2026-08-06T13:49:32.271Z" }, + { url = "https://files.pythonhosted.org/packages/dc/e6/6e3783e576719590194bdffb6dd6d85490801785b7c331e35a245d8cb8b5/coverage-7.15.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:d003b7a5708ddad5c206c79607a6b92abb6fc13c57d99d8a4468cc03a2941ced", size = 256682, upload-time = "2026-08-06T13:49:34.089Z" }, + { url = "https://files.pythonhosted.org/packages/dc/f2/bacdbde18b69ed2de424fcf64d9fb0a4913753d4f0eca8bae9daad69f4bd/coverage-7.15.4-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c38efe30fd74e5c19e9433f11fb1f5dc9c6522770971b7c6145bbaa413dc8800", size = 254560, upload-time = "2026-08-06T13:49:36.052Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a3/1fb927196e3477c1b48831169ab58ba08f451ba87ae311ff1de68b26a616/coverage-7.15.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:1f4f826d70f772ab8b0c052329580d7fe8b8abd191e4ce0c8f81aec6614665d3", size = 258792, upload-time = "2026-08-06T13:49:38.01Z" }, + { url = "https://files.pythonhosted.org/packages/41/58/30d4c149c69053de0edfe325614c1d28d508f62b1783e0e4a234d2e49136/coverage-7.15.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:4a4bf917c9953f57c957be31c1cd504e3bd2f34d4a352b9d391a3025336f6768", size = 253968, upload-time = "2026-08-06T13:49:39.934Z" }, + { url = "https://files.pythonhosted.org/packages/89/e4/77f639371b918aad30dda4051f95404b43578f7f2e2f87ba73e02ed1ff37/coverage-7.15.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:1c9bf40ebef178a45192c75c4964760bb261b0e6ad725da5fc4c93f674f19753", size = 255893, upload-time = "2026-08-06T13:49:41.825Z" }, + { url = "https://files.pythonhosted.org/packages/5c/62/13be29b3ddab35f14c87967a4820a05106d2a3eccb4fa4ff550bf30b75e0/coverage-7.15.4-cp315-cp315-win32.whl", hash = "sha256:43619d04c3671792d2c4706ae8bf45e265dc87bbd4078189ef8b847ea1e74be2", size = 224768, upload-time = "2026-08-06T13:49:44.08Z" }, + { url = "https://files.pythonhosted.org/packages/a1/70/af0c6be0f964af6954f6b74bc109b0dbca02824696d2520fb17fe1ab06e3/coverage-7.15.4-cp315-cp315-win_amd64.whl", hash = "sha256:be619439dbcd31a2eab10b32de9fff62c26ed4bab69dc32b8363fdaaa0882809", size = 225242, upload-time = "2026-08-06T13:49:45.899Z" }, + { url = "https://files.pythonhosted.org/packages/4f/2d/f3bd3aab899fc9efc18b53133ee68f5f98574ef480649b23e12962226387/coverage-7.15.4-cp315-cp315-win_arm64.whl", hash = "sha256:def597967dafc2e8d97c9097ea453c464e0bb8ed38f193a43070f10dc623bb6d", size = 224674, upload-time = "2026-08-06T13:49:48.322Z" }, + { url = "https://files.pythonhosted.org/packages/f5/ca/f69251cd63eabc6438321aea22148754cce758a26bde07dd490e3fe7cfc5/coverage-7.15.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c7dbc748ac8a1e3e59a2b28bea47675e6e778081dbbf081bde0d75def2fcbe1d", size = 223333, upload-time = "2026-08-06T13:49:50.293Z" }, + { url = "https://files.pythonhosted.org/packages/a7/a7/037b53b2885b0d8447064432491a4d5a1014cd9f97a594d53acd0c04541a/coverage-7.15.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:2413074a5ecbb61a01a7888fc72db0ca324d13588c5b38bc0dd8564cdcdfea26", size = 223630, upload-time = "2026-08-06T13:49:52.637Z" }, + { url = "https://files.pythonhosted.org/packages/80/4f/152b8a4779ae90da11bb24f7467df8a59f0be48a5c52acb856325ca48289/coverage-7.15.4-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4e6f6f632b7b2f714bf7a1346e8f97b650ee71f3c298aaad42a2ab60f0f07645", size = 264489, upload-time = "2026-08-06T13:49:54.52Z" }, + { url = "https://files.pythonhosted.org/packages/10/2d/84b4b9e0e1dd6528a51920ff7031f35b789382e467a28ec6a5a578cb8812/coverage-7.15.4-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8df457da2249d3c75ca2e5e835d59c725abfe92d27fdff6cd99eed85b51d5e9a", size = 267567, upload-time = "2026-08-06T13:49:56.721Z" }, + { url = "https://files.pythonhosted.org/packages/53/fc/ba01cc25299f9f8a2c8b02d3b28c53f3543d9fbfbe4e74fa2760b48f163e/coverage-7.15.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:050f66a08805acb5b8a23c6d4a517b1ecf82c08e81ed0e4bd727df065e5c6624", size = 270123, upload-time = "2026-08-06T13:49:58.736Z" }, + { url = "https://files.pythonhosted.org/packages/cf/d0/db2647cbf40b14f8c308f94ff7bf89c06d564e59f396906edf50086ec788/coverage-7.15.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1587fb771d1ccceef708fdde1e5af8c7ed24b486b61d13a321acb7d8145390aa", size = 271107, upload-time = "2026-08-06T13:50:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/70/ff/4d2d17924552c458bb4f77dd631f0e3bc92fbbdf2d2d916cd4b33bbfd5b1/coverage-7.15.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8b4f1c3a69ca580f3fbd6b2046915f536d7f586874f25c1bb23add2a3c88d50f", size = 264955, upload-time = "2026-08-06T13:50:03.023Z" }, + { url = "https://files.pythonhosted.org/packages/ee/de/dc010c7a3691f396d93bbc26bfcafa1c2a3a351cd520470f15faf5795bd5/coverage-7.15.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:ffb58d7eff5b7f6ecc6fa21d6288ab7f968a212cb67d682c269c09b9eba3b66f", size = 267949, upload-time = "2026-08-06T13:50:05.557Z" }, + { url = "https://files.pythonhosted.org/packages/78/ea/dc96a11375e83c045c2f7c61fb6918277cfe9401db7c0f7b1d111a84b2e5/coverage-7.15.4-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:d9df165544774574ee004b953023d1bebada1894a80b1052a43d798b0f676e67", size = 264421, upload-time = "2026-08-06T13:50:07.612Z" }, + { url = "https://files.pythonhosted.org/packages/c8/86/b77131a0f9503ce461cd577076147d7a9040f0c5dda772686f729e2cc9cb/coverage-7.15.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:f9de0a24a4079b53e523b5c5e2c5945ec251ab486652659955187cf255a259bc", size = 269121, upload-time = "2026-08-06T13:50:09.58Z" }, + { url = "https://files.pythonhosted.org/packages/24/24/944bc35007862955e7ebf05754e645419dcf5d7526c52735cfa2715e8ebf/coverage-7.15.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:150089274bdc9f940628552cb92844e0223c987f1902ab8efe9f45a2ec758d88", size = 264565, upload-time = "2026-08-06T13:50:11.722Z" }, + { url = "https://files.pythonhosted.org/packages/c7/cc/a3bb9f93e7e740659163e2ea584f8196ddcd2c456a5dbe15f6c50105fec1/coverage-7.15.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a58a94fed5da6997d258e8f7668c1e195fbd04a691d781b7558f1e468f9e68bc", size = 266522, upload-time = "2026-08-06T13:50:13.786Z" }, + { url = "https://files.pythonhosted.org/packages/49/dd/e0e40f3560d878d888c580698ff5ad1179f5e1c3ac949684ef66b41a3817/coverage-7.15.4-cp315-cp315t-win32.whl", hash = "sha256:ebd5a6d8466ff30836572f3ba2cae8a5e8f85029b1c6d5e2ed338dc472a5166a", size = 225068, upload-time = "2026-08-06T13:50:15.825Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7e/37732ea80eebc30e976e4cdab15c190bc42d96959a42e38ddf6f8c60468f/coverage-7.15.4-cp315-cp315t-win_amd64.whl", hash = "sha256:288bde2a2d7ab6b6c2d7252fcde8b524387f2d970bdba9658fc6f8bbcaef0f9b", size = 225895, upload-time = "2026-08-06T13:50:17.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/08/1e00f7923eaaba45fb3d51dd794125fc766304b1df264f3a9c6557bfb30e/coverage-7.15.4-cp315-cp315t-win_arm64.whl", hash = "sha256:68be5e1de60ff13c9095bbec0e5a7fa45b33b101752215b91345ea1f61c4a278", size = 225213, upload-time = "2026-08-06T13:50:19.981Z" }, + { url = "https://files.pythonhosted.org/packages/b4/d9/e70c286c979378f061d8266e279b686ab0b0b688e1fe0af864684f23a77d/coverage-7.15.4-py3-none-any.whl", hash = "sha256:964730a1e9de9c0cf11be6a1a3c79ce419c34882842abd256086ba4698705e84", size = 214332, upload-time = "2026-08-06T13:50:22.192Z" }, +] + +[[package]] +name = "cryptography" +version = "50.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/de/41/6cbdcf9142d00fe82836fbb51e503e58088575cf7a0fe1dbff6695bf0840/cryptography-50.0.0.tar.gz", hash = "sha256:eeac2acb5a20ed25e0ad6d1df9891a520b78b404266b6d11778f25d5d691a6c9", size = 880201, upload-time = "2026-07-31T14:25:10.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/5c/59086b4aac5e879d38ddbcf74e4be7ade89cebc3eb199a55da998c3bb46a/cryptography-50.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:031e2d5dd4bb9caa3ca9c82e5a197fd8ae680232cee62603d1a813f3f07e3d03", size = 4001252, upload-time = "2026-07-31T14:23:33.331Z" }, + { url = "https://files.pythonhosted.org/packages/57/ef/8f2df13c7216bcad3e1c74e07f6e193d93e998e114f524a53877c9af27ad/cryptography-50.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fd9192b7b70c573d7f214eb1ae35e00d359f6f5e4b27c7e21e30de1fc6204645", size = 4719554, upload-time = "2026-07-31T14:23:35.611Z" }, + { url = "https://files.pythonhosted.org/packages/d9/41/029086c34d91052fc3b88bcc8056f709a7c915c7a23b235a54eb800b1c97/cryptography-50.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:06a32a980526a6ab9a4b9bf8f7385800791e2bb960903cb6b530e4817509a3b7", size = 4702130, upload-time = "2026-07-31T14:23:37.635Z" }, + { url = "https://files.pythonhosted.org/packages/7d/ff/b6ce0954962e7f7b969f850a883744197bb3910bdfd7b6da162eab7d9f68/cryptography-50.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a1b30560f2acc95aa8b2e06e716a13dbfc97314747b80d9707e307f77b40d6b3", size = 4725244, upload-time = "2026-07-31T14:23:39.471Z" }, + { url = "https://files.pythonhosted.org/packages/06/1e/63a1027cb7fec360a182208e1b7767d5aa1fe57be3d6aa856e69a321edc0/cryptography-50.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:8d89f3976b10b4ce31118de72329025f70d2c6ead14a8217c5514dd2c6d5a78f", size = 5342265, upload-time = "2026-07-31T14:23:41.286Z" }, + { url = "https://files.pythonhosted.org/packages/6b/72/a1116d683a6d7ece94590013882515de087edf9ef0e6292aae615a44df73/cryptography-50.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b42a28c1844fd9de8f3f7d540e36b66f3a9c83fceac7170ebc7a6a19edd9dcae", size = 4734609, upload-time = "2026-07-31T14:23:43.139Z" }, + { url = "https://files.pythonhosted.org/packages/15/37/36a9c479bbe49acea2636c7fd3360d20f7b7e079c300352011c44850b181/cryptography-50.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:900131fafd8aead39ac7dd3a7e833be754c17a95cfd91221636949fe4eb0aa8a", size = 4356517, upload-time = "2026-07-31T14:23:44.939Z" }, + { url = "https://files.pythonhosted.org/packages/32/98/8a151d64367204cbc63ec65d37502f1d9c53cf4bfc6ec3c532614dbec60d/cryptography-50.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:07949c449a1abcf60d1ee6e88956d89404c7df3c8258f46589e912988e551987", size = 4724529, upload-time = "2026-07-31T14:23:46.93Z" }, + { url = "https://files.pythonhosted.org/packages/22/f6/ec13b470172126464a86bf54d2294a46d29837fc51ba3e45d4047946fb5e/cryptography-50.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f89831ef99dd7dd169ab06d63a831adb9e20a87aac6d380266bbda5823349169", size = 5299852, upload-time = "2026-07-31T14:23:48.851Z" }, + { url = "https://files.pythonhosted.org/packages/da/3a/f05e32c99d440c9bb891ea0e36c9091891e36be5a9a87ab2ee6ea20729f6/cryptography-50.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f", size = 4734462, upload-time = "2026-07-31T14:23:50.861Z" }, + { url = "https://files.pythonhosted.org/packages/ca/dc/bd72b26be8953f80625f63151efd38eee71c76ca6cf591c08ff34615a79e/cryptography-50.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1489e263a8048bb8b6a8bac662eb2d402ea5d2b7b4699b72f385f1e2772db105", size = 4852708, upload-time = "2026-07-31T14:23:52.715Z" }, + { url = "https://files.pythonhosted.org/packages/27/20/c930314a2ab476d15dec966ec87e2e9637bb02b06106b12c0396c57bb603/cryptography-50.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7cec5b856506da6defb290f30c9ee687d5f5e8cb0bd3f6459dde43b0b4fa40ef", size = 5004179, upload-time = "2026-07-31T14:23:54.887Z" }, + { url = "https://files.pythonhosted.org/packages/32/2e/c9db68a0c4bfa28e310707527c0ee3a2bd254104d2e02e68f368e197aa4c/cryptography-50.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:bd1c592e4d5974f0d08d4888e432157adba757c66da0246918e43677fafa2d30", size = 3840395, upload-time = "2026-07-31T14:23:56.677Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fb/951032a3bf22a5697c83183fb6294a4843772947a70e616c57b3ff5f522e/cryptography-50.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:49e7d93abdbd2990caced757e5fade25302f719c3c8fb6e6fff2dde98999fc41", size = 3989258, upload-time = "2026-07-31T14:23:58.881Z" }, + { url = "https://files.pythonhosted.org/packages/d4/67/91eb047e69c5e845f2f14b8a2e4a1aab0f283cb885531e9e22c8adb176bc/cryptography-50.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:19736989797678c6af1e55cd49055cdbcb55d8f6b5583ac5335f933aba9101dc", size = 4700648, upload-time = "2026-07-31T14:24:00.702Z" }, + { url = "https://files.pythonhosted.org/packages/30/82/85f0f7425c856b9f96459411eb12e74ef72df9caf6f8f15bf23a33ff131f/cryptography-50.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:80b63928fa35083b33966ce1efb70e5b9607181e49dcd1c22c8c005e319f667f", size = 4682442, upload-time = "2026-07-31T14:24:02.538Z" }, + { url = "https://files.pythonhosted.org/packages/1a/28/b555a365adff1cca2fbe7b9e487d68a40de6bc67ff2cb587473eb43de0e7/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:d58c3db7cd6eed54e6c06744db55456b65ebd7492ddeae9c1e93cfca7aa857d3", size = 4707596, upload-time = "2026-07-31T14:24:04.394Z" }, + { url = "https://files.pythonhosted.org/packages/72/d8/f52538140cc719df62a01cf87d1c7142318d235817109d6f4054d7c352d6/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:df2a58a472f332225671c35b0a830208b86d004f82baa8530fa3782c85646533", size = 5314552, upload-time = "2026-07-31T14:24:06.31Z" }, + { url = "https://files.pythonhosted.org/packages/38/14/6120e5bd7c5aa022ad15424ba4d5c5269d0d9448ed4d55e492ea91e3c1c4/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:11b74db56cdbe3cdee6e3f6982ecb70334fa10dce99ed58bf7894aaaa3b2a037", size = 4717113, upload-time = "2026-07-31T14:24:08.349Z" }, + { url = "https://files.pythonhosted.org/packages/fa/71/190bf38c3ee2e0f8efc9860ae100c9df4169742eef274b91e7aa1cb133b9/cryptography-50.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f59e38625469987d7ef6d495323c55e7db6c212eaf6112267e0d3b565a2e9c9f", size = 4338580, upload-time = "2026-07-31T14:24:10.227Z" }, + { url = "https://files.pythonhosted.org/packages/3a/63/504ccfbbe61fd8aa983f7f146399cdf034c72c2fc55f5b2dfdcdcdb20c99/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:ecfed7367f965a0328cfbdd70da860f15441f002f613185668c6e6ebf5a0ac11", size = 4707038, upload-time = "2026-07-31T14:24:12.169Z" }, + { url = "https://files.pythonhosted.org/packages/01/77/2cf79bbfc4d12ca106437a6e170d6aaa01a373e93093118aaaef0e801bd4/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:9aa87839c383bdbab6ef865787a1fb877af8dd03464c4400322726feaaadfc6d", size = 5273110, upload-time = "2026-07-31T14:24:14.38Z" }, + { url = "https://files.pythonhosted.org/packages/e5/45/8aae2972c520145377ea3559a605a899bebe227bf070b33cdb445929a9b9/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:6ba6a53445bd3cfa809ef3ef5f1589aa6ba08784a1d962bf47d0940e871dab1c", size = 4716439, upload-time = "2026-07-31T14:24:16.415Z" }, + { url = "https://files.pythonhosted.org/packages/7b/20/4fe50b619a48c2525cc46e2dbc1ac490708d704be5d467bdaac6dc955682/cryptography-50.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3f5735ffe4996d28b809371756219f5354864902a3b9e7c0b9ee87041209fc9c", size = 4837383, upload-time = "2026-07-31T14:24:18.553Z" }, + { url = "https://files.pythonhosted.org/packages/92/91/3a31366e183343d3703f8995c095f5734676bd6938118047e50fcf279eb4/cryptography-50.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:1b4a266766514614f8aa60416e71f2fc6e575d36e7bdc90f644fadb2f4b75b95", size = 4985772, upload-time = "2026-07-31T14:24:20.385Z" }, + { url = "https://files.pythonhosted.org/packages/74/9a/02ffe35b2853d121689871eb5dce862092562b3a1ed5cc98f1aaed441506/cryptography-50.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:12b9c6996425c76ea6c457ace4f3073e715b8c545add07cd1a8f3a4f90691269", size = 3816291, upload-time = "2026-07-31T14:24:22.125Z" }, + { url = "https://files.pythonhosted.org/packages/03/37/73d005be173aff344af30e9fd2a576575cb2391a7101d9cd3842e1fa8cce/cryptography-50.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ccdc4a71a4dabae05de219404f9f4abc38e3b58422177ff93d0da05967dafa07", size = 4036009, upload-time = "2026-07-31T14:24:24.122Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c6/7a6202a534e32103a285b7834a120869557fe198d51d7cfe59754c8bda9c/cryptography-50.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:910e1d2668e7de9648f2bcee30e180db2a6b15c30f887d7c4c93ddf96e3992e3", size = 4745252, upload-time = "2026-07-31T14:24:26.118Z" }, + { url = "https://files.pythonhosted.org/packages/85/4f/0fa8c2f4428198f15d9ff8d63400e27afbf94ce833f6108da1eb3753f945/cryptography-50.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a91296cb61e8df6f86d0c19cc4068228da256bf59bf86049fbd821084565327f", size = 4728939, upload-time = "2026-07-31T14:24:27.994Z" }, + { url = "https://files.pythonhosted.org/packages/d1/63/54dd723490ba2dc09b299682c10b38db38f159728bcaae8c591b8af2f22d/cryptography-50.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e722f16708d854fe924790e051061f6704a472c3bac347b6fd88033ea8dd0dc5", size = 4748483, upload-time = "2026-07-31T14:24:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1d/dd/7c77d26285cc7f6991efce64a0f5b4f9383bfa5dd8c5033003eaf7db4cdb/cryptography-50.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d764dcf130c428ef66786f866dd750f53182bc608813489915e9fc106bb0c82f", size = 5367599, upload-time = "2026-07-31T14:24:32.457Z" }, + { url = "https://files.pythonhosted.org/packages/46/c9/f60aed34c013f317f92817b6c171c2d22a78270fa41109bd4b08af26b194/cryptography-50.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:105110f43a471dbd0060b9c9516cb8a6a79233631a04cc2ba16f28323ac6e025", size = 4762647, upload-time = "2026-07-31T14:24:34.599Z" }, + { url = "https://files.pythonhosted.org/packages/be/f3/f9a0173b139372c3a48ed98154b45cc6b9de17c789d5ab552e621c293609/cryptography-50.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:828743d939e9629bc267b8e2d08d8bb67cd4319c771a33d4b18b22dd8fb7440a", size = 4385197, upload-time = "2026-07-31T14:24:36.647Z" }, + { url = "https://files.pythonhosted.org/packages/d8/36/83bb81f6e569bc38e1e4a7bc80f29b46bb9601920bc455fc8e888f5d5742/cryptography-50.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:2a8183b489dc1f7f80f135780fadc1108f14b31b8a40411c7a5b17425f65f28b", size = 4748095, upload-time = "2026-07-31T14:24:39.493Z" }, + { url = "https://files.pythonhosted.org/packages/6b/16/d3008eff98c764979865834c3d386d4fd041b5f52e7f34fc29ac1a5eb515/cryptography-50.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6e7d61120573a7f2cd94cc095f9e81f6967c61ccdf194285aa143ecec8e0b708", size = 5325948, upload-time = "2026-07-31T14:24:41.556Z" }, + { url = "https://files.pythonhosted.org/packages/9c/f8/d97f9603efda3888187bfdb893f26c41be4735c10631d05d284ee6b047c4/cryptography-50.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:37fdb0d0111f1e2ff07139dfb79f1b49531f8e213c46f1163dd7642979b58c47", size = 4762400, upload-time = "2026-07-31T14:24:43.636Z" }, + { url = "https://files.pythonhosted.org/packages/64/a2/4615c8f7d81a00b1d6e6afe19f694e1543582349fb5f4076f6cb5dc36485/cryptography-50.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87f62a3d3b9888ed0fdde100ec06aa61ca9cd44bad9057d1dff9a516b5f5bb9", size = 4878208, upload-time = "2026-07-31T14:24:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/d2/1a/efcfb02f91407149a0dacffffab791f7e19bf6385f63b3666dc8b5e5c9c8/cryptography-50.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:65c2c3add92b45fd0709db8594536aea39c2a67af0e27ffcf049c498501140b7", size = 5037050, upload-time = "2026-07-31T14:24:47.697Z" }, + { url = "https://files.pythonhosted.org/packages/57/30/4a22984d4f1bdfb8c054f07a92bc176b97a3134cc1d6c4b3bffb1f3688b4/cryptography-50.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:d24fead1d4d076e1bfb006dcec392074a3cd8d7b4fc8a595aa64073b2b7a96ba", size = 3874135, upload-time = "2026-07-31T14:24:50.085Z" }, +] + +[[package]] +name = "cssselect2" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tinycss2" }, + { name = "webencodings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/20/92eaa6b0aec7189fa4b75c890640e076e9e793095721db69c5c81142c2e1/cssselect2-0.9.0.tar.gz", hash = "sha256:759aa22c216326356f65e62e791d66160a0f9c91d1424e8d8adc5e74dddfc6fb", size = 35595, upload-time = "2026-02-12T17:16:39.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/21/0e/8459ca4413e1a21a06c97d134bfaf18adfd27cea068813dc0faae06cbf00/cssselect2-0.9.0-py3-none-any.whl", hash = "sha256:6a99e5f91f9a016a304dd929b0966ca464bcfda15177b6fb4a118fc0fb5d9563", size = 15453, upload-time = "2026-02-12T17:16:38.317Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.5.4" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/d0/c177e29701cf1d3008d7d2b16b5fc626592ce13bd535f8795c5f57187e0e/cuda_pathfinder-1.5.4-py3-none-any.whl", hash = "sha256:9563d3175ce1828531acf4b94e1c1c7d67208c347ca002493e2654878b26f4b7", size = 51657, upload-time = "2026-04-27T22:42:07.712Z" }, +] + +[[package]] +name = "cupy-cuda12x" +version = "14.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder" }, + { name = "numpy" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/6e/290ee2d7cc4ad63d66e67acfd7ff3026f2b648dd04449a1bf88ffaa36b1e/cupy_cuda12x-14.1.1-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:7aae7d3bed37985e2aa39f0914b88ad90dbd3a6141d3e8198d73fce65859013c", size = 144383812, upload-time = "2026-06-01T04:52:23.799Z" }, + { url = "https://files.pythonhosted.org/packages/f6/6e/dc03c1ddc940f33b3d32803898e2fdae5c9538a2127a25f499494c84b183/cupy_cuda12x-14.1.1-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:a1138f20080489a46209291498cd12f792226d0a57d50c64a586c162a875a069", size = 133516927, upload-time = "2026-06-01T04:52:35.765Z" }, + { url = "https://files.pythonhosted.org/packages/cc/da/d4a8045b533af634bc791572e8c87981065e4a27b5d3e09d0d4d285742fd/cupy_cuda12x-14.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:85bebce86ffc25ecf31727b25da7b3793daf07b6fd9952704546af574d250988", size = 95238722, upload-time = "2026-06-01T04:52:46.296Z" }, + { url = "https://files.pythonhosted.org/packages/30/90/00fe874c47207b26c9b6ac950d0cecc533b4a145491641932df17e573f3c/cupy_cuda12x-14.1.1-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:afbb3d1fa9484b0ae20d76372c5939a8c5da327e3fc8711b77b2354566cac355", size = 143920086, upload-time = "2026-06-01T04:52:51.726Z" }, + { url = "https://files.pythonhosted.org/packages/89/a4/c46ff91dba0dbe2a0a557974faf4c090a3159d6e7296431ca6846038d047/cupy_cuda12x-14.1.1-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:76ea35469e2aa0a8332b88f72505ea2f7871a0bc8f9b0c87184f57e47c9aa3bf", size = 133071615, upload-time = "2026-06-01T04:52:57.428Z" }, + { url = "https://files.pythonhosted.org/packages/ec/a0/46778424035ad3fc920d49471f079687a054f74d179142e9520014c2514e/cupy_cuda12x-14.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:64072f4139b44df38215f0519a6badc14138fa0e4bb5b2db44fe94d05f8b9c8b", size = 95219598, upload-time = "2026-06-01T04:53:02.774Z" }, + { url = "https://files.pythonhosted.org/packages/b6/99/d72336481264c3483b162ea128d58f80abb50009f1df82ca82905e0b8fd7/cupy_cuda12x-14.1.1-cp314-cp314-manylinux2014_aarch64.whl", hash = "sha256:22d0ff2755a7f29cb225d1d5fb979a73428c5534ea0bca91b0c02698e9948f84", size = 143788629, upload-time = "2026-06-01T04:53:09.404Z" }, + { url = "https://files.pythonhosted.org/packages/c7/77/c43a67e6809e03780d88caf690fa44a8b3152db2d8f848714bec327c9881/cupy_cuda12x-14.1.1-cp314-cp314-manylinux2014_x86_64.whl", hash = "sha256:1059581507343e7cf6231facce30932a195c7aad4fa7771d00e4a252683915a1", size = 132406367, upload-time = "2026-06-01T04:53:16.232Z" }, + { url = "https://files.pythonhosted.org/packages/7d/dc/96cd37de6da41239e02fc7f17e3364d60f99bd6816673d622916a06113ec/cupy_cuda12x-14.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:e707e0eceee174d323be21652e87bb97be982e6966b5dc241756307df42842aa", size = 95793971, upload-time = "2026-06-01T04:53:21.478Z" }, + { url = "https://files.pythonhosted.org/packages/20/c6/0ddec1be851de546e883ae3da5f03c1ea69738628b38234dce4362b5e38b/cupy_cuda12x-14.1.1-cp314-cp314t-manylinux2014_aarch64.whl", hash = "sha256:e09897636b7468a90efa1152109f0b19ba49ebc9a423d5dbd4682ed589e57843", size = 144093057, upload-time = "2026-06-01T04:53:28.647Z" }, + { url = "https://files.pythonhosted.org/packages/a4/80/5e05de89ba61df072aab6f8a6ee3ffeec57db68a0a456825b3b4ce608426/cupy_cuda12x-14.1.1-cp314-cp314t-manylinux2014_x86_64.whl", hash = "sha256:238080487174268d0f09770fe518de7c5b206527bef5c6792aef7ba0626a1c48", size = 132635338, upload-time = "2026-06-01T04:53:35.229Z" }, +] + +[[package]] +name = "defusedxml" +version = "0.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" }, +] + +[[package]] +name = "docker" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pywin32", marker = "sys_platform == 'win32'" }, + { name = "requests" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/91/9b/4a2ea29aeba62471211598dac5d96825bb49348fa07e906ea930394a83ce/docker-7.1.0.tar.gz", hash = "sha256:ad8c70e6e3f8926cb8a92619b832b4ea5299e2831c14284663184e200546fa6c", size = 117834, upload-time = "2024-05-23T11:13:57.216Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl", hash = "sha256:c96b93b7f0a746f9e77d325bcfb87422a3d8bd4f03136ae8a85b37f1898d5fc0", size = 147774, upload-time = "2024-05-23T11:13:55.01Z" }, +] + +[[package]] +name = "docutils" +version = "0.22.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ae/b6/03bb70946330e88ffec97aefd3ea75ba575cb2e762061e0e62a213befee8/docutils-0.22.4.tar.gz", hash = "sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968", size = 2291750, upload-time = "2025-12-18T19:00:26.443Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/10/5da547df7a391dcde17f59520a231527b8571e6f46fc8efb02ccb370ab12/docutils-0.22.4-py3-none-any.whl", hash = "sha256:d0013f540772d1420576855455d050a2180186c91c15779301ac2ccb3eeb68de", size = 633196, upload-time = "2025-12-18T19:00:18.077Z" }, +] + +[[package]] +name = "donfig" +version = "0.8.1.post1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/25/71/80cc718ff6d7abfbabacb1f57aaa42e9c1552bfdd01e64ddd704e4a03638/donfig-0.8.1.post1.tar.gz", hash = "sha256:3bef3413a4c1c601b585e8d297256d0c1470ea012afa6e8461dc28bfb7c23f52", size = 19506, upload-time = "2024-05-23T14:14:31.513Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/d5/c5db1ea3394c6e1732fb3286b3bd878b59507a8f77d32a2cebda7d7b7cd4/donfig-0.8.1.post1-py3-none-any.whl", hash = "sha256:2a3175ce74a06109ff9307d90a230f81215cbac9a751f4d1c6194644b8204f9d", size = 21592, upload-time = "2024-05-23T14:13:55.283Z" }, +] + +[[package]] +name = "execnet" +version = "2.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" }, +] + +[[package]] +name = "flask" +version = "3.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "blinker" }, + { name = "click" }, + { name = "itsdangerous" }, + { name = "jinja2" }, + { name = "markupsafe" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/9c/34f6962f9b9e9c71f6e5ed806e0d0ff03c9d1b0b2340088a0cf4bce09b18/flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c", size = 103424, upload-time = "2026-02-19T05:00:56.027Z" }, +] + +[[package]] +name = "flask-cors" +version = "6.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flask" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/70/74/0fc0fa68d62f21daef41017dafab19ef4b36551521260987eb3a5394c7ba/flask_cors-6.0.2.tar.gz", hash = "sha256:6e118f3698249ae33e429760db98ce032a8bf9913638d085ca0f4c5534ad2423", size = 13472, upload-time = "2025-12-12T20:31:42.861Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/af/72ad54402e599152de6d067324c46fe6a4f531c7c65baf7e96c63db55eaf/flask_cors-6.0.2-py3-none-any.whl", hash = "sha256:e57544d415dfd7da89a9564e1e3a9e515042df76e12130641ca6f3f2f03b699a", size = 13257, upload-time = "2025-12-12T20:31:41.3Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/29/948b9aa87e75820a38650af445d2ef2b6b8a6fab1a23b6bb9e4ef0be2d59/frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1", size = 87782, upload-time = "2025-10-06T05:36:06.649Z" }, + { url = "https://files.pythonhosted.org/packages/64/80/4f6e318ee2a7c0750ed724fa33a4bdf1eacdc5a39a7a24e818a773cd91af/frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b", size = 50594, upload-time = "2025-10-06T05:36:07.69Z" }, + { url = "https://files.pythonhosted.org/packages/2b/94/5c8a2b50a496b11dd519f4a24cb5496cf125681dd99e94c604ccdea9419a/frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4", size = 50448, upload-time = "2025-10-06T05:36:08.78Z" }, + { url = "https://files.pythonhosted.org/packages/6a/bd/d91c5e39f490a49df14320f4e8c80161cfcce09f1e2cde1edd16a551abb3/frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383", size = 242411, upload-time = "2025-10-06T05:36:09.801Z" }, + { url = "https://files.pythonhosted.org/packages/8f/83/f61505a05109ef3293dfb1ff594d13d64a2324ac3482be2cedc2be818256/frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4", size = 243014, upload-time = "2025-10-06T05:36:11.394Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cb/cb6c7b0f7d4023ddda30cf56b8b17494eb3a79e3fda666bf735f63118b35/frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8", size = 234909, upload-time = "2025-10-06T05:36:12.598Z" }, + { url = "https://files.pythonhosted.org/packages/31/c5/cd7a1f3b8b34af009fb17d4123c5a778b44ae2804e3ad6b86204255f9ec5/frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b", size = 250049, upload-time = "2025-10-06T05:36:14.065Z" }, + { url = "https://files.pythonhosted.org/packages/c0/01/2f95d3b416c584a1e7f0e1d6d31998c4a795f7544069ee2e0962a4b60740/frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52", size = 256485, upload-time = "2025-10-06T05:36:15.39Z" }, + { url = "https://files.pythonhosted.org/packages/ce/03/024bf7720b3abaebcff6d0793d73c154237b85bdf67b7ed55e5e9596dc9a/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29", size = 237619, upload-time = "2025-10-06T05:36:16.558Z" }, + { url = "https://files.pythonhosted.org/packages/69/fa/f8abdfe7d76b731f5d8bd217827cf6764d4f1d9763407e42717b4bed50a0/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3", size = 250320, upload-time = "2025-10-06T05:36:17.821Z" }, + { url = "https://files.pythonhosted.org/packages/f5/3c/b051329f718b463b22613e269ad72138cc256c540f78a6de89452803a47d/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143", size = 246820, upload-time = "2025-10-06T05:36:19.046Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/58282e8f98e444b3f4dd42448ff36fa38bef29e40d40f330b22e7108f565/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608", size = 250518, upload-time = "2025-10-06T05:36:20.763Z" }, + { url = "https://files.pythonhosted.org/packages/8f/96/007e5944694d66123183845a106547a15944fbbb7154788cbf7272789536/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa", size = 239096, upload-time = "2025-10-06T05:36:22.129Z" }, + { url = "https://files.pythonhosted.org/packages/66/bb/852b9d6db2fa40be96f29c0d1205c306288f0684df8fd26ca1951d461a56/frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf", size = 39985, upload-time = "2025-10-06T05:36:23.661Z" }, + { url = "https://files.pythonhosted.org/packages/b8/af/38e51a553dd66eb064cdf193841f16f077585d4d28394c2fa6235cb41765/frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746", size = 44591, upload-time = "2025-10-06T05:36:24.958Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1dc65480ab147339fecc70797e9c2f69d9cea9cf38934ce08df070fdb9cb/frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd", size = 40102, upload-time = "2025-10-06T05:36:26.333Z" }, + { url = "https://files.pythonhosted.org/packages/2d/40/0832c31a37d60f60ed79e9dfb5a92e1e2af4f40a16a29abcc7992af9edff/frozenlist-1.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a", size = 85717, upload-time = "2025-10-06T05:36:27.341Z" }, + { url = "https://files.pythonhosted.org/packages/30/ba/b0b3de23f40bc55a7057bd38434e25c34fa48e17f20ee273bbde5e0650f3/frozenlist-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7", size = 49651, upload-time = "2025-10-06T05:36:28.855Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ab/6e5080ee374f875296c4243c381bbdef97a9ac39c6e3ce1d5f7d42cb78d6/frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40", size = 49417, upload-time = "2025-10-06T05:36:29.877Z" }, + { url = "https://files.pythonhosted.org/packages/d5/4e/e4691508f9477ce67da2015d8c00acd751e6287739123113a9fca6f1604e/frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027", size = 234391, upload-time = "2025-10-06T05:36:31.301Z" }, + { url = "https://files.pythonhosted.org/packages/40/76/c202df58e3acdf12969a7895fd6f3bc016c642e6726aa63bd3025e0fc71c/frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822", size = 233048, upload-time = "2025-10-06T05:36:32.531Z" }, + { url = "https://files.pythonhosted.org/packages/f9/c0/8746afb90f17b73ca5979c7a3958116e105ff796e718575175319b5bb4ce/frozenlist-1.8.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121", size = 226549, upload-time = "2025-10-06T05:36:33.706Z" }, + { url = "https://files.pythonhosted.org/packages/7e/eb/4c7eefc718ff72f9b6c4893291abaae5fbc0c82226a32dcd8ef4f7a5dbef/frozenlist-1.8.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5", size = 239833, upload-time = "2025-10-06T05:36:34.947Z" }, + { url = "https://files.pythonhosted.org/packages/c2/4e/e5c02187cf704224f8b21bee886f3d713ca379535f16893233b9d672ea71/frozenlist-1.8.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e", size = 245363, upload-time = "2025-10-06T05:36:36.534Z" }, + { url = "https://files.pythonhosted.org/packages/1f/96/cb85ec608464472e82ad37a17f844889c36100eed57bea094518bf270692/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11", size = 229314, upload-time = "2025-10-06T05:36:38.582Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6f/4ae69c550e4cee66b57887daeebe006fe985917c01d0fff9caab9883f6d0/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1", size = 243365, upload-time = "2025-10-06T05:36:40.152Z" }, + { url = "https://files.pythonhosted.org/packages/7a/58/afd56de246cf11780a40a2c28dc7cbabbf06337cc8ddb1c780a2d97e88d8/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1", size = 237763, upload-time = "2025-10-06T05:36:41.355Z" }, + { url = "https://files.pythonhosted.org/packages/cb/36/cdfaf6ed42e2644740d4a10452d8e97fa1c062e2a8006e4b09f1b5fd7d63/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8", size = 240110, upload-time = "2025-10-06T05:36:42.716Z" }, + { url = "https://files.pythonhosted.org/packages/03/a8/9ea226fbefad669f11b52e864c55f0bd57d3c8d7eb07e9f2e9a0b39502e1/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed", size = 233717, upload-time = "2025-10-06T05:36:44.251Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0b/1b5531611e83ba7d13ccc9988967ea1b51186af64c42b7a7af465dcc9568/frozenlist-1.8.0-cp313-cp313-win32.whl", hash = "sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496", size = 39628, upload-time = "2025-10-06T05:36:45.423Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cf/174c91dbc9cc49bc7b7aab74d8b734e974d1faa8f191c74af9b7e80848e6/frozenlist-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231", size = 43882, upload-time = "2025-10-06T05:36:46.796Z" }, + { url = "https://files.pythonhosted.org/packages/c1/17/502cd212cbfa96eb1388614fe39a3fc9ab87dbbe042b66f97acb57474834/frozenlist-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62", size = 39676, upload-time = "2025-10-06T05:36:47.8Z" }, + { url = "https://files.pythonhosted.org/packages/d2/5c/3bbfaa920dfab09e76946a5d2833a7cbdf7b9b4a91c714666ac4855b88b4/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94", size = 89235, upload-time = "2025-10-06T05:36:48.78Z" }, + { url = "https://files.pythonhosted.org/packages/d2/d6/f03961ef72166cec1687e84e8925838442b615bd0b8854b54923ce5b7b8a/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c", size = 50742, upload-time = "2025-10-06T05:36:49.837Z" }, + { url = "https://files.pythonhosted.org/packages/1e/bb/a6d12b7ba4c3337667d0e421f7181c82dda448ce4e7ad7ecd249a16fa806/frozenlist-1.8.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52", size = 51725, upload-time = "2025-10-06T05:36:50.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/71/d1fed0ffe2c2ccd70b43714c6cab0f4188f09f8a67a7914a6b46ee30f274/frozenlist-1.8.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51", size = 284533, upload-time = "2025-10-06T05:36:51.898Z" }, + { url = "https://files.pythonhosted.org/packages/c9/1f/fb1685a7b009d89f9bf78a42d94461bc06581f6e718c39344754a5d9bada/frozenlist-1.8.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65", size = 292506, upload-time = "2025-10-06T05:36:53.101Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3b/b991fe1612703f7e0d05c0cf734c1b77aaf7c7d321df4572e8d36e7048c8/frozenlist-1.8.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82", size = 274161, upload-time = "2025-10-06T05:36:54.309Z" }, + { url = "https://files.pythonhosted.org/packages/ca/ec/c5c618767bcdf66e88945ec0157d7f6c4a1322f1473392319b7a2501ded7/frozenlist-1.8.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714", size = 294676, upload-time = "2025-10-06T05:36:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ce/3934758637d8f8a88d11f0585d6495ef54b2044ed6ec84492a91fa3b27aa/frozenlist-1.8.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d", size = 300638, upload-time = "2025-10-06T05:36:56.758Z" }, + { url = "https://files.pythonhosted.org/packages/fc/4f/a7e4d0d467298f42de4b41cbc7ddaf19d3cfeabaf9ff97c20c6c7ee409f9/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506", size = 283067, upload-time = "2025-10-06T05:36:57.965Z" }, + { url = "https://files.pythonhosted.org/packages/dc/48/c7b163063d55a83772b268e6d1affb960771b0e203b632cfe09522d67ea5/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51", size = 292101, upload-time = "2025-10-06T05:36:59.237Z" }, + { url = "https://files.pythonhosted.org/packages/9f/d0/2366d3c4ecdc2fd391e0afa6e11500bfba0ea772764d631bbf82f0136c9d/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e", size = 289901, upload-time = "2025-10-06T05:37:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/b8/94/daff920e82c1b70e3618a2ac39fbc01ae3e2ff6124e80739ce5d71c9b920/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0", size = 289395, upload-time = "2025-10-06T05:37:02.115Z" }, + { url = "https://files.pythonhosted.org/packages/e3/20/bba307ab4235a09fdcd3cc5508dbabd17c4634a1af4b96e0f69bfe551ebd/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41", size = 283659, upload-time = "2025-10-06T05:37:03.711Z" }, + { url = "https://files.pythonhosted.org/packages/fd/00/04ca1c3a7a124b6de4f8a9a17cc2fcad138b4608e7a3fc5877804b8715d7/frozenlist-1.8.0-cp313-cp313t-win32.whl", hash = "sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b", size = 43492, upload-time = "2025-10-06T05:37:04.915Z" }, + { url = "https://files.pythonhosted.org/packages/59/5e/c69f733a86a94ab10f68e496dc6b7e8bc078ebb415281d5698313e3af3a1/frozenlist-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888", size = 48034, upload-time = "2025-10-06T05:37:06.343Z" }, + { url = "https://files.pythonhosted.org/packages/16/6c/be9d79775d8abe79b05fa6d23da99ad6e7763a1d080fbae7290b286093fd/frozenlist-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042", size = 41749, upload-time = "2025-10-06T05:37:07.431Z" }, + { url = "https://files.pythonhosted.org/packages/f1/c8/85da824b7e7b9b6e7f7705b2ecaf9591ba6f79c1177f324c2735e41d36a2/frozenlist-1.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0", size = 86127, upload-time = "2025-10-06T05:37:08.438Z" }, + { url = "https://files.pythonhosted.org/packages/8e/e8/a1185e236ec66c20afd72399522f142c3724c785789255202d27ae992818/frozenlist-1.8.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f", size = 49698, upload-time = "2025-10-06T05:37:09.48Z" }, + { url = "https://files.pythonhosted.org/packages/a1/93/72b1736d68f03fda5fdf0f2180fb6caaae3894f1b854d006ac61ecc727ee/frozenlist-1.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c", size = 49749, upload-time = "2025-10-06T05:37:10.569Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b2/fabede9fafd976b991e9f1b9c8c873ed86f202889b864756f240ce6dd855/frozenlist-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2", size = 231298, upload-time = "2025-10-06T05:37:11.993Z" }, + { url = "https://files.pythonhosted.org/packages/3a/3b/d9b1e0b0eed36e70477ffb8360c49c85c8ca8ef9700a4e6711f39a6e8b45/frozenlist-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8", size = 232015, upload-time = "2025-10-06T05:37:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/dc/94/be719d2766c1138148564a3960fc2c06eb688da592bdc25adcf856101be7/frozenlist-1.8.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686", size = 225038, upload-time = "2025-10-06T05:37:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/e4/09/6712b6c5465f083f52f50cf74167b92d4ea2f50e46a9eea0523d658454ae/frozenlist-1.8.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e", size = 240130, upload-time = "2025-10-06T05:37:15.781Z" }, + { url = "https://files.pythonhosted.org/packages/f8/d4/cd065cdcf21550b54f3ce6a22e143ac9e4836ca42a0de1022da8498eac89/frozenlist-1.8.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a", size = 242845, upload-time = "2025-10-06T05:37:17.037Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/f57a5c8c70cd1ead3d5d5f776f89d33110b1addae0ab010ad774d9a44fb9/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128", size = 229131, upload-time = "2025-10-06T05:37:18.221Z" }, + { url = "https://files.pythonhosted.org/packages/6c/52/232476fe9cb64f0742f3fde2b7d26c1dac18b6d62071c74d4ded55e0ef94/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f", size = 240542, upload-time = "2025-10-06T05:37:19.771Z" }, + { url = "https://files.pythonhosted.org/packages/5f/85/07bf3f5d0fb5414aee5f47d33c6f5c77bfe49aac680bfece33d4fdf6a246/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7", size = 237308, upload-time = "2025-10-06T05:37:20.969Z" }, + { url = "https://files.pythonhosted.org/packages/11/99/ae3a33d5befd41ac0ca2cc7fd3aa707c9c324de2e89db0e0f45db9a64c26/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30", size = 238210, upload-time = "2025-10-06T05:37:22.252Z" }, + { url = "https://files.pythonhosted.org/packages/b2/60/b1d2da22f4970e7a155f0adde9b1435712ece01b3cd45ba63702aea33938/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7", size = 231972, upload-time = "2025-10-06T05:37:23.5Z" }, + { url = "https://files.pythonhosted.org/packages/3f/ab/945b2f32de889993b9c9133216c068b7fcf257d8595a0ac420ac8677cab0/frozenlist-1.8.0-cp314-cp314-win32.whl", hash = "sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806", size = 40536, upload-time = "2025-10-06T05:37:25.581Z" }, + { url = "https://files.pythonhosted.org/packages/59/ad/9caa9b9c836d9ad6f067157a531ac48b7d36499f5036d4141ce78c230b1b/frozenlist-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0", size = 44330, upload-time = "2025-10-06T05:37:26.928Z" }, + { url = "https://files.pythonhosted.org/packages/82/13/e6950121764f2676f43534c555249f57030150260aee9dcf7d64efda11dd/frozenlist-1.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b", size = 40627, upload-time = "2025-10-06T05:37:28.075Z" }, + { url = "https://files.pythonhosted.org/packages/c0/c7/43200656ecc4e02d3f8bc248df68256cd9572b3f0017f0a0c4e93440ae23/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d", size = 89238, upload-time = "2025-10-06T05:37:29.373Z" }, + { url = "https://files.pythonhosted.org/packages/d1/29/55c5f0689b9c0fb765055629f472c0de484dcaf0acee2f7707266ae3583c/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed", size = 50738, upload-time = "2025-10-06T05:37:30.792Z" }, + { url = "https://files.pythonhosted.org/packages/ba/7d/b7282a445956506fa11da8c2db7d276adcbf2b17d8bb8407a47685263f90/frozenlist-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930", size = 51739, upload-time = "2025-10-06T05:37:32.127Z" }, + { url = "https://files.pythonhosted.org/packages/62/1c/3d8622e60d0b767a5510d1d3cf21065b9db874696a51ea6d7a43180a259c/frozenlist-1.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c", size = 284186, upload-time = "2025-10-06T05:37:33.21Z" }, + { url = "https://files.pythonhosted.org/packages/2d/14/aa36d5f85a89679a85a1d44cd7a6657e0b1c75f61e7cad987b203d2daca8/frozenlist-1.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24", size = 292196, upload-time = "2025-10-06T05:37:36.107Z" }, + { url = "https://files.pythonhosted.org/packages/05/23/6bde59eb55abd407d34f77d39a5126fb7b4f109a3f611d3929f14b700c66/frozenlist-1.8.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37", size = 273830, upload-time = "2025-10-06T05:37:37.663Z" }, + { url = "https://files.pythonhosted.org/packages/d2/3f/22cff331bfad7a8afa616289000ba793347fcd7bc275f3b28ecea2a27909/frozenlist-1.8.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a", size = 294289, upload-time = "2025-10-06T05:37:39.261Z" }, + { url = "https://files.pythonhosted.org/packages/a4/89/5b057c799de4838b6c69aa82b79705f2027615e01be996d2486a69ca99c4/frozenlist-1.8.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2", size = 300318, upload-time = "2025-10-06T05:37:43.213Z" }, + { url = "https://files.pythonhosted.org/packages/30/de/2c22ab3eb2a8af6d69dc799e48455813bab3690c760de58e1bf43b36da3e/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef", size = 282814, upload-time = "2025-10-06T05:37:45.337Z" }, + { url = "https://files.pythonhosted.org/packages/59/f7/970141a6a8dbd7f556d94977858cfb36fa9b66e0892c6dd780d2219d8cd8/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe", size = 291762, upload-time = "2025-10-06T05:37:46.657Z" }, + { url = "https://files.pythonhosted.org/packages/c1/15/ca1adae83a719f82df9116d66f5bb28bb95557b3951903d39135620ef157/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8", size = 289470, upload-time = "2025-10-06T05:37:47.946Z" }, + { url = "https://files.pythonhosted.org/packages/ac/83/dca6dc53bf657d371fbc88ddeb21b79891e747189c5de990b9dfff2ccba1/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a", size = 289042, upload-time = "2025-10-06T05:37:49.499Z" }, + { url = "https://files.pythonhosted.org/packages/96/52/abddd34ca99be142f354398700536c5bd315880ed0a213812bc491cff5e4/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e", size = 283148, upload-time = "2025-10-06T05:37:50.745Z" }, + { url = "https://files.pythonhosted.org/packages/af/d3/76bd4ed4317e7119c2b7f57c3f6934aba26d277acc6309f873341640e21f/frozenlist-1.8.0-cp314-cp314t-win32.whl", hash = "sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df", size = 44676, upload-time = "2025-10-06T05:37:52.222Z" }, + { url = "https://files.pythonhosted.org/packages/89/76/c615883b7b521ead2944bb3480398cbb07e12b7b4e4d073d3752eb721558/frozenlist-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd", size = 49451, upload-time = "2025-10-06T05:37:53.425Z" }, + { url = "https://files.pythonhosted.org/packages/e0/a3/5982da14e113d07b325230f95060e2169f5311b1017ea8af2a29b374c289/frozenlist-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79", size = 42507, upload-time = "2025-10-06T05:37:54.513Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2026.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/78/f34251dadb8f3921264a1d9b8946f5e542014ee2614b285261b4e40e6775/fsspec-2026.7.0.tar.gz", hash = "sha256:c803c40f4cf860b49dea58ee3e1c33cb9c790520e233537e1340049f89b82a88", size = 317040, upload-time = "2026-07-28T16:34:51.052Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/3c/6a2bf344106328fd04963664a60b9bb6496fc25df8e962fcdc1367285fb9/fsspec-2026.7.0-py3-none-any.whl", hash = "sha256:b57ddbafedfaef7018c1ecab32aa200a9d7ca26b77965f64e48b70061249d279", size = 206583, upload-time = "2026-07-28T16:34:49.538Z" }, +] + +[[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 = "google-crc32c" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/41/4b9c02f99e4c5fb477122cd5437403b552873f014616ac1d19ac8221a58d/google_crc32c-1.8.0.tar.gz", hash = "sha256:a428e25fb7691024de47fecfbff7ff957214da51eddded0da0ae0e0f03a2cf79", size = 14192, upload-time = "2025-12-16T00:35:25.142Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/5f/7307325b1198b59324c0fa9807cafb551afb65e831699f2ce211ad5c8240/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:4b8286b659c1335172e39563ab0a768b8015e88e08329fa5321f774275fc3113", size = 31300, upload-time = "2025-12-16T00:21:56.723Z" }, + { url = "https://files.pythonhosted.org/packages/21/8e/58c0d5d86e2220e6a37befe7e6a94dd2f6006044b1a33edf1ff6d9f7e319/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:2a3dc3318507de089c5384cc74d54318401410f82aa65b2d9cdde9d297aca7cb", size = 30867, upload-time = "2025-12-16T00:38:31.302Z" }, + { url = "https://files.pythonhosted.org/packages/ce/a9/a780cc66f86335a6019f557a8aaca8fbb970728f0efd2430d15ff1beae0e/google_crc32c-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14f87e04d613dfa218d6135e81b78272c3b904e2a7053b841481b38a7d901411", size = 33364, upload-time = "2025-12-16T00:40:22.96Z" }, + { url = "https://files.pythonhosted.org/packages/21/3f/3457ea803db0198c9aaca2dd373750972ce28a26f00544b6b85088811939/google_crc32c-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb5c869c2923d56cb0c8e6bcdd73c009c36ae39b652dbe46a05eb4ef0ad01454", size = 33740, upload-time = "2025-12-16T00:40:23.96Z" }, + { url = "https://files.pythonhosted.org/packages/df/c0/87c2073e0c72515bb8733d4eef7b21548e8d189f094b5dad20b0ecaf64f6/google_crc32c-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:3cc0c8912038065eafa603b238abf252e204accab2a704c63b9e14837a854962", size = 34437, upload-time = "2025-12-16T00:35:21.395Z" }, + { url = "https://files.pythonhosted.org/packages/d1/db/000f15b41724589b0e7bc24bc7a8967898d8d3bc8caf64c513d91ef1f6c0/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:3ebb04528e83b2634857f43f9bb8ef5b2bbe7f10f140daeb01b58f972d04736b", size = 31297, upload-time = "2025-12-16T00:23:20.709Z" }, + { url = "https://files.pythonhosted.org/packages/d7/0d/8ebed0c39c53a7e838e2a486da8abb0e52de135f1b376ae2f0b160eb4c1a/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:450dc98429d3e33ed2926fc99ee81001928d63460f8538f21a5d6060912a8e27", size = 30867, upload-time = "2025-12-16T00:43:14.628Z" }, + { url = "https://files.pythonhosted.org/packages/ce/42/b468aec74a0354b34c8cbf748db20d6e350a68a2b0912e128cabee49806c/google_crc32c-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3b9776774b24ba76831609ffbabce8cdf6fa2bd5e9df37b594221c7e333a81fa", size = 33344, upload-time = "2025-12-16T00:40:24.742Z" }, + { url = "https://files.pythonhosted.org/packages/1c/e8/b33784d6fc77fb5062a8a7854e43e1e618b87d5ddf610a88025e4de6226e/google_crc32c-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:89c17d53d75562edfff86679244830599ee0a48efc216200691de8b02ab6b2b8", size = 33694, upload-time = "2025-12-16T00:40:25.505Z" }, + { url = "https://files.pythonhosted.org/packages/92/b1/d3cbd4d988afb3d8e4db94ca953df429ed6db7282ed0e700d25e6c7bfc8d/google_crc32c-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:57a50a9035b75643996fbf224d6661e386c7162d1dfdab9bc4ca790947d1007f", size = 34435, upload-time = "2025-12-16T00:35:22.107Z" }, + { url = "https://files.pythonhosted.org/packages/21/88/8ecf3c2b864a490b9e7010c84fd203ec8cf3b280651106a3a74dd1b0ca72/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:e6584b12cb06796d285d09e33f63309a09368b9d806a551d8036a4207ea43697", size = 31301, upload-time = "2025-12-16T00:24:48.527Z" }, + { url = "https://files.pythonhosted.org/packages/36/c6/f7ff6c11f5ca215d9f43d3629163727a272eabc356e5c9b2853df2bfe965/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:f4b51844ef67d6cf2e9425983274da75f18b1597bb2c998e1c0a0e8d46f8f651", size = 30868, upload-time = "2025-12-16T00:48:12.163Z" }, + { url = "https://files.pythonhosted.org/packages/56/15/c25671c7aad70f8179d858c55a6ae8404902abe0cdcf32a29d581792b491/google_crc32c-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b0d1a7afc6e8e4635564ba8aa5c0548e3173e41b6384d7711a9123165f582de2", size = 33381, upload-time = "2025-12-16T00:40:26.268Z" }, + { url = "https://files.pythonhosted.org/packages/42/fa/f50f51260d7b0ef5d4898af122d8a7ec5a84e2984f676f746445f783705f/google_crc32c-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8b3f68782f3cbd1bce027e48768293072813469af6a61a86f6bb4977a4380f21", size = 33734, upload-time = "2025-12-16T00:40:27.028Z" }, + { url = "https://files.pythonhosted.org/packages/08/a5/7b059810934a09fb3ccb657e0843813c1fee1183d3bc2c8041800374aa2c/google_crc32c-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:d511b3153e7011a27ab6ee6bb3a5404a55b994dc1a7322c0b87b29606d9790e2", size = 34878, upload-time = "2025-12-16T00:35:23.142Z" }, +] + +[[package]] +name = "graphql-core" +version = "3.2.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/68/c5/36aa96205c3ecbb3d34c7c24189e4553c7ca2ebc7e1dd07432339b980272/graphql_core-3.2.8.tar.gz", hash = "sha256:015457da5d996c924ddf57a43f4e959b0b94fb695b85ed4c29446e508ed65cf3", size = 513181, upload-time = "2026-03-05T19:55:37.332Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/86/41/cb887d9afc5dabd78feefe6ccbaf83ff423c206a7a1b7aeeac05120b2125/graphql_core-3.2.8-py3-none-any.whl", hash = "sha256:cbee07bee1b3ed5e531723685369039f32ff815ef60166686e0162f540f1520c", size = 207349, upload-time = "2026-03-05T19:55:35.911Z" }, +] + +[[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.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/82/74f4a3310cdabfbb10da554c3a672847f1ed33c6f61dd472681ce7f1fe67/griffelib-2.0.2.tar.gz", hash = "sha256:3cf20b3bc470e83763ffbf236e0076b1211bac1bc67de13daf494640f2de707e", size = 166461, upload-time = "2026-03-27T11:34:51.091Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/8c/c9138d881c79aa0ea9ed83cbd58d5ca75624378b38cee225dcf5c42cc91f/griffelib-2.0.2-py3-none-any.whl", hash = "sha256:925c857658fb1ba40c0772c37acbc2ab650bd794d9c1b9726922e36ea4117ea1", size = 142357, upload-time = "2026-03-27T11:34:46.275Z" }, +] + +[[package]] +name = "hypothesis" +version = "6.165.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/3a/b840ea8b26e0c4795584dc93c832c5d1a9ff37db1818cc91b2ee8110f757/hypothesis-6.165.5.tar.gz", hash = "sha256:0df7fdefd2e10bbfe7d690eb22c7181a739e8040026907207faa305d86e6e4db", size = 503056, upload-time = "2026-08-12T22:34:58.164Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/46/fba332db906bb26f3c27285d17f5210bee54c3d7e1545e4d1bcae08ec437/hypothesis-6.165.5-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e9ee79ccf2de7b185821ed8364eccfea7300b52b30a8c626f6b7213f3b38e5d5", size = 782500, upload-time = "2026-08-12T22:33:48.567Z" }, + { url = "https://files.pythonhosted.org/packages/cd/68/f3cd7814a571ecf58c97a40686c97814c9f6be95dd258d9144d909f0900e/hypothesis-6.165.5-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:b732ea0c758e9c587eea8bb89ea27c985cb7609304e484ff8e5ffdb890f56ae5", size = 778047, upload-time = "2026-08-12T22:33:44.541Z" }, + { url = "https://files.pythonhosted.org/packages/85/a4/e0825ff8e353bf92b77f9b990c3e0e1160a0f2953feb95647cf2ced0b1a0/hypothesis-6.165.5-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:edb08b192ea64a75e82dcc0b49e515f9ca86e4523c678bf8035c993f3bf7323f", size = 1107271, upload-time = "2026-08-12T22:33:31.315Z" }, + { url = "https://files.pythonhosted.org/packages/63/85/1005fece1e0f59f8974c2e4be3fae1d0436a77b9fbee9a6203d7b250536d/hypothesis-6.165.5-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb74178189e0a8451e0b7cde4a236f4c8bee848ce01d42df968623ac11a4671a", size = 1135836, upload-time = "2026-08-12T22:34:06.044Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8a/6f51cf111f590b883f5fcdb21b54345beeab516ad9c07d4256b731d66ef4/hypothesis-6.165.5-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a970cfb945f31b3115b013ede9fe3f0d68b37ff5b86499cc44ccec3d3fe1eeaa", size = 1156825, upload-time = "2026-08-12T22:34:28.263Z" }, + { url = "https://files.pythonhosted.org/packages/4c/7e/fbf54b49173d118681576259acdec61e045b825d516ca1fd5155f7a14ac1/hypothesis-6.165.5-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:569a7cd8b737019420a5530584ee28fba9dfa3ed877621764a2627f804e983c6", size = 1112117, upload-time = "2026-08-12T22:34:13.239Z" }, + { url = "https://files.pythonhosted.org/packages/d2/95/98bd41c67215950f73f8df711b7d13e40f0fad21c1ff61271b676abc4e19/hypothesis-6.165.5-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:61f30a43dc377ba94885e1990be785434686d76a8f37605336dd697c696dad4c", size = 1148864, upload-time = "2026-08-12T22:34:22.427Z" }, + { url = "https://files.pythonhosted.org/packages/0b/07/9dac0e757abc9dd0500b173adbfe018b1742af5ab35c46169cea290bbf65/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6a25168ab05d52a084e216f8f033472a8bd18167e0e8fc25a8774722db884be2", size = 1282719, upload-time = "2026-08-12T22:33:55.326Z" }, + { url = "https://files.pythonhosted.org/packages/62/9a/0dcce83dfa414427c2632be45a2338edb5b80e2b9b1c7d88c70c2478c90d/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:6984a5b7e62b19ddd78643d954dfa90ec8dabbdac4df43a4e63f60fa06514eb2", size = 1409219, upload-time = "2026-08-12T22:33:39.521Z" }, + { url = "https://files.pythonhosted.org/packages/31/8f/82ed9fe9dae7cb79714c5de9cbccd5c4847348971e4ee61c5ad2013417d9/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:77b57c6c5154357955d724a5ba198aa421f1273a9f88a6ae24d23a1c6d1c91b8", size = 1281995, upload-time = "2026-08-12T22:34:38.42Z" }, + { url = "https://files.pythonhosted.org/packages/b9/4b/06ca1631cce0a9a9806ef15535b9502967751a066dfd620876ff4b8e1eaf/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d77557a13f3cfbabc9b96909fc985563e474627208d981689e4925dc4708722f", size = 1324044, upload-time = "2026-08-12T22:33:57.817Z" }, + { url = "https://files.pythonhosted.org/packages/b0/d7/ac8ae1cf829faa5204a743db0e06880ff71bdd105927592b504e34368391/hypothesis-6.165.5-cp310-abi3-win32.whl", hash = "sha256:7c5fd96d54f63fca065cbc21579be0e9b75190af48ff77d5cb759111fe5edae0", size = 668283, upload-time = "2026-08-12T22:33:32.83Z" }, + { url = "https://files.pythonhosted.org/packages/1c/62/77acaaea919da21dbf9e76b78a87f9ac66fb44dc2e95afce07dad6da1185/hypothesis-6.165.5-cp310-abi3-win_amd64.whl", hash = "sha256:bcc3f34121b046e6091b35901b77e24dd1c674fc234b6e09b102e5efb03afa11", size = 674433, upload-time = "2026-08-12T22:34:47.75Z" }, + { url = "https://files.pythonhosted.org/packages/e6/d0/176ea6d8480d35a1a4fc2ffb1a61126441b2ac067216737052358581d5a7/hypothesis-6.165.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:1f330c91d532810bc2ac849e4d0d44a5a4f72508b4c92f1af91b7f2c90c4379a", size = 784074, upload-time = "2026-08-12T22:34:20.56Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0c/3d128243dfc0ae059935c6607869f244efdc5676bb6e0006a2795cfebaeb/hypothesis-6.165.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:331e8026a380629c8b3b01850f0504a5191617694fe8703ffbb7de32cfbb370e", size = 775642, upload-time = "2026-08-12T22:34:14.757Z" }, + { url = "https://files.pythonhosted.org/packages/6f/40/e80bb810b26fe5807f7c8e3c3c5c3c7556d7128a195e0a57f2480b8a78e2/hypothesis-6.165.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d4ebe628c589b512a0e20b99aa3799e2331ba2c590dadf411d3bee95f9edb914", size = 1106103, upload-time = "2026-08-12T22:33:53.788Z" }, + { url = "https://files.pythonhosted.org/packages/a6/1c/14648fa3d821bfe4f132e5482837320f191bc60f38a4bd2b687096adf6e5/hypothesis-6.165.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:397685c7e74e6c489bab521bf437c7aba366e275e54f8bb03a6f4571df71faa8", size = 1156164, upload-time = "2026-08-12T22:34:04.621Z" }, + { url = "https://files.pythonhosted.org/packages/59/59/74718a2b859e3b6673589f1591785dd15cdec2ff02b7c8d18f3fc0a42ed2/hypothesis-6.165.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ed071268fb878d206ff3172dfef29681cda4982c2752d57e3ad1cf70aa3d7535", size = 1280047, upload-time = "2026-08-12T22:33:51.258Z" }, + { url = "https://files.pythonhosted.org/packages/72/5f/1de655e95992c4657f302ec0eca0dd2cfb6bfaaa3b698836432daedac992/hypothesis-6.165.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:381bb61f342c47d0bbfed6af7fecc93f1a8d4778e0c12e7415bdfe0f9bdc9121", size = 1323384, upload-time = "2026-08-12T22:34:03.192Z" }, + { url = "https://files.pythonhosted.org/packages/52/e9/1f265bf5f575396e8097010c39b11c2c4dd905064c694a0f53dffff58445/hypothesis-6.165.5-cp312-cp312-win_amd64.whl", hash = "sha256:92f2dfb1417bfaf93fdbe654261c68dbbfd573b74473a570895bf81958c045e7", size = 671570, upload-time = "2026-08-12T22:34:51.694Z" }, + { url = "https://files.pythonhosted.org/packages/f1/af/2c3357cda375d8ba1276dec4d0a7b51404f86cc6855f1541b424cf99d5f7/hypothesis-6.165.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:55b907b33ece350a8b69890a7f09b22b6a93761a8724c3ed12a9cd71b2a03eb1", size = 783966, upload-time = "2026-08-12T22:34:40.078Z" }, + { url = "https://files.pythonhosted.org/packages/0b/64/71cbfa9e741a0d657570af6b42f5f81ca795fdd0bddca44bc89309b46e16/hypothesis-6.165.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2cf1a6b2ccaf36e0a2b1f95515edec4db6db14a4e7afd9c36ff477552ffc0f11", size = 775594, upload-time = "2026-08-12T22:34:00.589Z" }, + { url = "https://files.pythonhosted.org/packages/ac/1f/ccb8f0034c8e17f488bc60d74ac21ac0e8945f507ed0b6e8634b67da925e/hypothesis-6.165.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5faa41aca389826d21f311ae5e59b36eb8bb38933a88bc07ad08bd868af6daae", size = 1106007, upload-time = "2026-08-12T22:34:25.431Z" }, + { url = "https://files.pythonhosted.org/packages/13/9d/64f7f7e1398fb04286816b9770138a35d730f008ac45b44b6425dcc0dd61/hypothesis-6.165.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a194f401e5d0345ef459f5aa80a50676a64e146c4f57474d70f7ccbe11c886c7", size = 1155990, upload-time = "2026-08-12T22:33:37.139Z" }, + { url = "https://files.pythonhosted.org/packages/21/e9/4bc808417bac59e9c154cbfb38705613adba4f1f37a815607211ab9ee0ab/hypothesis-6.165.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dd2acd36004b990504125c4e679cf98addf3ca2ce873b38a52f71c66716cc7a6", size = 1280030, upload-time = "2026-08-12T22:34:53.359Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ff/dd0de28497f64ca01c059e32eca7e06a69c39f50ab614969ae636b7ceb3f/hypothesis-6.165.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:709d61590c8cd627479fb4255e085239b91b29a4d386e83f910c5117cfe5b25b", size = 1323111, upload-time = "2026-08-12T22:33:41.959Z" }, + { url = "https://files.pythonhosted.org/packages/45/45/756e1050f26041f6c3aeae2b7e41b10160b2560de0ec46fd3341f6a3cb52/hypothesis-6.165.5-cp313-cp313-win_amd64.whl", hash = "sha256:de4b6d24a0e6adfdd99b2ee1f8d9f43e6ba6146b3860a643e8bce6b41fcebdc6", size = 671569, upload-time = "2026-08-12T22:34:33.938Z" }, + { url = "https://files.pythonhosted.org/packages/63/5e/e4178b39d5e7307d3658ec54733f3b7d953df12a38681b91ab1929b740cb/hypothesis-6.165.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:6f877ace8cb1bc0af9e3c83bf2a63f0a29f54f99ec813d1ecc9c3224b514c036", size = 784066, upload-time = "2026-08-12T22:34:42.97Z" }, + { url = "https://files.pythonhosted.org/packages/7b/f1/9c338484238ef0169f77ae7fdd28e34d1dacc0501f003cf7b0009f1f1f58/hypothesis-6.165.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:f9d0b87ba2fa7ae53c09650e07cb74a117b383d7ab4839415341ac802596d1e5", size = 775741, upload-time = "2026-08-12T22:34:31.002Z" }, + { url = "https://files.pythonhosted.org/packages/a8/79/4502ccc73f5dbaa29c9cc1f33af0337aa28cc03c86ae289530bb70c0fc73/hypothesis-6.165.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:842481f603ef919c2594784bfbaa600916250a35e9d54cc4260e27d415eacc0a", size = 1106541, upload-time = "2026-08-12T22:34:24.067Z" }, + { url = "https://files.pythonhosted.org/packages/b8/e9/10575fe56720cc6be25f7bc8cef708ee1b6e6669ca0b7fd16f7dbf460190/hypothesis-6.165.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c1ecee1a9241db6c2d51ebbe58aa2575364f4fa21583f5d22ac2a8885bbe9490", size = 1156172, upload-time = "2026-08-12T22:33:35.018Z" }, + { url = "https://files.pythonhosted.org/packages/c1/3e/b89e390f580d55b2d65bf726d7602a80f7725cc414bd60526bed0caf507b/hypothesis-6.165.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c108e99e4029318ed85ec5c39f5687c36604606394de3ff4da6e42356a2cceff", size = 1280392, upload-time = "2026-08-12T22:34:18.877Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/b33b5c0aedf35c298011748c679d652839a86b55ea616ca7561b85ac233f/hypothesis-6.165.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a811fe1f763e725692fa730c8b27ee3909f652f9c885dd89ee06f2583fd80944", size = 1323482, upload-time = "2026-08-12T22:34:49.696Z" }, + { url = "https://files.pythonhosted.org/packages/f2/8f/0361d9fce27af669ae936f535ad8275c35736cccf7d9ed66275f3eca874d/hypothesis-6.165.5-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:38353c9aaf946f76fd2d7d5e59c1564eac93ad362e98c7d6ffa705aa0e38974d", size = 615638, upload-time = "2026-08-12T22:34:54.979Z" }, + { url = "https://files.pythonhosted.org/packages/2d/fa/f49d197e125db4dd6725f248a838c1a8230e50d91889237fbf21705b6d45/hypothesis-6.165.5-cp314-cp314-win_amd64.whl", hash = "sha256:377af80792d187cc222bb2666e979c7e559ebb0f1b312c5376d7216f9c91bbf1", size = 671380, upload-time = "2026-08-12T22:33:36.096Z" }, + { url = "https://files.pythonhosted.org/packages/28/90/f939079a65499cad6352f566c3c632da5292f80e2253a72cc9bf6684d4bb/hypothesis-6.165.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:e2c423f947be24a7a7324962bf4984bc2231d61c01a4ce4d794e5c7e72b918f3", size = 782526, upload-time = "2026-08-12T22:33:33.895Z" }, + { url = "https://files.pythonhosted.org/packages/51/55/8afa60314542179289b2ef7eb6623cc8d9a6405488d2f3266e7610e003d4/hypothesis-6.165.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:05e7e8288b2f5fbb34a30b45c9df72a5ce9da0d5ce90705c76b28dda75aac984", size = 774157, upload-time = "2026-08-12T22:33:56.544Z" }, + { url = "https://files.pythonhosted.org/packages/6b/83/93ba4b711c0bfa5a2acc200d60f6fb3c947ea1a4b7f6ef0dacc02ac90de0/hypothesis-6.165.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3837b9e586a78f961aa7c0eedb979fa1cf3dcc8302103ac1e75c2520e943555f", size = 1104748, upload-time = "2026-08-12T22:33:46.901Z" }, + { url = "https://files.pythonhosted.org/packages/57/b9/c0b04ab66762526855fc97c18ecafe038fb1b428f48b2234e3c17b75b4ad/hypothesis-6.165.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eb8fac650e976dfe4d48682f902224a70e2e64ec0716a8822818fa958b456053", size = 1154827, upload-time = "2026-08-12T22:34:17.53Z" }, + { url = "https://files.pythonhosted.org/packages/4c/9b/9368493ef62fba5a3ae8b09164466c3ad166b329ae2df01c897dfc3f3790/hypothesis-6.165.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0a5004c3fe761b642ca556abf4551bc9a94d190320bcf7ce118cf8b792eaf71c", size = 1278417, upload-time = "2026-08-12T22:34:16.196Z" }, + { url = "https://files.pythonhosted.org/packages/6f/21/5eef54851cb51f47ebe123312c4c737934cb6469f6af38bd6e052037f89c/hypothesis-6.165.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:df05b18c2dcb1701532044d4d119cecc08b7d91fcf72e78a17b03257053cc6e9", size = 1322104, upload-time = "2026-08-12T22:33:38.255Z" }, + { url = "https://files.pythonhosted.org/packages/9e/4e/9ed7f0b7c6b0a5d0d6aa0e0a5c05420db8ce21de6c96ce17139c0dbd8d2c/hypothesis-6.165.5-cp314-cp314t-win_amd64.whl", hash = "sha256:56f3a5b0b21695cdc6c8ccb7cf8da63f5822de4691cf23b9d95b5931b042af00", size = 671372, upload-time = "2026-08-12T22:34:46.023Z" }, +] + +[[package]] +name = "idna" +version = "3.15" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/77/7b3966d0b9d1d31a36ddf1746926a11dface89a83409bf1483f0237aa758/idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc", size = 199245, upload-time = "2026-05-12T22:45:57.011Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" }, +] + +[[package]] +name = "imagesize" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6c/e6/7bf14eeb8f8b7251141944835abd42eb20a658d89084b7e1f3e5fe394090/imagesize-2.0.0.tar.gz", hash = "sha256:8e8358c4a05c304f1fccf7ff96f036e7243a189e9e42e90851993c558cfe9ee3", size = 1773045, upload-time = "2026-03-03T14:18:29.941Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5f/53/fb7122b71361a0d121b669dcf3d31244ef75badbbb724af388948de543e2/imagesize-2.0.0-py2.py3-none-any.whl", hash = "sha256:5667c5bbb57ab3f1fa4bc366f4fbc971db3d5ed011fd2715fd8001f782718d96", size = 9441, upload-time = "2026-03-03T14:18:27.892Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "itsdangerous" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, +] + +[[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 = "jmespath" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, +] + +[[package]] +name = "joserfc" +version = "1.6.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5d/ac/d4fd5b30f82900eac60d765f179f0ba005825ac462cc8ced6e13ec685ab3/joserfc-1.6.8.tar.gz", hash = "sha256:878620c553a6ebdd76ccdc356782fee3f735f21a356d079a546b42a4670ace5f", size = 232930, upload-time = "2026-05-27T03:22:37.819Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/8c/5cdce2cf3ce8155849baf9a5e2ce77e89dc87ec3bdb38259e5d85fbc45bd/joserfc-1.6.8-py3-none-any.whl", hash = "sha256:22fb31a69094a5e6f44632002a9df2c30c941fc6c8ce1b037e92c03de954cf9f", size = 70927, upload-time = "2026-05-27T03:22:35.796Z" }, +] + +[[package]] +name = "jsonpatch" +version = "1.33" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonpointer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/78/18813351fe5d63acad16aec57f94ec2b70a09e53ca98145589e185423873/jsonpatch-1.33.tar.gz", hash = "sha256:9fcd4009c41e6d12348b4a0ff2563ba56a2923a7dfee731d004e212e1ee5030c", size = 21699, upload-time = "2023-06-26T12:07:29.144Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/07/02e16ed01e04a374e644b575638ec7987ae846d25ad97bcc9945a3ee4b0e/jsonpatch-1.33-py2.py3-none-any.whl", hash = "sha256:0ae28c0cd062bbd8b8ecc26d7d164fbbea9652a1a3693f3b956c1eae5145dade", size = 12898, upload-time = "2023-06-16T21:01:28.466Z" }, +] + +[[package]] +name = "jsonpath-ng" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/32/58/250751940d75c8019659e15482d548a4aa3b6ce122c515102a4bfdac50e3/jsonpath_ng-1.8.0.tar.gz", hash = "sha256:54252968134b5e549ea5b872f1df1168bd7defe1a52fed5a358c194e1943ddc3", size = 74513, upload-time = "2026-02-24T14:42:06.182Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/99/33c7d78a3fb70d545fd5411ac67a651c81602cc09c9cf0df383733f068c5/jsonpath_ng-1.8.0-py3-none-any.whl", hash = "sha256:b8dde192f8af58d646fc031fac9c99fe4d00326afc4148f1f043c601a8cfe138", size = 67844, upload-time = "2026-02-28T00:53:19.637Z" }, +] + +[[package]] +name = "jsonpointer" +version = "3.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/c7/af399a2e7a67fd18d63c40c5e62d3af4e67b836a2107468b6a5ea24c4304/jsonpointer-3.1.1.tar.gz", hash = "sha256:0b801c7db33a904024f6004d526dcc53bbb8a4a0f4e32bfd10beadf60adf1900", size = 9068, upload-time = "2026-03-23T22:32:32.458Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/6a/a83720e953b1682d2d109d3c2dbb0bc9bf28cc1cbc205be4ef4be5da709d/jsonpointer-3.1.1-py3-none-any.whl", hash = "sha256:8ff8b95779d071ba472cf5bc913028df06031797532f08a7d5b602d8b2a488ca", size = 7659, upload-time = "2026-03-23T22:32:31.568Z" }, +] + +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-path" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pathable" }, + { name = "pyyaml" }, + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/01/86/cfee6dd25843bec0760f456599a4f7e7e40221a934b9229fda0662c859bc/jsonschema_path-0.4.6.tar.gz", hash = "sha256:c89eb635f4d497c9ac328eeff359c489755838806a7d033510a692e9576f5c4b", size = 15302, upload-time = "2026-04-27T18:57:08.412Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/43/3d3065c05a04bb550c143bfbb8e4fd7022cd327e1082bf257bac74923783/jsonschema_path-0.4.6-py3-none-any.whl", hash = "sha256:451354b5311fa955c3144e6e4e255388c751c0121c5570ec5bb9291dd42d08c9", size = 19565, upload-time = "2026-04-27T18:57:06.792Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + +[[package]] +name = "lazy-object-proxy" +version = "1.12.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/08/a2/69df9c6ba6d316cfd81fe2381e464db3e6de5db45f8c43c6a23504abf8cb/lazy_object_proxy-1.12.0.tar.gz", hash = "sha256:1f5a462d92fd0cfb82f1fab28b51bfb209fabbe6aabf7f0d51472c0c124c0c61", size = 43681, upload-time = "2025-08-22T13:50:06.783Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0d/1b/b5f5bd6bda26f1e15cd3232b223892e4498e34ec70a7f4f11c401ac969f1/lazy_object_proxy-1.12.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8ee0d6027b760a11cc18281e702c0309dd92da458a74b4c15025d7fc490deede", size = 26746, upload-time = "2025-08-22T13:42:37.572Z" }, + { url = "https://files.pythonhosted.org/packages/55/64/314889b618075c2bfc19293ffa9153ce880ac6153aacfd0a52fcabf21a66/lazy_object_proxy-1.12.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4ab2c584e3cc8be0dfca422e05ad30a9abe3555ce63e9ab7a559f62f8dbc6ff9", size = 71457, upload-time = "2025-08-22T13:42:38.743Z" }, + { url = "https://files.pythonhosted.org/packages/11/53/857fc2827fc1e13fbdfc0ba2629a7d2579645a06192d5461809540b78913/lazy_object_proxy-1.12.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:14e348185adbd03ec17d051e169ec45686dcd840a3779c9d4c10aabe2ca6e1c0", size = 71036, upload-time = "2025-08-22T13:42:40.184Z" }, + { url = "https://files.pythonhosted.org/packages/2b/24/e581ffed864cd33c1b445b5763d617448ebb880f48675fc9de0471a95cbc/lazy_object_proxy-1.12.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c4fcbe74fb85df8ba7825fa05eddca764138da752904b378f0ae5ab33a36c308", size = 69329, upload-time = "2025-08-22T13:42:41.311Z" }, + { url = "https://files.pythonhosted.org/packages/78/be/15f8f5a0b0b2e668e756a152257d26370132c97f2f1943329b08f057eff0/lazy_object_proxy-1.12.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:563d2ec8e4d4b68ee7848c5ab4d6057a6d703cb7963b342968bb8758dda33a23", size = 70690, upload-time = "2025-08-22T13:42:42.51Z" }, + { url = "https://files.pythonhosted.org/packages/5d/aa/f02be9bbfb270e13ee608c2b28b8771f20a5f64356c6d9317b20043c6129/lazy_object_proxy-1.12.0-cp312-cp312-win_amd64.whl", hash = "sha256:53c7fd99eb156bbb82cbc5d5188891d8fdd805ba6c1e3b92b90092da2a837073", size = 26563, upload-time = "2025-08-22T13:42:43.685Z" }, + { url = "https://files.pythonhosted.org/packages/f4/26/b74c791008841f8ad896c7f293415136c66cc27e7c7577de4ee68040c110/lazy_object_proxy-1.12.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:86fd61cb2ba249b9f436d789d1356deae69ad3231dc3c0f17293ac535162672e", size = 26745, upload-time = "2025-08-22T13:42:44.982Z" }, + { url = "https://files.pythonhosted.org/packages/9b/52/641870d309e5d1fb1ea7d462a818ca727e43bfa431d8c34b173eb090348c/lazy_object_proxy-1.12.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:81d1852fb30fab81696f93db1b1e55a5d1ff7940838191062f5f56987d5fcc3e", size = 71537, upload-time = "2025-08-22T13:42:46.141Z" }, + { url = "https://files.pythonhosted.org/packages/47/b6/919118e99d51c5e76e8bf5a27df406884921c0acf2c7b8a3b38d847ab3e9/lazy_object_proxy-1.12.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be9045646d83f6c2664c1330904b245ae2371b5c57a3195e4028aedc9f999655", size = 71141, upload-time = "2025-08-22T13:42:47.375Z" }, + { url = "https://files.pythonhosted.org/packages/e5/47/1d20e626567b41de085cf4d4fb3661a56c159feaa73c825917b3b4d4f806/lazy_object_proxy-1.12.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:67f07ab742f1adfb3966c40f630baaa7902be4222a17941f3d85fd1dae5565ff", size = 69449, upload-time = "2025-08-22T13:42:48.49Z" }, + { url = "https://files.pythonhosted.org/packages/58/8d/25c20ff1a1a8426d9af2d0b6f29f6388005fc8cd10d6ee71f48bff86fdd0/lazy_object_proxy-1.12.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:75ba769017b944fcacbf6a80c18b2761a1795b03f8899acdad1f1c39db4409be", size = 70744, upload-time = "2025-08-22T13:42:49.608Z" }, + { url = "https://files.pythonhosted.org/packages/c0/67/8ec9abe15c4f8a4bcc6e65160a2c667240d025cbb6591b879bea55625263/lazy_object_proxy-1.12.0-cp313-cp313-win_amd64.whl", hash = "sha256:7b22c2bbfb155706b928ac4d74c1a63ac8552a55ba7fff4445155523ea4067e1", size = 26568, upload-time = "2025-08-22T13:42:57.719Z" }, + { url = "https://files.pythonhosted.org/packages/23/12/cd2235463f3469fd6c62d41d92b7f120e8134f76e52421413a0ad16d493e/lazy_object_proxy-1.12.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4a79b909aa16bde8ae606f06e6bbc9d3219d2e57fb3e0076e17879072b742c65", size = 27391, upload-time = "2025-08-22T13:42:50.62Z" }, + { url = "https://files.pythonhosted.org/packages/60/9e/f1c53e39bbebad2e8609c67d0830cc275f694d0ea23d78e8f6db526c12d3/lazy_object_proxy-1.12.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:338ab2f132276203e404951205fe80c3fd59429b3a724e7b662b2eb539bb1be9", size = 80552, upload-time = "2025-08-22T13:42:51.731Z" }, + { url = "https://files.pythonhosted.org/packages/4c/b6/6c513693448dcb317d9d8c91d91f47addc09553613379e504435b4cc8b3e/lazy_object_proxy-1.12.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8c40b3c9faee2e32bfce0df4ae63f4e73529766893258eca78548bac801c8f66", size = 82857, upload-time = "2025-08-22T13:42:53.225Z" }, + { url = "https://files.pythonhosted.org/packages/12/1c/d9c4aaa4c75da11eb7c22c43d7c90a53b4fca0e27784a5ab207768debea7/lazy_object_proxy-1.12.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:717484c309df78cedf48396e420fa57fc8a2b1f06ea889df7248fdd156e58847", size = 80833, upload-time = "2025-08-22T13:42:54.391Z" }, + { url = "https://files.pythonhosted.org/packages/0b/ae/29117275aac7d7d78ae4f5a4787f36ff33262499d486ac0bf3e0b97889f6/lazy_object_proxy-1.12.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:a6b7ea5ea1ffe15059eb44bcbcb258f97bcb40e139b88152c40d07b1a1dfc9ac", size = 79516, upload-time = "2025-08-22T13:42:55.812Z" }, + { url = "https://files.pythonhosted.org/packages/19/40/b4e48b2c38c69392ae702ae7afa7b6551e0ca5d38263198b7c79de8b3bdf/lazy_object_proxy-1.12.0-cp313-cp313t-win_amd64.whl", hash = "sha256:08c465fb5cd23527512f9bd7b4c7ba6cec33e28aad36fbbe46bf7b858f9f3f7f", size = 27656, upload-time = "2025-08-22T13:42:56.793Z" }, + { url = "https://files.pythonhosted.org/packages/ef/3a/277857b51ae419a1574557c0b12e0d06bf327b758ba94cafc664cb1e2f66/lazy_object_proxy-1.12.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c9defba70ab943f1df98a656247966d7729da2fe9c2d5d85346464bf320820a3", size = 26582, upload-time = "2025-08-22T13:49:49.366Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b6/c5e0fa43535bb9c87880e0ba037cdb1c50e01850b0831e80eb4f4762f270/lazy_object_proxy-1.12.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6763941dbf97eea6b90f5b06eb4da9418cc088fce0e3883f5816090f9afcde4a", size = 71059, upload-time = "2025-08-22T13:49:50.488Z" }, + { url = "https://files.pythonhosted.org/packages/06/8a/7dcad19c685963c652624702f1a968ff10220b16bfcc442257038216bf55/lazy_object_proxy-1.12.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fdc70d81235fc586b9e3d1aeef7d1553259b62ecaae9db2167a5d2550dcc391a", size = 71034, upload-time = "2025-08-22T13:49:54.224Z" }, + { url = "https://files.pythonhosted.org/packages/12/ac/34cbfb433a10e28c7fd830f91c5a348462ba748413cbb950c7f259e67aa7/lazy_object_proxy-1.12.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:0a83c6f7a6b2bfc11ef3ed67f8cbe99f8ff500b05655d8e7df9aab993a6abc95", size = 69529, upload-time = "2025-08-22T13:49:55.29Z" }, + { url = "https://files.pythonhosted.org/packages/6f/6a/11ad7e349307c3ca4c0175db7a77d60ce42a41c60bcb11800aabd6a8acb8/lazy_object_proxy-1.12.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:256262384ebd2a77b023ad02fbcc9326282bcfd16484d5531154b02bc304f4c5", size = 70391, upload-time = "2025-08-22T13:49:56.35Z" }, + { url = "https://files.pythonhosted.org/packages/59/97/9b410ed8fbc6e79c1ee8b13f8777a80137d4bc189caf2c6202358e66192c/lazy_object_proxy-1.12.0-cp314-cp314-win_amd64.whl", hash = "sha256:7601ec171c7e8584f8ff3f4e440aa2eebf93e854f04639263875b8c2971f819f", size = 26988, upload-time = "2025-08-22T13:49:57.302Z" }, +] + +[[package]] +name = "librt" +version = "0.13.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/2f/3908645ddddab7120b46295e541ead308109fa48dbec7d67d7a778870d60/librt-0.13.0.tar.gz", hash = "sha256:1d2a610c14ac0d0750ee0a3ab8548e83155258387891caaca04def4bf7289781", size = 211402, upload-time = "2026-07-08T12:26:29.834Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f0/f4/b2933ddae222dac338476abb872641169a5cfed2c2bb5444a5b07b32b0c3/librt-0.13.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:30536798f4504c0fad0885b1d371b0539abb081e4570c9d7c641cb51141b49f0", size = 150990, upload-time = "2026-07-08T12:25:02.42Z" }, + { url = "https://files.pythonhosted.org/packages/90/ef/db98f744ca50e6efc9c95c70ee49b77aefac31f6a3fc7c83754a42d6a74f/librt-0.13.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:93d24ebb82aa4420b1409c389e7857bc35bd0b668007ac8172427d5c73cc8cc5", size = 155238, upload-time = "2026-07-08T12:25:03.681Z" }, + { url = "https://files.pythonhosted.org/packages/03/e7/a197e7bc72baf2c61ce7fdc6906a5054dc05bd8da0819aa894e4857bf87e/librt-0.13.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cb8a1adce42d8b75485a5d56a9623a50bcab995b6079f1dac59fc44034dd93d9", size = 503073, upload-time = "2026-07-08T12:25:05.049Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e7/7887712e27da7c1ab80fcabb1de6eb24243964f6557cae530d4b70706dbd/librt-0.13.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:0763ca2ab66058174f9dee426dc64f5e0a89c24a7df8d3fe3f1836c04e25de4b", size = 496528, upload-time = "2026-07-08T12:25:06.26Z" }, + { url = "https://files.pythonhosted.org/packages/94/f0/f2283385bb6b950b26a1410f4ce51ec27231e0b3a4b925c46366d218b198/librt-0.13.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b222493da6e7b6199db9bd79502436cf5a27da3c1f7fa83c7e285444fc93fd03", size = 531786, upload-time = "2026-07-08T12:25:07.658Z" }, + { url = "https://files.pythonhosted.org/packages/36/11/69ac3b54766ffba5fd7e5acebfb048d66dbe1f9f2d14516c2b3edc59cf87/librt-0.13.0-cp312-cp312-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fadc63331f4388c3dc90090448f682a7e9feafc11481391c1e94f2f907a3976e", size = 524393, upload-time = "2026-07-08T12:25:09.121Z" }, + { url = "https://files.pythonhosted.org/packages/61/5f/d72f95fd444a926a3c14b4e24979474116988dd57a45be242077c45d3c22/librt-0.13.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:70d9c62a4cffd9f23396cd5ef93fc5d11b31596b9b7d6306074abe3d5fcf09bd", size = 543026, upload-time = "2026-07-08T12:25:10.459Z" }, + { url = "https://files.pythonhosted.org/packages/c4/08/dcd9993ad192737a004ba263d549f8ea605b326b952e7d6205c7d4170b76/librt-0.13.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:66c0e7e6b02a155576df2c77ec933a70b72da726e248c494abf690923e624348", size = 546829, upload-time = "2026-07-08T12:25:11.716Z" }, + { url = "https://files.pythonhosted.org/packages/96/d5/6d9bb2f54e4109a956b7128836529653eb9d740f784bc47ed10a02c1000e/librt-0.13.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:ac04bcd3328eb91d99dfedf6a60d9c1f15d3434e6f6daf922f0420f7d90b85c7", size = 535700, upload-time = "2026-07-08T12:25:13.144Z" }, + { url = "https://files.pythonhosted.org/packages/8c/f2/10946922503858a359492fa27f13e86228bde702116a740ac7b3cd185f24/librt-0.13.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:db327e7271e653c32040b85ae6188059c924b57d7e1e29f935523fa017cd4e82", size = 573566, upload-time = "2026-07-08T12:25:14.336Z" }, + { url = "https://files.pythonhosted.org/packages/48/a8/94f00e3c99479a18088af3685ea016c42f3c7d5d1964d8dbb40c08d7f1aa/librt-0.13.0-cp312-cp312-win32.whl", hash = "sha256:860bd1d8ba48456ce08feaf8d343a8aaeb2fa086f2bcaa2a923fa3f7a3ff9aa3", size = 106099, upload-time = "2026-07-08T12:25:16.159Z" }, + { url = "https://files.pythonhosted.org/packages/c9/7b/2da9c74c1ed25a89cc4e1c8e007ea2eb4a0f1fafa3e70d757fe3242c5c5c/librt-0.13.0-cp312-cp312-win_amd64.whl", hash = "sha256:e54a315caf843c8d77e388cadc56ea9ded569935ee2d2347d7ea94992e5aa6fa", size = 126934, upload-time = "2026-07-08T12:25:17.275Z" }, + { url = "https://files.pythonhosted.org/packages/d0/65/aead61bbf3b5358593f9d4779d2a0e88eaf6ec191a6342dde36dd1df6371/librt-0.13.0-cp312-cp312-win_arm64.whl", hash = "sha256:c718e99a0992127af84385378460db624103b559ab260435abcfe77a4e4ed1c1", size = 112236, upload-time = "2026-07-08T12:25:18.425Z" }, + { url = "https://files.pythonhosted.org/packages/67/3b/18e7b63255297a2bdc9c25c8d6d4ca8eca9f63aceb1252c0f7427ac7099e/librt-0.13.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a468951af16155824e88bdd8326ebe5bdb371f3ec0ac04642994b98201d914f3", size = 151027, upload-time = "2026-07-08T12:25:19.638Z" }, + { url = "https://files.pythonhosted.org/packages/4d/68/e2248452c00d1a03b45fee1752cdc8f790a476efd2402b75181da88a9e61/librt-0.13.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:ae01d8512cc17079e53425635327dbf3f7ff57a42c00dec348bf79791c56444c", size = 155152, upload-time = "2026-07-08T12:25:20.851Z" }, + { url = "https://files.pythonhosted.org/packages/0e/16/52b1c99bf19057a062aac39c900cbb81499f6f75d6c537c14463d247ba78/librt-0.13.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32c26893cd085c1efe83219e78d866da23fb20a066101b8f68210004361d224c", size = 502499, upload-time = "2026-07-08T12:25:22.055Z" }, + { url = "https://files.pythonhosted.org/packages/9f/54/b811151805c795f55e0dedee6ec687b75f9982a8105d240ea3910737a77b/librt-0.13.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5929da1981a46bcf4b28b1b9499905f0ff58e2419da402a048234e9783acbc4b", size = 496108, upload-time = "2026-07-08T12:25:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/8f/f8/094d6b2bd93f3fdaa54db54cc788c4a365333bddad65ab02e04da0b1d004/librt-0.13.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:94b85d664d777bab6c0d709416cb42938251fda9e221b79e3a2215d85df5f4f9", size = 531576, upload-time = "2026-07-08T12:25:24.648Z" }, + { url = "https://files.pythonhosted.org/packages/2e/40/541733d5755824f968f7ec39d78ffbd75d145964157ae5e69a09ec6d7326/librt-0.13.0-cp313-cp313-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:531b2df3e9fe96b1fcf73a6d165921e4656be5f58d631d384ebce344298368db", size = 524390, upload-time = "2026-07-08T12:25:25.898Z" }, + { url = "https://files.pythonhosted.org/packages/c6/b5/255673cfdbf5ba663339d36cd863c897289ab4337577e19f9405ce059f36/librt-0.13.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:109b84a9edf69ad89dc1f66358659e14a031baca95e3e5b0060bd903ede8efd6", size = 543053, upload-time = "2026-07-08T12:25:27.436Z" }, + { url = "https://files.pythonhosted.org/packages/9e/11/ab5005e9c9850710f21e354201bf090646349d3fabf5f951eaf70235729e/librt-0.13.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:1304368a3e7ffc3e9db986796cc5326fdb5943a3567ecc137cff318e4240c0e7", size = 546387, upload-time = "2026-07-08T12:25:28.65Z" }, + { url = "https://files.pythonhosted.org/packages/a2/04/a5d7ce1d1df1afd15ca283dcdf7530ac073e12d69ae8c40879dda96f7868/librt-0.13.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e4f9b472e7d308d94b62c801982065661158c6ed02790d6c7ddb4337cea0f9c1", size = 535970, upload-time = "2026-07-08T12:25:30.171Z" }, + { url = "https://files.pythonhosted.org/packages/5a/76/927e267a6daa290174ac281b23c9804c8829b042ade9c6f24a065f540958/librt-0.13.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9f836c37478f167a81200d8c8b2c920a22224564bed2c23d7aeec760965c367a", size = 573582, upload-time = "2026-07-08T12:25:31.507Z" }, + { url = "https://files.pythonhosted.org/packages/10/24/b6c5213efe39c19f9e13605644d0cf063b4ddaa33ac2e45b088e23a70e2e/librt-0.13.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:4000d961ff9598ac6ea603c6c836a5ed49bc205ade5fc378b998dfe1e2c36628", size = 82189, upload-time = "2026-07-08T12:25:32.675Z" }, + { url = "https://files.pythonhosted.org/packages/4c/00/d29736be177a906ac0b84a5b04b4fbfa22c776dc2f366de4172b0f968c08/librt-0.13.0-cp313-cp313-win32.whl", hash = "sha256:79e44cff71750d299d61a678e49995b0d5935a9cda238c2574daeca3ba536927", size = 106193, upload-time = "2026-07-08T12:25:33.692Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ac/aff6fb45393cb8912f39dfb156ef6b2d1cadb207ff465fc8f66141054be8/librt-0.13.0-cp313-cp313-win_amd64.whl", hash = "sha256:54dab44a847d5ad1acd05c8a83fe518ae685516ecf4d3f7cc6e3df2a66767650", size = 126962, upload-time = "2026-07-08T12:25:34.769Z" }, + { url = "https://files.pythonhosted.org/packages/d9/3a/d68cb2b334d53fd30fac81d3a489ce4ba0d9506f4df43fcf676b68352b19/librt-0.13.0-cp313-cp313-win_arm64.whl", hash = "sha256:d4cb6fbfdf874340ab5e51450753c0f817b6958a3621125ee695bbc3de866566", size = 112127, upload-time = "2026-07-08T12:25:35.981Z" }, + { url = "https://files.pythonhosted.org/packages/7b/66/f49ae0d592bd45b6941e9a8bafcb6a87cddcd501ee7874707e767f01b585/librt-0.13.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:25218d94b1d2cbc0ba1d8a3f9dc9af578d9646e5ed16443a70cde1dfdcce6d71", size = 149818, upload-time = "2026-07-08T12:25:37.203Z" }, + { url = "https://files.pythonhosted.org/packages/3d/50/51c76d74014d04fb95b6506d286808984b78a2f7a41039094e6b2194ac48/librt-0.13.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:f26629539d4893c2957a16c41bb058e1e135c1f150f6a2e25ed047f64cf3f5c6", size = 154071, upload-time = "2026-07-08T12:25:39.399Z" }, + { url = "https://files.pythonhosted.org/packages/b8/fe/f19b0f5f82d5a1f2da736586bc840abd00ce07d6388136ae80b7333883fc/librt-0.13.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a4517d47b2b8af26975a406fba7d314de9696d864252e0257c6ea90238cfe27f", size = 494168, upload-time = "2026-07-08T12:25:40.641Z" }, + { url = "https://files.pythonhosted.org/packages/94/bc/b8550c75775127fd31a5f20e8775997f7b527ad661fc8ddccd7497c064f7/librt-0.13.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:f19e181de5b3a1148bb3420b8c4b0b0ea0fce6950099724ad151d6cea5acc180", size = 491054, upload-time = "2026-07-08T12:25:41.905Z" }, + { url = "https://files.pythonhosted.org/packages/30/14/4d0204867623df3f33f86efd3d3692ba5e01321443f4d6eab35a22697618/librt-0.13.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22034924f5b42d5a56371cf271771bfeaabf235a7a8b6264bef2d20013f786c6", size = 523006, upload-time = "2026-07-08T12:25:43.327Z" }, + { url = "https://files.pythonhosted.org/packages/19/0a/c45fc9a260934696bace1ac5df1e148ac92bd71767aee3bf7cd7a4534f4c/librt-0.13.0-cp314-cp314-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c7897db4e95e22468bdda33d8e012ceacd0182abf001e6389d763f0def6286b9", size = 515058, upload-time = "2026-07-08T12:25:44.541Z" }, + { url = "https://files.pythonhosted.org/packages/13/0a/50c5ce45b326854ef8fa6ae4c36cf5142e5c55315eaf9e51d0ae73ac4da3/librt-0.13.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:1ce61b3746545029d4f5c17d6bd74b676254ad98433086c846ffb5e8fa73f007", size = 534025, upload-time = "2026-07-08T12:25:45.825Z" }, + { url = "https://files.pythonhosted.org/packages/89/2d/08c413c8f93fc13b8103624fce38e5caa86cd08cbbc8465870ab287af54b/librt-0.13.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:46c330e82565962c761dbce7941be2cff7db674ee807455a8d0cadc5f9b759b0", size = 540557, upload-time = "2026-07-08T12:25:47.059Z" }, + { url = "https://files.pythonhosted.org/packages/b3/c1/93af71fb4a364952210051811dd4e40174e79656b050c89cacac18af3330/librt-0.13.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:375f5af8f99cbaa99dd293af986e3d57caabc9ba81a5d3f021603764854197a1", size = 523201, upload-time = "2026-07-08T12:25:48.392Z" }, + { url = "https://files.pythonhosted.org/packages/c1/6e/9766f07b676a4889d9f8bc2864e9ba5fff165653143ef4dda7df6aa34d16/librt-0.13.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9320d34c3376ae204b2cd176e8d4883a013934e0aef822f1aed9c536490c275d", size = 565740, upload-time = "2026-07-08T12:25:49.678Z" }, + { url = "https://files.pythonhosted.org/packages/a2/1e/664e3472ce2b6e10e9b83f29d4a36eb982ff6b5a169ae7567bba3a4c4ff5/librt-0.13.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:9af313c66157a69dc69ea0059a66961692250e0dc95af9c385a48ffb770a0d16", size = 81611, upload-time = "2026-07-08T12:25:50.857Z" }, + { url = "https://files.pythonhosted.org/packages/2f/d4/8582a4d65e2234673685e07309d02c230b28a85724eb0acbf13f019b7f6e/librt-0.13.0-cp314-cp314-win32.whl", hash = "sha256:f2a7253458e34f33543551394ae4fe104b497ec2a65ac266074de64c1df82e37", size = 100106, upload-time = "2026-07-08T12:25:52.03Z" }, + { url = "https://files.pythonhosted.org/packages/63/ce/0cb99efe6086b46cd985dc26672166fae312a239690e75871f7fafbd3fc5/librt-0.13.0-cp314-cp314-win_amd64.whl", hash = "sha256:a3dfe4edf10e8ed7e55b026a8bfc2c2a8704218b659cd4bffdf604fab966dc39", size = 121209, upload-time = "2026-07-08T12:25:53.166Z" }, + { url = "https://files.pythonhosted.org/packages/26/85/4f3ccb083a3c9b0d42e223acdb3c3f507953324a59cdcab4826e8e2e3b89/librt-0.13.0-cp314-cp314-win_arm64.whl", hash = "sha256:68a5faee4bba381cb93b5961f684a514cf0053cb92308ff9c792c2fea0b174c6", size = 106404, upload-time = "2026-07-08T12:25:54.253Z" }, + { url = "https://files.pythonhosted.org/packages/b2/77/333191499538c8e8189de7a4cba8e6f49ee949fd6d6e6324b21fd1522466/librt-0.13.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:a38fb81d8376dfa2f8963b265fec07637802b0d01e2a127c19c66cb070fb24f5", size = 159231, upload-time = "2026-07-08T12:25:55.432Z" }, + { url = "https://files.pythonhosted.org/packages/7a/9e/2aa83758f22c278b837a1d8025898434ce2b8bff36678d5330ecaef56dff/librt-0.13.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d4c8d9bd5abce34b2e75edb3bf37ab0f34e49b1f915a40ae8468eb7c85bc5b46", size = 161300, upload-time = "2026-07-08T12:25:56.585Z" }, + { url = "https://files.pythonhosted.org/packages/bb/c0/86791e936553ca763d6b3c2fb4d31d596cd00e14fa631c283a40ba01559a/librt-0.13.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:387e2f1d27e89bffe0d3f520f0da0662c973fd607ca16c1808f8a5085419485e", size = 582056, upload-time = "2026-07-08T12:25:58.144Z" }, + { url = "https://files.pythonhosted.org/packages/a8/d3/a9ec15984a185e000c4d2a16ba28bd623124ad4c38a10974c7ff78e3a893/librt-0.13.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:4f6db193d2e5e0ed60359b9a5a682cd67205d0d3b1e459a867dd4b5c4e7eaa7a", size = 562758, upload-time = "2026-07-08T12:25:59.544Z" }, + { url = "https://files.pythonhosted.org/packages/3c/af/dbe36b78b19c06a55097f99305e4ea9458e2273e6ae16a3cbecaad7ee978/librt-0.13.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0d38604854e8d22faadf683ec6c02bb0f886e2ba56ef981a1c36ee275f21ea22", size = 602095, upload-time = "2026-07-08T12:26:00.991Z" }, + { url = "https://files.pythonhosted.org/packages/2a/a8/2966891b4dd2830f5203fbee92ac2c4947653a2390ba73dfa44244fad025/librt-0.13.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:371f7ce73026815dafd51c50ce38416e91428b28c4b2ec97cd39271164b0045c", size = 593452, upload-time = "2026-07-08T12:26:02.352Z" }, + { url = "https://files.pythonhosted.org/packages/61/f5/4df8bfc8405ecf8c0d525b4d69636f694bdd8620b313ec8b76e54a5926cc/librt-0.13.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3aaedf52171bee90860704c560bc798fe83b76247df47568e0197e9b13c735a0", size = 623729, upload-time = "2026-07-08T12:26:04.294Z" }, + { url = "https://files.pythonhosted.org/packages/d6/13/9ac202dffc8db06f75d06c08c2f9f6ff054be67d21272dcc078fa1cc0c57/librt-0.13.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:96bad8725a4f196a798366c25ce075d1f7543a4ec045ffc13e6a7ec095cdab04", size = 617077, upload-time = "2026-07-08T12:26:05.845Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f0/ebe38610716aee5cb28efd95089bb90192096179802779381e1c5dcf239c/librt-0.13.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:6bf6a559ffe4a93bbea6cf31ddf01a7fd9ba342ef51f27beb178e318b74acd61", size = 599561, upload-time = "2026-07-08T12:26:07.21Z" }, + { url = "https://files.pythonhosted.org/packages/4f/5c/c2e72e236fff7abc716d5b1753b8b8cd3ea85ac46fe17d2e7c51d4e1c723/librt-0.13.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:301067672387902c55f94b51d5022304b36c966ea9fe1f21caab99a9bef487c9", size = 645511, upload-time = "2026-07-08T12:26:08.562Z" }, + { url = "https://files.pythonhosted.org/packages/0c/99/6203ce619dee940d6bfbe099ec3fe4be00a68e9d60f70abf906cf124fe66/librt-0.13.0-cp314-cp314t-win32.whl", hash = "sha256:5fdcf34f86de8fb66d7dc7589f96ba91c4aa46671200d400e6fd6f109a483f18", size = 104357, upload-time = "2026-07-08T12:26:09.828Z" }, + { url = "https://files.pythonhosted.org/packages/52/dd/843b6314087c41657c7036d7914d8f294bdf9b580aa8513ea0588c8e9a3d/librt-0.13.0-cp314-cp314t-win_amd64.whl", hash = "sha256:260c33e92263fa629b4f6d3c51967a1c2158fe6c33237aaa3ebeac586b085259", size = 126998, upload-time = "2026-07-08T12:26:10.975Z" }, + { url = "https://files.pythonhosted.org/packages/5f/5d/3dcec2884ba1b0806d1408612555c38dd5d68e90156b59f75f6e36435c3a/librt-0.13.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2f281549a4c52ac7bb97997f14353f8bd0e53a34ca0dad1c905cfd0b4a58ae99", size = 110771, upload-time = "2026-07-08T12:26:12.303Z" }, +] + +[[package]] +name = "markdown" +version = "3.10.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2b/f4/69fa6ed85ae003c2378ffa8f6d2e3234662abd02c10d216c0ba96081a238/markdown-3.10.2.tar.gz", hash = "sha256:994d51325d25ad8aa7ce4ebaec003febcce822c3f8c911e3b17c52f7f589f950", size = 368805, upload-time = "2026-02-09T14:57:26.942Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/1f/77fa3081e4f66ca3576c896ae5d31c3002ac6607f9747d2e3aa49227e464/markdown-3.10.2-py3-none-any.whl", hash = "sha256:e91464b71ae3ee7afd3017d9f358ef0baf158fd9a298db92f1d4761133824c36", size = 108180, upload-time = "2026-02-09T14:57:25.787Z" }, +] + +[[package]] +name = "markdown-exec" +version = "1.12.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pymdown-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6d/76/c47da8edb6a12b066728432fb3724109d9d91de5331df5073d12d272493f/markdown_exec-1.12.3.tar.gz", hash = "sha256:006b9cac46470a9499797bc9c579305ae4719e0a8e495e5401dfbf1e66ce7fb4", size = 77841, upload-time = "2026-07-07T09:53:13.838Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/a7/0279016386d611183ccc508c5688eb1e2133e8182164d7a2c6213b176f69/markdown_exec-1.12.3-py3-none-any.whl", hash = "sha256:48ac12a565f3f4331b1acd9efc48a0773e717eb7ca7c38e23c1d72ee61660de6", size = 37995, upload-time = "2026-07-07T09:53:12.619Z" }, +] + +[package.optional-dependencies] +ansi = [ + { name = "pygments-ansi-color" }, +] + +[[package]] +name = "markdown-it-py" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + +[[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 = "mike" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "mkdocs" }, + { name = "pyparsing" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "verspec" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/47/fa87e9d56bef16cdfe34b059a437e8c6f7ec6f1b9c378871c3cf95ebea9c/mike-2.2.0.tar.gz", hash = "sha256:1e3858e32c0f125aac14432fc7848434358f9ae0962c5c5cde387ad47f6ad25e", size = 38450, upload-time = "2026-04-14T04:59:03.944Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/8e/56ccb09c7232a55403a7637caa21922f3b65901a37f5e8bdb405d0de0946/mike-2.2.0-py3-none-any.whl", hash = "sha256:e1f4981c1152eec7c2490a3401142292cc47d686194188416db2648fdfe1d040", size = 34026, upload-time = "2026-04-14T04:59:02.602Z" }, +] + +[[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.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/c0/f641843de3f612a6b48253f39244165acff36657a91cc903633d456ae1ac/mkdocs_autorefs-1.4.4.tar.gz", hash = "sha256:d54a284f27a7346b9c38f1f852177940c222da508e66edc816a0fa55fc6da197", size = 56588, upload-time = "2026-02-10T15:23:55.105Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/de/a3e710469772c6a89595fc52816da05c1e164b4c866a89e3cb82fb1b67c5/mkdocs_autorefs-1.4.4-py3-none-any.whl", hash = "sha256:834ef5408d827071ad1bc69e0f39704fa34c7fc05bc8e1c72b227dfdc5c76089", size = 25530, upload-time = "2026-02-10T15:23:53.817Z" }, +] + +[[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.optional-dependencies] +imaging = [ + { name = "cairosvg" }, + { name = "pillow" }, +] + +[[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 = "mkdocs-redirects" +version = "1.2.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mkdocs" }, + { name = "properdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/25/49725f78ca5d3026b09973f7a2b3a8b179cc2e8c15e43d5a13bc79f6b274/mkdocs_redirects-1.2.3.tar.gz", hash = "sha256:5e980330999299729a2d6a125347d1af78023d68a23681a4de3053ce7dfe2e51", size = 7712, upload-time = "2026-03-28T13:57:41.766Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/90/871b1cddc01d2ba1637b858eeeabc2e3013dc8df591306b5567b98ef0870/mkdocs_redirects-1.2.3-py3-none-any.whl", hash = "sha256:ec7312fff462d03ec16395d0c001006a418f8d0c21cdf2b47ff11cf839dc3ce0", size = 6245, upload-time = "2026-03-28T13:57:40.466Z" }, +] + +[[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.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/b6/e858701499d57eee8b3fd8e78168083956c6683ddbe727b46758b19e1119/mkdocstrings_python-2.0.5.tar.gz", hash = "sha256:3a4d92556ad39637e88af94a5374213af9a8e3040c3824ceaed04b486c017594", size = 199578, upload-time = "2026-06-19T10:41:08.868Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/fc/10ab7e80650a9c9e8f4f1105f8c8e73567f88ed0c06ada589ab81d38687c/mkdocstrings_python-2.0.5-py3-none-any.whl", hash = "sha256:30c837bbff016549f659fcba6539ac351303f0fd7e713c89a040611072236e9d", size = 104951, upload-time = "2026-06-19T10:41:07.378Z" }, +] + +[[package]] +name = "moto" +version = "5.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "boto3" }, + { name = "botocore" }, + { name = "cryptography" }, + { name = "requests" }, + { name = "responses" }, + { name = "werkzeug" }, + { name = "xmltodict" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/47/63/d944f387582cc53f53febbff2b3fa36a6d2ed7c1feef8990bf646cfa9cba/moto-5.2.2.tar.gz", hash = "sha256:aac8023a429e125e91c91f8f4730a67b54f518cda587352f7e67252fe3168f75", size = 8678761, upload-time = "2026-06-06T18:57:54.931Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/45/13cff46f4f617a6e97e1d497d75abd913e250bb4c823a4985668c6e593e4/moto-5.2.2-py3-none-any.whl", hash = "sha256:3817f1e39721ca833579b921e53e3b68547ace6a34d848c9486fbb5905808de9", size = 6698689, upload-time = "2026-06-06T18:57:51.435Z" }, +] + +[package.optional-dependencies] +s3 = [ + { name = "py-partiql-parser" }, + { name = "pyyaml" }, +] +server = [ + { name = "antlr4-python3-runtime" }, + { name = "aws-xray-sdk" }, + { name = "cfn-lint" }, + { name = "docker" }, + { name = "flask" }, + { name = "flask-cors" }, + { name = "graphql-core" }, + { name = "joserfc" }, + { name = "jsonpath-ng" }, + { name = "openapi-spec-validator" }, + { name = "py-partiql-parser" }, + { name = "pyparsing" }, + { name = "pyyaml" }, + { name = "setuptools" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "msgpack" +version = "1.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/31/f9/c0a1c127f9049db9155afc316952ea571720dd01833ff5e4d7e8e6352dbb/msgpack-1.2.1.tar.gz", hash = "sha256:04c721c2c7448767e9e3f2520a475663d8ee0f09c31890f6d2bd70fd636a9647", size = 183960, upload-time = "2026-06-18T16:13:52.594Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/dd/9e8cbd8f5582ca4b590336f2b91ee5662f6a6ca562b565abaf696a0f81ff/msgpack-1.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2ef59c659f289eddf8aa6623823f19fa2f40a4029266889eac7a2505dd210c35", size = 83531, upload-time = "2026-06-18T16:12:58.249Z" }, + { url = "https://files.pythonhosted.org/packages/50/2e/ebdb85a8da151397a2790363676b7ed7c125924fe618e4c6d8befb0cc62c/msgpack-1.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d3567748a5107cb40cdf66a275430c2f87c07777698f4bfd25c35f44d533258c", size = 82657, upload-time = "2026-06-18T16:12:59.396Z" }, + { url = "https://files.pythonhosted.org/packages/26/aa/753ad8b007b464e1d8aa0c8e650b9c5f4f725e658fc5ac8a7635c55b7f6e/msgpack-1.2.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:60926b75d00c8e816ef98f3034f484a8bc64242d66839cef4cf7e503142316a0", size = 410634, upload-time = "2026-06-18T16:13:00.383Z" }, + { url = "https://files.pythonhosted.org/packages/6a/fd/6adabd4f6d5e686f97dd02ce7fce3fe4cf672cbac36b8f67ff4040e8ad8b/msgpack-1.2.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:020e881a764b20d8d7ca1a54fc01b8175519d108e3c3f194fddc200bda95951a", size = 419989, upload-time = "2026-06-18T16:13:01.776Z" }, + { url = "https://files.pythonhosted.org/packages/5a/cc/85039b7b0eb168aaad7383a23c97e291a11f08351cb45a606ce865e4e3f1/msgpack-1.2.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4202c74688ca06591f78cb18988228bd4cca2cc75d57b60008372892d2f1e6e6", size = 377544, upload-time = "2026-06-18T16:13:03.637Z" }, + { url = "https://files.pythonhosted.org/packages/ed/bf/35963899493b32030c85fc513b723ae66144ac70c11ebc52e889e16e3d99/msgpack-1.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8b267ce94efb76fbd1b3373511420074ee3187f0f7811bf394531de13294735a", size = 400842, upload-time = "2026-06-18T16:13:05.012Z" }, + { url = "https://files.pythonhosted.org/packages/a6/df/8e2ac970c8f99264cd9997d1c73df5466bc19da3301d7dc5500862a9b089/msgpack-1.2.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e4f1d0f8f98ade9634e01fb704a408f9336c0a8f1117b369f5db83dc7551d8b1", size = 374108, upload-time = "2026-06-18T16:13:06.232Z" }, + { url = "https://files.pythonhosted.org/packages/17/dd/fa8bd265110dfa51c20cb529f9e6d240a16fafe7e645004c6af2d01353ba/msgpack-1.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f02cf17a6ca1abe29b5f980644f7551f94d71f2011509b26d8625ce038f0df64", size = 414939, upload-time = "2026-06-18T16:13:07.478Z" }, + { url = "https://files.pythonhosted.org/packages/2e/b9/8377a5ad8953fc0437c70cc98d9ae29f27fe5ac5109fbec0812085865735/msgpack-1.2.1-cp312-cp312-win32.whl", hash = "sha256:0c0d9802354507bcba62af19c17918e3eb437cc25e6f50657d511b5856a77aac", size = 64504, upload-time = "2026-06-18T16:13:08.822Z" }, + { url = "https://files.pythonhosted.org/packages/57/7f/ce1e377df7e62461fefd9eb23bfb93a4a523f40a517b377b8f844d836828/msgpack-1.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:5c24aa15d5963051e1a5c62b12c50cd705992502b5ec1f3bece6046f33c9fc24", size = 71421, upload-time = "2026-06-18T16:13:09.828Z" }, + { url = "https://files.pythonhosted.org/packages/8f/32/ebfe84c9929f08f188d56c7a2fd913406a9ddad76a634697c1c43b8112e6/msgpack-1.2.1-cp312-cp312-win_arm64.whl", hash = "sha256:4227224aaec8f7fbcbfbd4272319347b2bb4030366502600f8c45588c5187b07", size = 64775, upload-time = "2026-06-18T16:13:11.056Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ac/dcddcab6f6c20ecb387ca5e980371cdb3f87ff69aeca388be97eebc4c074/msgpack-1.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0a70e3cf2804a300d921bb0940426e35f4e489a23adfb77a808892241db0a064", size = 83151, upload-time = "2026-06-18T16:13:12.173Z" }, + { url = "https://files.pythonhosted.org/packages/64/71/fbcfa83a1d6a9c6091942d1cfd070962244664b87427a9a49a6897b1b219/msgpack-1.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:491cc39455ca765fad51fb451bf2915eb2cf41192ab5801ce8d67c1d614fe056", size = 82351, upload-time = "2026-06-18T16:13:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/e3/10/ddf7b06db879e8792d13934ddda09ff20bd2a583fd84c9b59aae9b0e650b/msgpack-1.2.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f310233ef7fb9c14e201c93639fe5f5260b005f56f0b29048e999c30935596cc", size = 407518, upload-time = "2026-06-18T16:13:14.233Z" }, + { url = "https://files.pythonhosted.org/packages/79/d3/36a46a8ed992b781acbc05928bd5bee3c810cb0c3563bf81a7b0c04a1a76/msgpack-1.2.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:787c9bebb5833e8f6fc8abca3c0597683d8d87f56a8842b6b89c75a5f3176e2d", size = 416405, upload-time = "2026-06-18T16:13:15.435Z" }, + { url = "https://files.pythonhosted.org/packages/f9/84/e8e9598b557c0ba6ddae901a73780a4c75ac667dddf59414b1e56a42fb34/msgpack-1.2.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dc871b997a9370d855b7394465f2f350e847a5b806dd38dcc9c989e7d87da155", size = 376257, upload-time = "2026-06-18T16:13:17.022Z" }, + { url = "https://files.pythonhosted.org/packages/40/16/738fe6d875ad7e2a9429c165322a4ec088f4f273cdfae63d96a89c467961/msgpack-1.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:85f57e960d877f2977f6430896191b04a21f8901b3b4baf2e4604329f4db5402", size = 397469, upload-time = "2026-06-18T16:13:18.287Z" }, + { url = "https://files.pythonhosted.org/packages/ca/be/6d5952df75a7f24f35833af764c3a6860780364cb3a0030beb8099e1b2b4/msgpack-1.2.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:1233ee2dd0cefba127583de50ea654677277047d238303521db35def3d7b2e7c", size = 372802, upload-time = "2026-06-18T16:13:19.685Z" }, + { url = "https://files.pythonhosted.org/packages/e1/39/e2ef7dbf0473bcb8dc7c50bf782a892d67414877b63e47fc88eb189ef5e6/msgpack-1.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3dc2feb0876209d9c38aa56cb1de169bd6c4348f1aa48271f241226590993e6", size = 411273, upload-time = "2026-06-18T16:13:21.028Z" }, + { url = "https://files.pythonhosted.org/packages/ef/c5/133f4512a56e983a93445c836c9d94d88f3bc2e0980ff4b9e577bd8416ce/msgpack-1.2.1-cp313-cp313-win32.whl", hash = "sha256:6d09badf350af2be9d189184e04e64cf54ad93569ab3d96fca58bd3e84aad707", size = 64471, upload-time = "2026-06-18T16:13:22.293Z" }, + { url = "https://files.pythonhosted.org/packages/e2/98/577e10b055096a7dd40732358cabaf7180a20c79ed1dcdbb618e4b9deac7/msgpack-1.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:33f14fba63278b714efe6ad07e50ea5f03d91537aa6a1c5f1ceca4cf44013ca9", size = 71274, upload-time = "2026-06-18T16:13:23.455Z" }, + { url = "https://files.pythonhosted.org/packages/ba/ee/0c0048e7cfbef23c6a94791b8959ab28155232e7956de8a305b5ff588f05/msgpack-1.2.1-cp313-cp313-win_arm64.whl", hash = "sha256:afc5febcd4c99effbc02b528e49d6fd0760b2b7d48c05239e345a5fa6e743d9a", size = 64795, upload-time = "2026-06-18T16:13:24.687Z" }, + { url = "https://files.pythonhosted.org/packages/77/58/cce442852c6b9e1639c7c8ac8fd9143121cb32dab0f308df4d1426a8eb9c/msgpack-1.2.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:05f340e47e7e47d2da8db9b53e1bb1d294369e9ef45a747441309f6650b8351d", size = 83610, upload-time = "2026-06-18T16:13:25.724Z" }, + { url = "https://files.pythonhosted.org/packages/60/5c/15b4c7a0182f75ffa90751958ba36a9c01cafee367d49a3edc10ed140b01/msgpack-1.2.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:810b916696c86ef0deb3b74588480224df4c1b071136c34183e4a2a4284d7ac7", size = 83138, upload-time = "2026-06-18T16:13:26.781Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a6/99e58722feaffc5f2fbcc0c8c0d1451ab9f84097f7af87291b46af2390f4/msgpack-1.2.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ca0dacff965c47afdc3749a8469d7302a8f801d6a28758d55120d75e66ce6889", size = 406090, upload-time = "2026-06-18T16:13:28.072Z" }, + { url = "https://files.pythonhosted.org/packages/19/03/8c63e8cf52958534ef688625965ab04c269a6cadd8caef16758b380a821a/msgpack-1.2.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e2bf9280bceb5efca998435904b5d3e9fdbcc11d90dc9df30aec7973252b720", size = 412106, upload-time = "2026-06-18T16:13:29.427Z" }, + { url = "https://files.pythonhosted.org/packages/63/d2/155d9e71b40e41fd934bc0c48b9b2770f22263e1ac20aad8e29fdca7be3f/msgpack-1.2.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:aa6c4be5d1c02a42b066ca6ddb71adf36432868fdcdb6ee87e634e86e0674190", size = 374851, upload-time = "2026-06-18T16:13:30.631Z" }, + { url = "https://files.pythonhosted.org/packages/98/48/deaf2326262a8d5ea3295ce9649912ecd3f551ba7ec8e33c665d2ba583f3/msgpack-1.2.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec0e675d59150a6269ddc9139087c722292664a37d071a849c05c473350f1f2d", size = 396168, upload-time = "2026-06-18T16:13:31.977Z" }, + { url = "https://files.pythonhosted.org/packages/10/2a/b4410f906c2ec0008f1608d3ab5143afc3ad3f4e6da0fed3ea2231d0bef4/msgpack-1.2.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:dd3bfe82d53edfe4b7fc9a7ec9761e23a7a5b1dac22264505af428253c29ed24", size = 371959, upload-time = "2026-06-18T16:13:33.282Z" }, + { url = "https://files.pythonhosted.org/packages/59/86/1edc67270099a528fa2093ea60fe191233cd238e4bd30cfacf7db79fc959/msgpack-1.2.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5ad5467fc3f68b5468e06c5f788d712e9f8ffc8b0cd1bcb160c105c1ee92dae7", size = 408457, upload-time = "2026-06-18T16:13:34.567Z" }, + { url = "https://files.pythonhosted.org/packages/82/90/8b630fef07d8c5ab457b71ff2c217910c83d333c7a68472c186e87cc504a/msgpack-1.2.1-cp314-cp314-win32.whl", hash = "sha256:98b58bdb89c46190e4609bb36abe17c6d4105ad13f9c5f8f6f64d320f8ced3fb", size = 65942, upload-time = "2026-06-18T16:13:36.056Z" }, + { url = "https://files.pythonhosted.org/packages/16/f1/467b81e98b24dd3885d7b1857728797b4ffc76a7a7483af4fb321a07de3c/msgpack-1.2.1-cp314-cp314-win_amd64.whl", hash = "sha256:74847557e28ce71bd3c438a447ca90e4b507e997ddbdef8a12a7b283b86c156b", size = 72627, upload-time = "2026-06-18T16:13:37.079Z" }, + { url = "https://files.pythonhosted.org/packages/a7/1d/5d8c4c89985feb6acefb82a09e501c60392261856d2408d20bfe4f0360b1/msgpack-1.2.1-cp314-cp314-win_arm64.whl", hash = "sha256:b50b727bd652bdc37d950336c848ef20ec54a4cafc38dce19b1cd86ad625d0f7", size = 66908, upload-time = "2026-06-18T16:13:38.23Z" }, + { url = "https://files.pythonhosted.org/packages/1b/02/ad2afb678b4de94496cd432b581759b756a92c1192d8c767edd6b132efdc/msgpack-1.2.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:8d00f177ca88a77c1cf848d204a38f249751650b601cb6532acc68805d8a8273", size = 86000, upload-time = "2026-06-18T16:13:39.44Z" }, + { url = "https://files.pythonhosted.org/packages/54/74/0b797484013128837f3b1cbb6cea019277c4de4e377dc512b4d9a0f92940/msgpack-1.2.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5bb9c386f0a329c035ddbab4b72d1028bf9627add8dda41070288563d57ed1b1", size = 86544, upload-time = "2026-06-18T16:13:40.447Z" }, + { url = "https://files.pythonhosted.org/packages/a9/b4/b774d7eb95561739907fec675582f83203cf41c597a418c2589b4bfb8e9d/msgpack-1.2.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20466cca18c49c7292a8984bc15d65857b171e7264bdcb5f96baf8be238791fc", size = 427661, upload-time = "2026-06-18T16:13:41.574Z" }, + { url = "https://files.pythonhosted.org/packages/b2/f9/3243191dc9937e00756c8bc1b0272fed8f23758e43df2a3b46f533e5090f/msgpack-1.2.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:196300e7e5d6e74d50f1607ab9c06c4a1484c383cd22defd727902591f7e8dde", size = 426375, upload-time = "2026-06-18T16:13:42.936Z" }, + { url = "https://files.pythonhosted.org/packages/23/c7/1693111db9944ba4ad4b67a1e788400d78a0b6af7a6523dc7e4e58f8274b/msgpack-1.2.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:575957e79cd51903a4e8495a242442949641e08f1efd5197b43bebd3ea7682b4", size = 380495, upload-time = "2026-06-18T16:13:44.306Z" }, + { url = "https://files.pythonhosted.org/packages/3e/2b/92f86956a0c13e8662f7e2ad630c4eb4db07497b967589bd5245e018b2c1/msgpack-1.2.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8c2ed1e48cc0f460bf3c7780e7137ff21a4e18433451916f2442c1b21036cd7d", size = 410897, upload-time = "2026-06-18T16:13:45.629Z" }, + { url = "https://files.pythonhosted.org/packages/da/ea/1479f72d200313a76fc2f823a79d1e07ed052ab7b8a0280640aa7b95de42/msgpack-1.2.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:5f6277e5f783c36786a145e0247fc189a03f35f84b251646e53592d2bc12b355", size = 378519, upload-time = "2026-06-18T16:13:46.998Z" }, + { url = "https://files.pythonhosted.org/packages/f5/4d/fa006060ffa1011d32bfae826fe766fe73e02982183601633b7121058ab3/msgpack-1.2.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f9389552ecf4784886345ead0647e4edc96bee37cbab05b75540f542f766c48c", size = 419815, upload-time = "2026-06-18T16:13:48.205Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/aab6c946570496b78e67804721f3d5e2d62a93081b9b37df77764ef56347/msgpack-1.2.1-cp314-cp314t-win32.whl", hash = "sha256:c1c79a604a2969a868a78b6ebd27a887e00c624f14f66b3038e0590cb23332d1", size = 70914, upload-time = "2026-06-18T16:13:49.385Z" }, + { url = "https://files.pythonhosted.org/packages/13/0a/e608956488a2af014cfe6e3d665e090b8ee42aa14b07f8f95b8880d66b09/msgpack-1.2.1-cp314-cp314t-win_amd64.whl", hash = "sha256:f12038a35fabd52e56a3547bab42401af49a45caa6dd00b34c44de235bc93ee2", size = 77999, upload-time = "2026-06-18T16:13:50.467Z" }, + { url = "https://files.pythonhosted.org/packages/d2/8a/27e2e57055176e366a46b85d02d68e7a5bcfbdd8474c9706375d965f24d3/msgpack-1.2.1-cp314-cp314t-win_arm64.whl", hash = "sha256:0adcf06ffde0777c0e1a9b771a2b1c4226ba1bbf748c8efcc02fcdeca3299107", size = 71160, upload-time = "2026-06-18T16:13:51.498Z" }, +] + +[[package]] +name = "msgspec" +version = "0.21.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/60/f79b9b013a16fa3a58350c9295ddc6789f2e335f36ea61ed10a21b215364/msgspec-0.21.1.tar.gz", hash = "sha256:2313508e394b0d208f8f56892ca9b2799e2561329de9763b19619595a6c0f72c", size = 319193, upload-time = "2026-04-12T21:44:50.394Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6e/cf/317224852c00248c620a9bcf4b26e2e4ab8afd752f18d2a6ef73ebd423b6/msgspec-0.21.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d4248cf0b6129b7d230eacd493c17cc2d4f3989f3bb7f633a928a85b7dcfa251", size = 196188, upload-time = "2026-04-12T21:44:07.181Z" }, + { url = "https://files.pythonhosted.org/packages/6d/81/074612945c0666078f7366f40000013de9f6ba687491d450df699bceebc9/msgspec-0.21.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5102c7e9b3acff82178449b85006d96310e690291bb1ea0142f1b24bcb8aabcb", size = 188473, upload-time = "2026-04-12T21:44:08.736Z" }, + { url = "https://files.pythonhosted.org/packages/8a/37/655101799590bcc5fddb2bd3fe0e6194e816c2d1da7c361725f5eb89a910/msgspec-0.21.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:846758412e9518252b2ac9bffd6f0e54d9ff614f5f9488df7749f81ff5c80920", size = 218871, upload-time = "2026-04-12T21:44:09.917Z" }, + { url = "https://files.pythonhosted.org/packages/b5/d1/d4cd9fe89c7d400d7a18f86ccc94daa3f0927f53558846fcb60791dce5d6/msgspec-0.21.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:21995e74b5c598c2e004110ad66ec7f1b8c20bf2bcf3b2de8fd9a3094422d3ff", size = 225025, upload-time = "2026-04-12T21:44:11.191Z" }, + { url = "https://files.pythonhosted.org/packages/24/bf/e20549e602b9edccadeeff98760345a416f9cce846a657e8b18e3396b212/msgspec-0.21.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6129f0cca52992e898fd5344187f7c8127b63d810b2fd73e36fca73b4c6475ee", size = 222672, upload-time = "2026-04-12T21:44:12.481Z" }, + { url = "https://files.pythonhosted.org/packages/b4/68/04d7a8f0f786545cf9b8c280c57aa6befb5977af6e884b8b54191cbe44b3/msgspec-0.21.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ef3ec2296248d1f8b9231acb051b6d471dfde8f21819e86c9adaaa9f42918521", size = 227303, upload-time = "2026-04-12T21:44:13.709Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4d/619866af2840875be408047bf9e70ceafbae6ab50660de7134ed1b25eb86/msgspec-0.21.1-cp312-cp312-win_amd64.whl", hash = "sha256:d4ab834a054c6f0cbeef6df9e7e1b33d5f1bc7b86dea1d2fd7cad003873e783d", size = 190017, upload-time = "2026-04-12T21:44:14.977Z" }, + { url = "https://files.pythonhosted.org/packages/5e/2e/a8f9eca8fd00e097d7a9e99ba8a4685db994494448e3d4f0b7f6e9a3c0f7/msgspec-0.21.1-cp312-cp312-win_arm64.whl", hash = "sha256:628aaa35c74950a8c59da330d7e98917e1c7188f983745782027748ee4ca573e", size = 175345, upload-time = "2026-04-12T21:44:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/7e/74/f11ede02839b19ff459f88e3145df5d711626ca84da4e23520cebf819367/msgspec-0.21.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:764173717a01743f007e9f74520ed281f24672c604514f7d76c1c3a10e8edb66", size = 196176, upload-time = "2026-04-12T21:44:17.613Z" }, + { url = "https://files.pythonhosted.org/packages/bb/40/4476c1bd341418a046c4955aff632ec769315d1e3cb94e6acf86d461f9ed/msgspec-0.21.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:344c7cd0eaed1fb81d7959f99100ef71ec9b536881a376f11b9a6c4803365697", size = 188524, upload-time = "2026-04-12T21:44:18.815Z" }, + { url = "https://files.pythonhosted.org/packages/ca/d9/9e9d7d7e5061b47540d03d640fab9b3965ba7ae49c1b2154861c8f007518/msgspec-0.21.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:48943e278b3854c2f89f955ddc6f9f430d3f0784b16e47d10604ee0463cd21f5", size = 218880, upload-time = "2026-04-12T21:44:20.028Z" }, + { url = "https://files.pythonhosted.org/packages/74/66/2bb344f34abb4b57e60c7c9c761994e0417b9718ec1460bf00c296f2a7ea/msgspec-0.21.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a9aa659ebb0101b1cbc31461212b87e341d961f0ab0772aaf068a99e001ec4aa", size = 225050, upload-time = "2026-04-12T21:44:21.577Z" }, + { url = "https://files.pythonhosted.org/packages/1a/84/7c1e412f76092277bf760cef12b7979d03314d259ab5b5cafde5d0c1722d/msgspec-0.21.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7b27d1a8ead2b6f5b0c4f2d07b8be1ccfcc041c8a0e704781edebe3ae13c484", size = 222713, upload-time = "2026-04-12T21:44:22.83Z" }, + { url = "https://files.pythonhosted.org/packages/4e/27/0bba04b2b4ef05f3d068429410bc71d2cea925f1596a8f41152cccd5edb8/msgspec-0.21.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:38fe93e86b61328fe544cb7fd871fad5a27c8734bfda90f65e5dbe288ae50f61", size = 227259, upload-time = "2026-04-12T21:44:24.11Z" }, + { url = "https://files.pythonhosted.org/packages/b0/2d/09574b0eea02fed2c2c1383dbaae2c7f79dc16dcd6487a886000afb5d7c4/msgspec-0.21.1-cp313-cp313-win_amd64.whl", hash = "sha256:8bc666331c35fcce05a7cd2d6221adbe0f6058f8e750711413d22793c080ac6a", size = 189857, upload-time = "2026-04-12T21:44:25.359Z" }, + { url = "https://files.pythonhosted.org/packages/46/34/105b1576ad182879914f0c821f17ee1d13abb165cb060448f96fe2aff078/msgspec-0.21.1-cp313-cp313-win_arm64.whl", hash = "sha256:42bb1241e0750c1a4346f2aa84db26c5ffd99a4eb3a954927d9f149ff2f42898", size = 175403, upload-time = "2026-04-12T21:44:26.608Z" }, + { url = "https://files.pythonhosted.org/packages/5a/ad/86954e987d1d6a5c579e2c2e7832b65e0fff194179fdac4f581536086024/msgspec-0.21.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fab48eb45fdbfbdb2c0edfec00ffc53b6b6085beefc6b50b61e01659f9f8757f", size = 196261, upload-time = "2026-04-12T21:44:27.807Z" }, + { url = "https://files.pythonhosted.org/packages/d1/a1/c5e46c3e42b866199365e35d11dddfd1fbd8bba4fdb3c52f965b1607ce94/msgspec-0.21.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3cb779ea0c35bc807ff941d415875c1f69ca0be91a2e907ab99a171811d86a9a", size = 188729, upload-time = "2026-04-12T21:44:28.99Z" }, + { url = "https://files.pythonhosted.org/packages/85/7d/1e29a319d678d6cb962ae5bdf32a6858ebdf38f73bc654c0e9c742a0c2c8/msgspec-0.21.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:68604db36b3b4dd9bf160e436e12798a4738848144cea1aca1cb984011eb160f", size = 219866, upload-time = "2026-04-12T21:44:31.104Z" }, + { url = "https://files.pythonhosted.org/packages/25/1f/cca084ca2572810fff12ea9dbdcbe39eac048f40daf4a9077b49fcbe8cee/msgspec-0.21.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d6b9dc50948eaf65df54d2fd0ff66e6d8c32f116037209ee861810eb9b676cb", size = 224993, upload-time = "2026-04-12T21:44:32.649Z" }, + { url = "https://files.pythonhosted.org/packages/71/94/d2120fc9d419a89a3a7c13e5b7078798c4b392a96a02a6e2b3ce43a8766c/msgspec-0.21.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:52c5e21930942302394429c5a582ce7e6b62c7f983b3760834c2ce107e0dd6df", size = 223535, upload-time = "2026-04-12T21:44:33.839Z" }, + { url = "https://files.pythonhosted.org/packages/75/17/42418b66a3ad972a89bab73dd78b79cc6282bb488a25e73c853cee7443b9/msgspec-0.21.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:abbb39d65681fa24ed394e01af3d59d869068324f900c61d06062b7fb9980f2f", size = 227222, upload-time = "2026-04-12T21:44:35.093Z" }, + { url = "https://files.pythonhosted.org/packages/c4/33/265c894268cca88ff67b144ca2b4c522fc8b9a6f1966a3640c70516e78e1/msgspec-0.21.1-cp314-cp314-win_amd64.whl", hash = "sha256:5666b1b560b97b6ec2eb3fca8a502298ebac56e13bbca1f88523538ce83d01ea", size = 193810, upload-time = "2026-04-12T21:44:36.612Z" }, + { url = "https://files.pythonhosted.org/packages/3b/8f/a6d35f25bf1fc63c492fdd88fdce01ba0875ead48c2b91f90f33653b4131/msgspec-0.21.1-cp314-cp314-win_arm64.whl", hash = "sha256:d8b8578e4c83b14ceea4cef0d0b747e31d9330fe4b03b2b2ad4063866a178f93", size = 179125, upload-time = "2026-04-12T21:44:38.198Z" }, + { url = "https://files.pythonhosted.org/packages/c6/39/74839641e64b99d87da55af0fc472854d42b46e2183b9e2a67fe1bb2a512/msgspec-0.21.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:15f523d51c00ebad412213bfe9f06f0a50ec2b93e0c19e824a2d267cabb48ea2", size = 200171, upload-time = "2026-04-12T21:44:39.414Z" }, + { url = "https://files.pythonhosted.org/packages/70/9b/ce0cca6d2d87fcd4b6ff97600790494e64f26a2c55d61507cd2755c16193/msgspec-0.21.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:4e47390360583ba3d5c6cb44cf0a9f61b0a06a899d3c2c00627cedebb2e2884b", size = 192879, upload-time = "2026-04-12T21:44:40.882Z" }, + { url = "https://files.pythonhosted.org/packages/a7/08/673a7bb05e5702dc787ddd3011195b509f9867927970da59052211929987/msgspec-0.21.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f60800e6299b798142dc40b0644da77ceac5ea0568be58228417eae14135c847", size = 226281, upload-time = "2026-04-12T21:44:42.181Z" }, + { url = "https://files.pythonhosted.org/packages/7d/45/86508cf57283e9070b3c447e3ab25b792a7a0855a3ea4e0c6d111ac34c97/msgspec-0.21.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f8e9dfcd98419cf7568808470c4317a3fb30bef0e3715b568730a2b272a20d7", size = 229863, upload-time = "2026-04-12T21:44:43.442Z" }, + { url = "https://files.pythonhosted.org/packages/2c/62/e7c9367cd08d590559faacd711edbae36840342843e669440363f33c7d36/msgspec-0.21.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:92d89dfad13bd1ea640dc3e37e724ed380da1030b272bdf5ecafb983c3ad7c75", size = 230445, upload-time = "2026-04-12T21:44:44.806Z" }, + { url = "https://files.pythonhosted.org/packages/42/b4/c0f54632103846b658a10930025f4de41c8724b5e4805a5f3b395586cb7e/msgspec-0.21.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0d03867786e5d7ba25d666df4b11320c27170f4aeafcb8e3a8b0a50a4fb742ca", size = 231822, upload-time = "2026-04-12T21:44:46.343Z" }, + { url = "https://files.pythonhosted.org/packages/ea/1d/0d85cc79d0ccf5508e9c846cc66552a6a16bf92abd1dbd8362617f7b35cd/msgspec-0.21.1-cp314-cp314t-win_amd64.whl", hash = "sha256:740fbf1c9d59992ca3537d6fbe9ebbf9eaf726a65fbf31448e0ecbc710697a63", size = 206650, upload-time = "2026-04-12T21:44:47.601Z" }, + { url = "https://files.pythonhosted.org/packages/90/91/56c5d560f20e6c20e9e4f55bd0e458f7f162aa689ee350346c04c48eac0b/msgspec-0.21.1-cp314-cp314t-win_arm64.whl", hash = "sha256:0d2cc73df6058d811a126ac3a8ad63a4dfa210c82f9cf5a004802eaf4712de90", size = 183149, upload-time = "2026-04-12T21:44:48.833Z" }, +] + +[[package]] +name = "multidict" +version = "6.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1a/c2/c2d94cbe6ac1753f3fc980da97b3d930efe1da3af3c9f5125354436c073d/multidict-6.7.1.tar.gz", hash = "sha256:ec6652a1bee61c53a3e5776b6049172c53b6aaba34f18c9ad04f82712bac623d", size = 102010, upload-time = "2026-01-26T02:46:45.979Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8d/9c/f20e0e2cf80e4b2e4b1c365bf5fe104ee633c751a724246262db8f1a0b13/multidict-6.7.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a90f75c956e32891a4eda3639ce6dd86e87105271f43d43442a3aedf3cddf172", size = 76893, upload-time = "2026-01-26T02:43:52.754Z" }, + { url = "https://files.pythonhosted.org/packages/fe/cf/18ef143a81610136d3da8193da9d80bfe1cb548a1e2d1c775f26b23d024a/multidict-6.7.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fccb473e87eaa1382689053e4a4618e7ba7b9b9b8d6adf2027ee474597128cd", size = 45456, upload-time = "2026-01-26T02:43:53.893Z" }, + { url = "https://files.pythonhosted.org/packages/a9/65/1caac9d4cd32e8433908683446eebc953e82d22b03d10d41a5f0fefe991b/multidict-6.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b0fa96985700739c4c7853a43c0b3e169360d6855780021bfc6d0f1ce7c123e7", size = 43872, upload-time = "2026-01-26T02:43:55.041Z" }, + { url = "https://files.pythonhosted.org/packages/cf/3b/d6bd75dc4f3ff7c73766e04e705b00ed6dbbaccf670d9e05a12b006f5a21/multidict-6.7.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cb2a55f408c3043e42b40cc8eecd575afa27b7e0b956dfb190de0f8499a57a53", size = 251018, upload-time = "2026-01-26T02:43:56.198Z" }, + { url = "https://files.pythonhosted.org/packages/fd/80/c959c5933adedb9ac15152e4067c702a808ea183a8b64cf8f31af8ad3155/multidict-6.7.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb0ce7b2a32d09892b3dd6cc44877a0d02a33241fafca5f25c8b6b62374f8b75", size = 258883, upload-time = "2026-01-26T02:43:57.499Z" }, + { url = "https://files.pythonhosted.org/packages/86/85/7ed40adafea3d4f1c8b916e3b5cc3a8e07dfcdcb9cd72800f4ed3ca1b387/multidict-6.7.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c3a32d23520ee37bf327d1e1a656fec76a2edd5c038bf43eddfa0572ec49c60b", size = 242413, upload-time = "2026-01-26T02:43:58.755Z" }, + { url = "https://files.pythonhosted.org/packages/d2/57/b8565ff533e48595503c785f8361ff9a4fde4d67de25c207cd0ba3befd03/multidict-6.7.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c90fed18bffc0189ba814749fdcc102b536e83a9f738a9003e569acd540a733", size = 268404, upload-time = "2026-01-26T02:44:00.216Z" }, + { url = "https://files.pythonhosted.org/packages/e0/50/9810c5c29350f7258180dfdcb2e52783a0632862eb334c4896ac717cebcb/multidict-6.7.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:da62917e6076f512daccfbbde27f46fed1c98fee202f0559adec8ee0de67f71a", size = 269456, upload-time = "2026-01-26T02:44:02.202Z" }, + { url = "https://files.pythonhosted.org/packages/f3/8d/5e5be3ced1d12966fefb5c4ea3b2a5b480afcea36406559442c6e31d4a48/multidict-6.7.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bfde23ef6ed9db7eaee6c37dcec08524cb43903c60b285b172b6c094711b3961", size = 256322, upload-time = "2026-01-26T02:44:03.56Z" }, + { url = "https://files.pythonhosted.org/packages/31/6e/d8a26d81ac166a5592782d208dd90dfdc0a7a218adaa52b45a672b46c122/multidict-6.7.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3758692429e4e32f1ba0df23219cd0b4fc0a52f476726fff9337d1a57676a582", size = 253955, upload-time = "2026-01-26T02:44:04.845Z" }, + { url = "https://files.pythonhosted.org/packages/59/4c/7c672c8aad41534ba619bcd4ade7a0dc87ed6b8b5c06149b85d3dd03f0cd/multidict-6.7.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:398c1478926eca669f2fd6a5856b6de9c0acf23a2cb59a14c0ba5844fa38077e", size = 251254, upload-time = "2026-01-26T02:44:06.133Z" }, + { url = "https://files.pythonhosted.org/packages/7b/bd/84c24de512cbafbdbc39439f74e967f19570ce7924e3007174a29c348916/multidict-6.7.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c102791b1c4f3ab36ce4101154549105a53dc828f016356b3e3bcae2e3a039d3", size = 252059, upload-time = "2026-01-26T02:44:07.518Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ba/f5449385510825b73d01c2d4087bf6d2fccc20a2d42ac34df93191d3dd03/multidict-6.7.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a088b62bd733e2ad12c50dad01b7d0166c30287c166e137433d3b410add807a6", size = 263588, upload-time = "2026-01-26T02:44:09.382Z" }, + { url = "https://files.pythonhosted.org/packages/d7/11/afc7c677f68f75c84a69fe37184f0f82fce13ce4b92f49f3db280b7e92b3/multidict-6.7.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d51ff4785d58d3f6c91bdbffcb5e1f7ddfda557727043aa20d20ec4f65e324a", size = 259642, upload-time = "2026-01-26T02:44:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/2b/17/ebb9644da78c4ab36403739e0e6e0e30ebb135b9caf3440825001a0bddcb/multidict-6.7.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc5907494fccf3e7d3f94f95c91d6336b092b5fc83811720fae5e2765890dfba", size = 251377, upload-time = "2026-01-26T02:44:12.042Z" }, + { url = "https://files.pythonhosted.org/packages/ca/a4/840f5b97339e27846c46307f2530a2805d9d537d8b8bd416af031cad7fa0/multidict-6.7.1-cp312-cp312-win32.whl", hash = "sha256:28ca5ce2fd9716631133d0e9a9b9a745ad7f60bac2bccafb56aa380fc0b6c511", size = 41887, upload-time = "2026-01-26T02:44:14.245Z" }, + { url = "https://files.pythonhosted.org/packages/80/31/0b2517913687895f5904325c2069d6a3b78f66cc641a86a2baf75a05dcbb/multidict-6.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcee94dfbd638784645b066074b338bc9cc155d4b4bffa4adce1615c5a426c19", size = 46053, upload-time = "2026-01-26T02:44:15.371Z" }, + { url = "https://files.pythonhosted.org/packages/0c/5b/aba28e4ee4006ae4c7df8d327d31025d760ffa992ea23812a601d226e682/multidict-6.7.1-cp312-cp312-win_arm64.whl", hash = "sha256:ba0a9fb644d0c1a2194cf7ffb043bd852cea63a57f66fbd33959f7dae18517bf", size = 43307, upload-time = "2026-01-26T02:44:16.852Z" }, + { url = "https://files.pythonhosted.org/packages/f2/22/929c141d6c0dba87d3e1d38fbdf1ba8baba86b7776469f2bc2d3227a1e67/multidict-6.7.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2b41f5fed0ed563624f1c17630cb9941cf2309d4df00e494b551b5f3e3d67a23", size = 76174, upload-time = "2026-01-26T02:44:18.509Z" }, + { url = "https://files.pythonhosted.org/packages/c7/75/bc704ae15fee974f8fccd871305e254754167dce5f9e42d88a2def741a1d/multidict-6.7.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:84e61e3af5463c19b67ced91f6c634effb89ef8bfc5ca0267f954451ed4bb6a2", size = 45116, upload-time = "2026-01-26T02:44:19.745Z" }, + { url = "https://files.pythonhosted.org/packages/79/76/55cd7186f498ed080a18440c9013011eb548f77ae1b297206d030eb1180a/multidict-6.7.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:935434b9853c7c112eee7ac891bc4cb86455aa631269ae35442cb316790c1445", size = 43524, upload-time = "2026-01-26T02:44:21.571Z" }, + { url = "https://files.pythonhosted.org/packages/e9/3c/414842ef8d5a1628d68edee29ba0e5bcf235dbfb3ccd3ea303a7fe8c72ff/multidict-6.7.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:432feb25a1cb67fe82a9680b4d65fb542e4635cb3166cd9c01560651ad60f177", size = 249368, upload-time = "2026-01-26T02:44:22.803Z" }, + { url = "https://files.pythonhosted.org/packages/f6/32/befed7f74c458b4a525e60519fe8d87eef72bb1e99924fa2b0f9d97a221e/multidict-6.7.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e82d14e3c948952a1a85503817e038cba5905a3352de76b9a465075d072fba23", size = 256952, upload-time = "2026-01-26T02:44:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/03/d6/c878a44ba877f366630c860fdf74bfb203c33778f12b6ac274936853c451/multidict-6.7.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4cfb48c6ea66c83bcaaf7e4dfa7ec1b6bbcf751b7db85a328902796dfde4c060", size = 240317, upload-time = "2026-01-26T02:44:25.772Z" }, + { url = "https://files.pythonhosted.org/packages/68/49/57421b4d7ad2e9e60e25922b08ceb37e077b90444bde6ead629095327a6f/multidict-6.7.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1d540e51b7e8e170174555edecddbd5538105443754539193e3e1061864d444d", size = 267132, upload-time = "2026-01-26T02:44:27.648Z" }, + { url = "https://files.pythonhosted.org/packages/b7/fe/ec0edd52ddbcea2a2e89e174f0206444a61440b40f39704e64dc807a70bd/multidict-6.7.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:273d23f4b40f3dce4d6c8a821c741a86dec62cded82e1175ba3d99be128147ed", size = 268140, upload-time = "2026-01-26T02:44:29.588Z" }, + { url = "https://files.pythonhosted.org/packages/b0/73/6e1b01cbeb458807aa0831742232dbdd1fa92bfa33f52a3f176b4ff3dc11/multidict-6.7.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d624335fd4fa1c08a53f8b4be7676ebde19cd092b3895c421045ca87895b429", size = 254277, upload-time = "2026-01-26T02:44:30.902Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b2/5fb8c124d7561a4974c342bc8c778b471ebbeb3cc17df696f034a7e9afe7/multidict-6.7.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:12fad252f8b267cc75b66e8fc51b3079604e8d43a75428ffe193cd9e2195dfd6", size = 252291, upload-time = "2026-01-26T02:44:32.31Z" }, + { url = "https://files.pythonhosted.org/packages/5a/96/51d4e4e06bcce92577fcd488e22600bd38e4fd59c20cb49434d054903bd2/multidict-6.7.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:03ede2a6ffbe8ef936b92cb4529f27f42be7f56afcdab5ab739cd5f27fb1cbf9", size = 250156, upload-time = "2026-01-26T02:44:33.734Z" }, + { url = "https://files.pythonhosted.org/packages/db/6b/420e173eec5fba721a50e2a9f89eda89d9c98fded1124f8d5c675f7a0c0f/multidict-6.7.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:90efbcf47dbe33dcf643a1e400d67d59abeac5db07dc3f27d6bdeae497a2198c", size = 249742, upload-time = "2026-01-26T02:44:35.222Z" }, + { url = "https://files.pythonhosted.org/packages/44/a3/ec5b5bd98f306bc2aa297b8c6f11a46714a56b1e6ef5ebda50a4f5d7c5fb/multidict-6.7.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5c4b9bfc148f5a91be9244d6264c53035c8a0dcd2f51f1c3c6e30e30ebaa1c84", size = 262221, upload-time = "2026-01-26T02:44:36.604Z" }, + { url = "https://files.pythonhosted.org/packages/cd/f7/e8c0d0da0cd1e28d10e624604e1a36bcc3353aaebdfdc3a43c72bc683a12/multidict-6.7.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:401c5a650f3add2472d1d288c26deebc540f99e2fb83e9525007a74cd2116f1d", size = 258664, upload-time = "2026-01-26T02:44:38.008Z" }, + { url = "https://files.pythonhosted.org/packages/52/da/151a44e8016dd33feed44f730bd856a66257c1ee7aed4f44b649fb7edeb3/multidict-6.7.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:97891f3b1b3ffbded884e2916cacf3c6fc87b66bb0dde46f7357404750559f33", size = 249490, upload-time = "2026-01-26T02:44:39.386Z" }, + { url = "https://files.pythonhosted.org/packages/87/af/a3b86bf9630b732897f6fc3f4c4714b90aa4361983ccbdcd6c0339b21b0c/multidict-6.7.1-cp313-cp313-win32.whl", hash = "sha256:e1c5988359516095535c4301af38d8a8838534158f649c05dd1050222321bcb3", size = 41695, upload-time = "2026-01-26T02:44:41.318Z" }, + { url = "https://files.pythonhosted.org/packages/b2/35/e994121b0e90e46134673422dd564623f93304614f5d11886b1b3e06f503/multidict-6.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:960c83bf01a95b12b08fd54324a4eb1d5b52c88932b5cba5d6e712bb3ed12eb5", size = 45884, upload-time = "2026-01-26T02:44:42.488Z" }, + { url = "https://files.pythonhosted.org/packages/ca/61/42d3e5dbf661242a69c97ea363f2d7b46c567da8eadef8890022be6e2ab0/multidict-6.7.1-cp313-cp313-win_arm64.whl", hash = "sha256:563fe25c678aaba333d5399408f5ec3c383ca5b663e7f774dd179a520b8144df", size = 43122, upload-time = "2026-01-26T02:44:43.664Z" }, + { url = "https://files.pythonhosted.org/packages/6d/b3/e6b21c6c4f314bb956016b0b3ef2162590a529b84cb831c257519e7fde44/multidict-6.7.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:c76c4bec1538375dad9d452d246ca5368ad6e1c9039dadcf007ae59c70619ea1", size = 83175, upload-time = "2026-01-26T02:44:44.894Z" }, + { url = "https://files.pythonhosted.org/packages/fb/76/23ecd2abfe0957b234f6c960f4ade497f55f2c16aeb684d4ecdbf1c95791/multidict-6.7.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:57b46b24b5d5ebcc978da4ec23a819a9402b4228b8a90d9c656422b4bdd8a963", size = 48460, upload-time = "2026-01-26T02:44:46.106Z" }, + { url = "https://files.pythonhosted.org/packages/c4/57/a0ed92b23f3a042c36bc4227b72b97eca803f5f1801c1ab77c8a212d455e/multidict-6.7.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e954b24433c768ce78ab7929e84ccf3422e46deb45a4dc9f93438f8217fa2d34", size = 46930, upload-time = "2026-01-26T02:44:47.278Z" }, + { url = "https://files.pythonhosted.org/packages/b5/66/02ec7ace29162e447f6382c495dc95826bf931d3818799bbef11e8f7df1a/multidict-6.7.1-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3bd231490fa7217cc832528e1cd8752a96f0125ddd2b5749390f7c3ec8721b65", size = 242582, upload-time = "2026-01-26T02:44:48.604Z" }, + { url = "https://files.pythonhosted.org/packages/58/18/64f5a795e7677670e872673aca234162514696274597b3708b2c0d276cce/multidict-6.7.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:253282d70d67885a15c8a7716f3a73edf2d635793ceda8173b9ecc21f2fb8292", size = 250031, upload-time = "2026-01-26T02:44:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ed/e192291dbbe51a8290c5686f482084d31bcd9d09af24f63358c3d42fd284/multidict-6.7.1-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0b4c48648d7649c9335cf1927a8b87fa692de3dcb15faa676c6a6f1f1aabda43", size = 228596, upload-time = "2026-01-26T02:44:51.951Z" }, + { url = "https://files.pythonhosted.org/packages/1e/7e/3562a15a60cf747397e7f2180b0a11dc0c38d9175a650e75fa1b4d325e15/multidict-6.7.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:98bc624954ec4d2c7cb074b8eefc2b5d0ce7d482e410df446414355d158fe4ca", size = 257492, upload-time = "2026-01-26T02:44:53.902Z" }, + { url = "https://files.pythonhosted.org/packages/24/02/7d0f9eae92b5249bb50ac1595b295f10e263dd0078ebb55115c31e0eaccd/multidict-6.7.1-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1b99af4d9eec0b49927b4402bcbb58dea89d3e0db8806a4086117019939ad3dd", size = 255899, upload-time = "2026-01-26T02:44:55.316Z" }, + { url = "https://files.pythonhosted.org/packages/00/e3/9b60ed9e23e64c73a5cde95269ef1330678e9c6e34dd4eb6b431b85b5a10/multidict-6.7.1-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6aac4f16b472d5b7dc6f66a0d49dd57b0e0902090be16594dc9ebfd3d17c47e7", size = 247970, upload-time = "2026-01-26T02:44:56.783Z" }, + { url = "https://files.pythonhosted.org/packages/3e/06/538e58a63ed5cfb0bd4517e346b91da32fde409d839720f664e9a4ae4f9d/multidict-6.7.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:21f830fe223215dffd51f538e78c172ed7c7f60c9b96a2bf05c4848ad49921c3", size = 245060, upload-time = "2026-01-26T02:44:58.195Z" }, + { url = "https://files.pythonhosted.org/packages/b2/2f/d743a3045a97c895d401e9bd29aaa09b94f5cbdf1bd561609e5a6c431c70/multidict-6.7.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:f5dd81c45b05518b9aa4da4aa74e1c93d715efa234fd3e8a179df611cc85e5f4", size = 235888, upload-time = "2026-01-26T02:44:59.57Z" }, + { url = "https://files.pythonhosted.org/packages/38/83/5a325cac191ab28b63c52f14f1131f3b0a55ba3b9aa65a6d0bf2a9b921a0/multidict-6.7.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:eb304767bca2bb92fb9c5bd33cedc95baee5bb5f6c88e63706533a1c06ad08c8", size = 243554, upload-time = "2026-01-26T02:45:01.054Z" }, + { url = "https://files.pythonhosted.org/packages/20/1f/9d2327086bd15da2725ef6aae624208e2ef828ed99892b17f60c344e57ed/multidict-6.7.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:c9035dde0f916702850ef66460bc4239d89d08df4d02023a5926e7446724212c", size = 252341, upload-time = "2026-01-26T02:45:02.484Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2c/2a1aa0280cf579d0f6eed8ee5211c4f1730bd7e06c636ba2ee6aafda302e/multidict-6.7.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:af959b9beeb66c822380f222f0e0a1889331597e81f1ded7f374f3ecb0fd6c52", size = 246391, upload-time = "2026-01-26T02:45:03.862Z" }, + { url = "https://files.pythonhosted.org/packages/e5/03/7ca022ffc36c5a3f6e03b179a5ceb829be9da5783e6fe395f347c0794680/multidict-6.7.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:41f2952231456154ee479651491e94118229844dd7226541788be783be2b5108", size = 243422, upload-time = "2026-01-26T02:45:05.296Z" }, + { url = "https://files.pythonhosted.org/packages/dc/1d/b31650eab6c5778aceed46ba735bd97f7c7d2f54b319fa916c0f96e7805b/multidict-6.7.1-cp313-cp313t-win32.whl", hash = "sha256:df9f19c28adcb40b6aae30bbaa1478c389efd50c28d541d76760199fc1037c32", size = 47770, upload-time = "2026-01-26T02:45:06.754Z" }, + { url = "https://files.pythonhosted.org/packages/ac/5b/2d2d1d522e51285bd61b1e20df8f47ae1a9d80839db0b24ea783b3832832/multidict-6.7.1-cp313-cp313t-win_amd64.whl", hash = "sha256:d54ecf9f301853f2c5e802da559604b3e95bb7a3b01a9c295c6ee591b9882de8", size = 53109, upload-time = "2026-01-26T02:45:08.044Z" }, + { url = "https://files.pythonhosted.org/packages/3d/a3/cc409ba012c83ca024a308516703cf339bdc4b696195644a7215a5164a24/multidict-6.7.1-cp313-cp313t-win_arm64.whl", hash = "sha256:5a37ca18e360377cfda1d62f5f382ff41f2b8c4ccb329ed974cc2e1643440118", size = 45573, upload-time = "2026-01-26T02:45:09.349Z" }, + { url = "https://files.pythonhosted.org/packages/91/cc/db74228a8be41884a567e88a62fd589a913708fcf180d029898c17a9a371/multidict-6.7.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8f333ec9c5eb1b7105e3b84b53141e66ca05a19a605368c55450b6ba208cb9ee", size = 75190, upload-time = "2026-01-26T02:45:10.651Z" }, + { url = "https://files.pythonhosted.org/packages/d5/22/492f2246bb5b534abd44804292e81eeaf835388901f0c574bac4eeec73c5/multidict-6.7.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a407f13c188f804c759fc6a9f88286a565c242a76b27626594c133b82883b5c2", size = 44486, upload-time = "2026-01-26T02:45:11.938Z" }, + { url = "https://files.pythonhosted.org/packages/f1/4f/733c48f270565d78b4544f2baddc2fb2a245e5a8640254b12c36ac7ac68e/multidict-6.7.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0e161ddf326db5577c3a4cc2d8648f81456e8a20d40415541587a71620d7a7d1", size = 43219, upload-time = "2026-01-26T02:45:14.346Z" }, + { url = "https://files.pythonhosted.org/packages/24/bb/2c0c2287963f4259c85e8bcbba9182ced8d7fca65c780c38e99e61629d11/multidict-6.7.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:1e3a8bb24342a8201d178c3b4984c26ba81a577c80d4d525727427460a50c22d", size = 245132, upload-time = "2026-01-26T02:45:15.712Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f9/44d4b3064c65079d2467888794dea218d1601898ac50222ab8a9a8094460/multidict-6.7.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97231140a50f5d447d3164f994b86a0bed7cd016e2682f8650d6a9158e14fd31", size = 252420, upload-time = "2026-01-26T02:45:17.293Z" }, + { url = "https://files.pythonhosted.org/packages/8b/13/78f7275e73fa17b24c9a51b0bd9d73ba64bb32d0ed51b02a746eb876abe7/multidict-6.7.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b10359683bd8806a200fd2909e7c8ca3a7b24ec1d8132e483d58e791d881048", size = 233510, upload-time = "2026-01-26T02:45:19.356Z" }, + { url = "https://files.pythonhosted.org/packages/4b/25/8167187f62ae3cbd52da7893f58cb036b47ea3fb67138787c76800158982/multidict-6.7.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:283ddac99f7ac25a4acadbf004cb5ae34480bbeb063520f70ce397b281859362", size = 264094, upload-time = "2026-01-26T02:45:20.834Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e7/69a3a83b7b030cf283fb06ce074a05a02322359783424d7edf0f15fe5022/multidict-6.7.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:538cec1e18c067d0e6103aa9a74f9e832904c957adc260e61cd9d8cf0c3b3d37", size = 260786, upload-time = "2026-01-26T02:45:22.818Z" }, + { url = "https://files.pythonhosted.org/packages/fe/3b/8ec5074bcfc450fe84273713b4b0a0dd47c0249358f5d82eb8104ffe2520/multidict-6.7.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7eee46ccb30ff48a1e35bb818cc90846c6be2b68240e42a78599166722cea709", size = 248483, upload-time = "2026-01-26T02:45:24.368Z" }, + { url = "https://files.pythonhosted.org/packages/48/5a/d5a99e3acbca0e29c5d9cba8f92ceb15dce78bab963b308ae692981e3a5d/multidict-6.7.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa263a02f4f2dd2d11a7b1bb4362aa7cb1049f84a9235d31adf63f30143469a0", size = 248403, upload-time = "2026-01-26T02:45:25.982Z" }, + { url = "https://files.pythonhosted.org/packages/35/48/e58cd31f6c7d5102f2a4bf89f96b9cf7e00b6c6f3d04ecc44417c00a5a3c/multidict-6.7.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:2e1425e2f99ec5bd36c15a01b690a1a2456209c5deed58f95469ffb46039ccbb", size = 240315, upload-time = "2026-01-26T02:45:27.487Z" }, + { url = "https://files.pythonhosted.org/packages/94/33/1cd210229559cb90b6786c30676bb0c58249ff42f942765f88793b41fdce/multidict-6.7.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:497394b3239fc6f0e13a78a3e1b61296e72bf1c5f94b4c4eb80b265c37a131cd", size = 245528, upload-time = "2026-01-26T02:45:28.991Z" }, + { url = "https://files.pythonhosted.org/packages/64/f2/6e1107d226278c876c783056b7db43d800bb64c6131cec9c8dfb6903698e/multidict-6.7.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:233b398c29d3f1b9676b4b6f75c518a06fcb2ea0b925119fb2c1bc35c05e1601", size = 258784, upload-time = "2026-01-26T02:45:30.503Z" }, + { url = "https://files.pythonhosted.org/packages/4d/c1/11f664f14d525e4a1b5327a82d4de61a1db604ab34c6603bb3c2cc63ad34/multidict-6.7.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:93b1818e4a6e0930454f0f2af7dfce69307ca03cdcfb3739bf4d91241967b6c1", size = 251980, upload-time = "2026-01-26T02:45:32.603Z" }, + { url = "https://files.pythonhosted.org/packages/e1/9f/75a9ac888121d0c5bbd4ecf4eead45668b1766f6baabfb3b7f66a410e231/multidict-6.7.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f33dc2a3abe9249ea5d8360f969ec7f4142e7ac45ee7014d8f8d5acddf178b7b", size = 243602, upload-time = "2026-01-26T02:45:34.043Z" }, + { url = "https://files.pythonhosted.org/packages/9a/e7/50bf7b004cc8525d80dbbbedfdc7aed3e4c323810890be4413e589074032/multidict-6.7.1-cp314-cp314-win32.whl", hash = "sha256:3ab8b9d8b75aef9df299595d5388b14530839f6422333357af1339443cff777d", size = 40930, upload-time = "2026-01-26T02:45:36.278Z" }, + { url = "https://files.pythonhosted.org/packages/e0/bf/52f25716bbe93745595800f36fb17b73711f14da59ed0bb2eba141bc9f0f/multidict-6.7.1-cp314-cp314-win_amd64.whl", hash = "sha256:5e01429a929600e7dab7b166062d9bb54a5eed752384c7384c968c2afab8f50f", size = 45074, upload-time = "2026-01-26T02:45:37.546Z" }, + { url = "https://files.pythonhosted.org/packages/97/ab/22803b03285fa3a525f48217963da3a65ae40f6a1b6f6cf2768879e208f9/multidict-6.7.1-cp314-cp314-win_arm64.whl", hash = "sha256:4885cb0e817aef5d00a2e8451d4665c1808378dc27c2705f1bf4ef8505c0d2e5", size = 42471, upload-time = "2026-01-26T02:45:38.889Z" }, + { url = "https://files.pythonhosted.org/packages/e0/6d/f9293baa6146ba9507e360ea0292b6422b016907c393e2f63fc40ab7b7b5/multidict-6.7.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0458c978acd8e6ea53c81eefaddbbee9c6c5e591f41b3f5e8e194780fe026581", size = 82401, upload-time = "2026-01-26T02:45:40.254Z" }, + { url = "https://files.pythonhosted.org/packages/7a/68/53b5494738d83558d87c3c71a486504d8373421c3e0dbb6d0db48ad42ee0/multidict-6.7.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:c0abd12629b0af3cf590982c0b413b1e7395cd4ec026f30986818ab95bfaa94a", size = 48143, upload-time = "2026-01-26T02:45:41.635Z" }, + { url = "https://files.pythonhosted.org/packages/37/e8/5284c53310dcdc99ce5d66563f6e5773531a9b9fe9ec7a615e9bc306b05f/multidict-6.7.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:14525a5f61d7d0c94b368a42cff4c9a4e7ba2d52e2672a7b23d84dc86fb02b0c", size = 46507, upload-time = "2026-01-26T02:45:42.99Z" }, + { url = "https://files.pythonhosted.org/packages/e4/fc/6800d0e5b3875568b4083ecf5f310dcf91d86d52573160834fb4bfcf5e4f/multidict-6.7.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:17307b22c217b4cf05033dabefe68255a534d637c6c9b0cc8382718f87be4262", size = 239358, upload-time = "2026-01-26T02:45:44.376Z" }, + { url = "https://files.pythonhosted.org/packages/41/75/4ad0973179361cdf3a113905e6e088173198349131be2b390f9fa4da5fc6/multidict-6.7.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a7e590ff876a3eaf1c02a4dfe0724b6e69a9e9de6d8f556816f29c496046e59", size = 246884, upload-time = "2026-01-26T02:45:47.167Z" }, + { url = "https://files.pythonhosted.org/packages/c3/9c/095bb28b5da139bd41fb9a5d5caff412584f377914bd8787c2aa98717130/multidict-6.7.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5fa6a95dfee63893d80a34758cd0e0c118a30b8dcb46372bf75106c591b77889", size = 225878, upload-time = "2026-01-26T02:45:48.698Z" }, + { url = "https://files.pythonhosted.org/packages/07/d0/c0a72000243756e8f5a277b6b514fa005f2c73d481b7d9e47cd4568aa2e4/multidict-6.7.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a0543217a6a017692aa6ae5cc39adb75e587af0f3a82288b1492eb73dd6cc2a4", size = 253542, upload-time = "2026-01-26T02:45:50.164Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6b/f69da15289e384ecf2a68837ec8b5ad8c33e973aa18b266f50fe55f24b8c/multidict-6.7.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f99fe611c312b3c1c0ace793f92464d8cd263cc3b26b5721950d977b006b6c4d", size = 252403, upload-time = "2026-01-26T02:45:51.779Z" }, + { url = "https://files.pythonhosted.org/packages/a2/76/b9669547afa5a1a25cd93eaca91c0da1c095b06b6d2d8ec25b713588d3a1/multidict-6.7.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9004d8386d133b7e6135679424c91b0b854d2d164af6ea3f289f8f2761064609", size = 244889, upload-time = "2026-01-26T02:45:53.27Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a9/a50d2669e506dad33cfc45b5d574a205587b7b8a5f426f2fbb2e90882588/multidict-6.7.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e628ef0e6859ffd8273c69412a2465c4be4a9517d07261b33334b5ec6f3c7489", size = 241982, upload-time = "2026-01-26T02:45:54.919Z" }, + { url = "https://files.pythonhosted.org/packages/c5/bb/1609558ad8b456b4827d3c5a5b775c93b87878fd3117ed3db3423dfbce1b/multidict-6.7.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:841189848ba629c3552035a6a7f5bf3b02eb304e9fea7492ca220a8eda6b0e5c", size = 232415, upload-time = "2026-01-26T02:45:56.981Z" }, + { url = "https://files.pythonhosted.org/packages/d8/59/6f61039d2aa9261871e03ab9dc058a550d240f25859b05b67fd70f80d4b3/multidict-6.7.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:ce1bbd7d780bb5a0da032e095c951f7014d6b0a205f8318308140f1a6aba159e", size = 240337, upload-time = "2026-01-26T02:45:58.698Z" }, + { url = "https://files.pythonhosted.org/packages/a1/29/fdc6a43c203890dc2ae9249971ecd0c41deaedfe00d25cb6564b2edd99eb/multidict-6.7.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b26684587228afed0d50cf804cc71062cc9c1cdf55051c4c6345d372947b268c", size = 248788, upload-time = "2026-01-26T02:46:00.862Z" }, + { url = "https://files.pythonhosted.org/packages/a9/14/a153a06101323e4cf086ecee3faadba52ff71633d471f9685c42e3736163/multidict-6.7.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9f9af11306994335398293f9958071019e3ab95e9a707dc1383a35613f6abcb9", size = 242842, upload-time = "2026-01-26T02:46:02.824Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/604ae839e64a4a6efc80db94465348d3b328ee955e37acb24badbcd24d83/multidict-6.7.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b4938326284c4f1224178a560987b6cf8b4d38458b113d9b8c1db1a836e640a2", size = 240237, upload-time = "2026-01-26T02:46:05.898Z" }, + { url = "https://files.pythonhosted.org/packages/5f/60/c3a5187bf66f6fb546ff4ab8fb5a077cbdd832d7b1908d4365c7f74a1917/multidict-6.7.1-cp314-cp314t-win32.whl", hash = "sha256:98655c737850c064a65e006a3df7c997cd3b220be4ec8fe26215760b9697d4d7", size = 48008, upload-time = "2026-01-26T02:46:07.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/f7/addf1087b860ac60e6f382240f64fb99f8bfb532bb06f7c542b83c29ca61/multidict-6.7.1-cp314-cp314t-win_amd64.whl", hash = "sha256:497bde6223c212ba11d462853cfa4f0ae6ef97465033e7dc9940cdb3ab5b48e5", size = 53542, upload-time = "2026-01-26T02:46:08.809Z" }, + { url = "https://files.pythonhosted.org/packages/4c/81/4629d0aa32302ef7b2ec65c75a728cc5ff4fa410c50096174c1632e70b3e/multidict-6.7.1-cp314-cp314t-win_arm64.whl", hash = "sha256:2bbd113e0d4af5db41d5ebfe9ccaff89de2120578164f86a5d17d5a576d1e5b2", size = 44719, upload-time = "2026-01-26T02:46:11.146Z" }, + { url = "https://files.pythonhosted.org/packages/81/08/7036c080d7117f28a4af526d794aab6a84463126db031b007717c1a6676e/multidict-6.7.1-py3-none-any.whl", hash = "sha256:55d97cc6dae627efa6a6e548885712d4864b81110ac76fa4e534c03819fa4a56", size = 12319, upload-time = "2026-01-26T02:46:44.004Z" }, +] + +[[package]] +name = "mypy" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ast-serialize" }, + { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, + { name = "mypy-extensions" }, + { name = "pathspec" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/12/af/4e516a05d3ca2eb9283e9ec45b2c02225c1514dd6da49fd3c9eaa6639370/mypy-2.3.0.tar.gz", hash = "sha256:465965d41cd9a2726694e983e8ce7113259327bec798115d1e1dfa2a52fb666e", size = 3988104, upload-time = "2026-07-13T11:34:53.387Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/94/0e7e592619e2133596a47cdd642534b0456545c218430bd3b9d8fefdd1b1/mypy-2.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d53fc67b9d28a43c6199077f49fea0f05839e36cf6158500331c9549225e5a5", size = 15026523, upload-time = "2026-07-13T11:34:49.206Z" }, + { url = "https://files.pythonhosted.org/packages/f6/d2/1e1731df090a857df2807177a4626863e5ac0f0256513c35780efe53986f/mypy-2.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fbc00cee7bdbb9291979ddc9d08034a29dfcda4932628c9bbc28c1edd589df0c", size = 14032189, upload-time = "2026-07-13T11:33:57.168Z" }, + { url = "https://files.pythonhosted.org/packages/44/95/cab921f4a806e171f34113e6181dd23c55358ccf6a80741269ef594a410e/mypy-2.3.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:04e617030eca5221909c8b7d8d7fd1c637948199aa2100b2ad9813feb07e1491", size = 14198696, upload-time = "2026-07-13T11:32:12.767Z" }, + { url = "https://files.pythonhosted.org/packages/66/80/e6d008bb19fe446e3662d85e0e2717bf9f2d611a2164fb29d6e067dbf46c/mypy-2.3.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:56c184d2c20ca6b6378d58d1960270a767f41f5e44acbbd27f05effef4f4e1d7", size = 15286904, upload-time = "2026-07-13T11:34:27.594Z" }, + { url = "https://files.pythonhosted.org/packages/db/83/94397c9293608a364aa03e8084fb34ede4ae976a260384b9b52929308135/mypy-2.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3961a4a34b05f7c74b0f05aa51fbfe99a2d1e126038df40318d15c8f558b7ef3", size = 15528342, upload-time = "2026-07-13T11:34:07.819Z" }, + { url = "https://files.pythonhosted.org/packages/cf/96/d8b37d819adec6cfccfb1fd3afc1735d94717ddeafb45536db9c6943e09b/mypy-2.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:b1942b9314d4c784b8ea1dbab4972603290e5dd5630f06675f13aec97526bc4c", size = 11218346, upload-time = "2026-07-13T11:28:27.745Z" }, + { url = "https://files.pythonhosted.org/packages/2b/cd/cd9f725b19b19e5b530a154cf9bcf9e94279c5d55b3c34fb42b3aa48ea1b/mypy-2.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:be51653d7669d7d7955d613b8d0bb57d5b652eaf71a873ddf65ac87254dd2595", size = 10204525, upload-time = "2026-07-13T11:31:02.552Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ae/f7d056eb0294586a572d0d0d89580ec633c064db520f11d37d5a2fb833bd/mypy-2.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:91ad22a52ae2c7e621c2f67c94d5a17f66b3209a4cff5cf8a573579835c69e97", size = 14947298, upload-time = "2026-07-13T11:27:47.734Z" }, + { url = "https://files.pythonhosted.org/packages/32/d5/db3e7af01e7844d21662c6ddc1f7825ec7cb4053f0391ac02faf3638396f/mypy-2.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:99ac767cc5d3b64c8d0ae226ead10c96694f94e4e7da1668642225dcd4e75aac", size = 13950768, upload-time = "2026-07-13T11:27:57.726Z" }, + { url = "https://files.pythonhosted.org/packages/d9/fb/43c031f0190513d1ec248ed037eceb742ddd2a4d74bbf406658a28173837/mypy-2.3.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:de6d2c484742a4d7b0ed6d07b143375624d3b899c5749c7b3c947f56261f48a6", size = 14151586, upload-time = "2026-07-13T11:29:18.615Z" }, + { url = "https://files.pythonhosted.org/packages/ec/c3/f8b2ffc60883084da91be51af58e88a7ffd4ff9795acb7d902ff88d31eb1/mypy-2.3.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7da939dd335cfd2ad788bdfd081c9f4e47634ab995e5a45eb15fd1e5bc052f8b", size = 15227411, upload-time = "2026-07-13T11:30:29.904Z" }, + { url = "https://files.pythonhosted.org/packages/83/2e/16b917fc7adcf03f1aadddfc93aab804ffb234b1ab09c0ffd6d92a5d34a2/mypy-2.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7247eb2824f996722a949530183394921ca71deb9680052a338cf53cff7925c2", size = 15478790, upload-time = "2026-07-13T11:33:14.686Z" }, + { url = "https://files.pythonhosted.org/packages/c0/88/aaa65a93c73d0cdae7e42f8adb302bf6885bb281302084f99d0290a35347/mypy-2.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:75b0984bb3cbd76bb5c9291a8671f7ae66ca3b51c7584c358fc2e923259f0757", size = 11234919, upload-time = "2026-07-13T11:33:39.28Z" }, + { url = "https://files.pythonhosted.org/packages/35/19/b40de63f1a80e63bc2d40f0679a6a8dbd34e95176c8122119bdf406aa552/mypy-2.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:d78fcf900b59cb7e82cb7e3a235e31b462d9333d92285bd1e4952d355b8ffba1", size = 10201510, upload-time = "2026-07-13T11:31:52.619Z" }, + { url = "https://files.pythonhosted.org/packages/a4/58/fa0ae047da911f540284009b4f44b96fe09d83c076d7c103e9d645f46303/mypy-2.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ea317b060ce83e26050f8f9e4d7d6bf44ed7597c8ff9990bccffbb9d1d8522db", size = 14941909, upload-time = "2026-07-13T11:32:34.332Z" }, + { url = "https://files.pythonhosted.org/packages/15/14/2ba1d61452d7c2a7fe12741e8d374e52b183476b07aa7f9e2a0d02b0720a/mypy-2.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:094af99f92638aa92852326188b85a89e50f4a472f44827c03362228482f0762", size = 13967581, upload-time = "2026-07-13T11:30:00.587Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5a/483fb9e5ffbbb1a28dccc7b0a13d141b17ac769b6c9f488c0a0c63698962/mypy-2.3.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:de121747278144fc9ae7caa2e978cf5df12aebc82933182f5b3b86081a30baef", size = 14168807, upload-time = "2026-07-13T11:28:48.6Z" }, + { url = "https://files.pythonhosted.org/packages/ae/77/70d7a10732063beb74ad713682cf871e88f5c5fa39bfc8beff8a524bf9cb/mypy-2.3.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:37fa4de896a84e2dc9200d91e614c22563b43d1a266789d4bbac7b22ebe6192b", size = 15200144, upload-time = "2026-07-13T11:31:25.283Z" }, + { url = "https://files.pythonhosted.org/packages/56/72/766218ac783be4fdfcd699b90037b63017348a3e86fb2c1fbfb18302637d/mypy-2.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f1b3a98dfd21058bc759bb3337d5d1f61d0fdf9f3cf9c00f4291790fb5427bff", size = 15460389, upload-time = "2026-07-13T11:29:29.077Z" }, + { url = "https://files.pythonhosted.org/packages/38/4e/8a9db7411ecb8ec0cb1fd05dba432f28bafffcd38b4e887714a4a0506689/mypy-2.3.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:944c665d984157cb96a679dfb7a4a81dd1d36b24b9c284b699514e6e626b82d4", size = 7753664, upload-time = "2026-07-13T11:29:08.147Z" }, + { url = "https://files.pythonhosted.org/packages/65/4c/c3f8bfd6ed0e5e38b5a244403b27f821d433443df5a15a278417c10a3a3c/mypy-2.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:4359424140d985192c778c1ce2c114a10c1ca58a381ed79cfa70d37df94b299f", size = 11417237, upload-time = "2026-07-13T11:33:47.467Z" }, + { url = "https://files.pythonhosted.org/packages/3c/00/89a32eaf5ccf174bc4f90db0eaea5d70636c01b8d49f384bdab2e8834390/mypy-2.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:3dd0bed92c4bdec57c42505b96416fb9e6a5aa7be84d2809bcd5f2ecec2860d7", size = 10389252, upload-time = "2026-07-13T11:31:43.81Z" }, + { url = "https://files.pythonhosted.org/packages/31/56/104f93d69aa9f339b6b9d3b0a7faa699b8b466c942cf3ae86cc2a2ec0915/mypy-2.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:691fdc37132b1ae628d834f672e74de83462d9fb4aff621835767fb43a8dd373", size = 16385495, upload-time = "2026-07-13T11:29:49.818Z" }, + { url = "https://files.pythonhosted.org/packages/d2/03/f1d2123313f55efafdd27706960f43a771c62f1b68426c76043f3ab9ebf3/mypy-2.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:aec15d465d477558fd842757b487849007311cf3897849cdda0e3162ac0ac556", size = 15098155, upload-time = "2026-07-13T11:30:40.301Z" }, + { url = "https://files.pythonhosted.org/packages/e5/5d/d5f9200399b445e81726c4f23becee33f233aee81c72680b1ef3a258b641/mypy-2.3.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b352b7e49f5e6576009e8df730e1ff4f915cb565b851b396d2ffe2f5a6f5da88", size = 15514155, upload-time = "2026-07-13T11:34:38.569Z" }, + { url = "https://files.pythonhosted.org/packages/cd/ce/69977c555f08faa3190cfde44189b89dbd56861b1ab97aa18fc5f3a2e4a3/mypy-2.3.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1c6c6bf687b17f90dbfcad95b960d32eaa0154c00da45f03ab50bf8952e047fe", size = 16766351, upload-time = "2026-07-13T11:33:29.195Z" }, + { url = "https://files.pythonhosted.org/packages/bc/92/6648b6caa3ab9e00f9ac0c2a78307805f873dd48139b24a6f6f7c3667bbf/mypy-2.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f4ed18f111bfe2d599bca7468e7f9251042c1c2118f762c8de2766a56d773c60", size = 17043490, upload-time = "2026-07-13T11:30:53.927Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ab/0dc91d80f3f016634c68d451f294a97320fe903a9b6f90b9e57b3f7f1717/mypy-2.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:0b025a93cffb9781d231f232be07a17912f35f10a313c24f301c81e842870654", size = 12146869, upload-time = "2026-07-13T11:29:38.874Z" }, + { url = "https://files.pythonhosted.org/packages/85/b5/4c964d02634ba81f4d1c84838e5c5b18ab06d13ed568960f5d6318495ccc/mypy-2.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:adebc76aab4f3495a88b41d48aa4aff0c03f2822501da76625afcca5975f19e5", size = 10965113, upload-time = "2026-07-13T11:28:07.056Z" }, + { url = "https://files.pythonhosted.org/packages/2c/fa/fdc54fe583ba3cafbcedfb70eeeaf03849f75b1827a07096c7bd996f582d/mypy-2.3.0-py3-none-any.whl", hash = "sha256:6b1cdb579446b60432432b2b2403a6201b4b475a004d7f488511c9ba177c9e88", size = 2753292, upload-time = "2026-07-13T11:33:18.48Z" }, +] + +[[package]] +name = "mypy-extensions" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, +] + +[[package]] +name = "networkx" +version = "3.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" }, +] + +[[package]] +name = "numcodecs" +version = "0.16.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/44/bd/8a391e7c356366224734efd24da929cc4796fff468bfb179fe1af6548535/numcodecs-0.16.5.tar.gz", hash = "sha256:0d0fb60852f84c0bd9543cc4d2ab9eefd37fc8efcc410acd4777e62a1d300318", size = 6276387, upload-time = "2025-11-21T02:49:48.986Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/cc/55420f3641a67f78392dc0bc5d02cb9eb0a9dcebf2848d1ac77253ca61fa/numcodecs-0.16.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:24e675dc8d1550cd976a99479b87d872cb142632c75cc402fea04c08c4898523", size = 1656287, upload-time = "2025-11-21T02:49:25.755Z" }, + { url = "https://files.pythonhosted.org/packages/f5/6c/86644987505dcb90ba6d627d6989c27bafb0699f9fd00187e06d05ea8594/numcodecs-0.16.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:94ddfa4341d1a3ab99989d13b01b5134abb687d3dab2ead54b450aefe4ad5bd6", size = 1148899, upload-time = "2025-11-21T02:49:26.87Z" }, + { url = "https://files.pythonhosted.org/packages/97/1e/98aaddf272552d9fef1f0296a9939d1487914a239e98678f6b20f8b0a5c8/numcodecs-0.16.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b554ab9ecf69de7ca2b6b5e8bc696bd9747559cb4dd5127bd08d7a28bec59c3a", size = 8534814, upload-time = "2025-11-21T02:49:28.547Z" }, + { url = "https://files.pythonhosted.org/packages/fb/53/78c98ef5c8b2b784453487f3e4d6c017b20747c58b470393e230c78d18e8/numcodecs-0.16.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad1a379a45bd3491deab8ae6548313946744f868c21d5340116977ea3be5b1d6", size = 9173471, upload-time = "2025-11-21T02:49:30.444Z" }, + { url = "https://files.pythonhosted.org/packages/1c/20/2fdec87fc7f8cec950d2b0bea603c12dc9f05b4966dc5924ba5a36a61bf6/numcodecs-0.16.5-cp312-cp312-win_amd64.whl", hash = "sha256:845a9857886ffe4a3172ba1c537ae5bcc01e65068c31cf1fce1a844bd1da050f", size = 801412, upload-time = "2025-11-21T02:49:32.123Z" }, + { url = "https://files.pythonhosted.org/packages/38/38/071ced5a5fd1c85ba0e14ba721b66b053823e5176298c2f707e50bed11d9/numcodecs-0.16.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:25be3a516ab677dad890760d357cfe081a371d9c0a2e9a204562318ac5969de3", size = 1654359, upload-time = "2025-11-21T02:49:33.673Z" }, + { url = "https://files.pythonhosted.org/packages/d1/c0/5f84ba7525577c1b9909fc2d06ef11314825fc4ad4378f61d0e4c9883b4a/numcodecs-0.16.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0107e839ef75b854e969cb577e140b1aadb9847893937636582d23a2a4c6ce50", size = 1144237, upload-time = "2025-11-21T02:49:35.294Z" }, + { url = "https://files.pythonhosted.org/packages/0b/00/787ea5f237b8ea7bc67140c99155f9c00b5baf11c49afc5f3bfefa298f95/numcodecs-0.16.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:015a7c859ecc2a06e2a548f64008c0ec3aaecabc26456c2c62f4278d8fc20597", size = 8483064, upload-time = "2025-11-21T02:49:36.454Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e6/d359fdd37498e74d26a167f7a51e54542e642ea47181eb4e643a69a066c3/numcodecs-0.16.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84230b4b9dad2392f2a84242bd6e3e659ac137b5a1ce3571d6965fca673e0903", size = 9126063, upload-time = "2025-11-21T02:49:38.018Z" }, + { url = "https://files.pythonhosted.org/packages/27/72/6663cc0382ddbb866136c255c837bcb96cc7ce5e83562efec55e1b995941/numcodecs-0.16.5-cp313-cp313-win_amd64.whl", hash = "sha256:5088145502ad1ebf677ec47d00eb6f0fd600658217db3e0c070c321c85d6cf3d", size = 799275, upload-time = "2025-11-21T02:49:39.558Z" }, + { url = "https://files.pythonhosted.org/packages/3c/9e/38e7ca8184c958b51f45d56a4aeceb1134ecde2d8bd157efadc98502cc42/numcodecs-0.16.5-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:b05647b8b769e6bc8016e9fd4843c823ce5c9f2337c089fb5c9c4da05e5275de", size = 1654721, upload-time = "2025-11-21T02:49:40.602Z" }, + { url = "https://files.pythonhosted.org/packages/a1/37/260fa42e7b2b08e6e00ad632f8dd620961a60a459426c26cea390f8c68d0/numcodecs-0.16.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3832bd1b5af8bb3e413076b7d93318c8e7d7b68935006b9fa36ca057d1725a8f", size = 1146887, upload-time = "2025-11-21T02:49:41.721Z" }, + { url = "https://files.pythonhosted.org/packages/4e/15/e2e1151b5a8b14a15dfd4bb4abccce7fff7580f39bc34092780088835f3a/numcodecs-0.16.5-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49f7b7d24f103187f53135bed28bb9f0ed6b2e14c604664726487bb6d7c882e1", size = 8476987, upload-time = "2025-11-21T02:49:43.363Z" }, + { url = "https://files.pythonhosted.org/packages/6d/30/16a57fc4d9fb0ba06c600408bd6634f2f1753c54a7a351c99c5e09b51ee2/numcodecs-0.16.5-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aec9736d81b70f337d89c4070ee3ffeff113f386fd789492fa152d26a15043e4", size = 9102377, upload-time = "2025-11-21T02:49:45.508Z" }, + { url = "https://files.pythonhosted.org/packages/31/a5/a0425af36c20d55a3ea884db4b4efca25a43bea9214ba69ca7932dd997b4/numcodecs-0.16.5-cp314-cp314-win_amd64.whl", hash = "sha256:b16a14303800e9fb88abc39463ab4706c037647ac17e49e297faa5f7d7dbbf1d", size = 819022, upload-time = "2025-11-21T02:49:47.39Z" }, +] + +[package.optional-dependencies] +msgpack = [ + { name = "msgpack" }, +] + +[[package]] +name = "numpy" +version = "2.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/80/db0b4559e57ec36362bedbb05530a87fafbcb6067708c946967a41d449e7/numpy-2.5.2.tar.gz", hash = "sha256:d482d171c406ae88c5b19cad3b6a1c4c5209f886ab74bc44c2c865c23f52d860", size = 20773161, upload-time = "2026-08-09T13:48:27.962Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/72/dccb0aaf40972777283303919f613964227266d0c13adebb79ac124f1c3e/numpy-2.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:14e373cfc6387177e8409dac3c7159be8eb05cd77096cd7c950268b86f62831c", size = 16891693, upload-time = "2026-08-09T13:44:51.702Z" }, + { url = "https://files.pythonhosted.org/packages/60/2e/b5aee50a1f74ac815cf8331812cb8251e29024025de462e0c047641c614c/numpy-2.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4bbd96c833ecc8cc069ce518078fc8c60cb9cbfb0fea5b7a803ad65035596d03", size = 11903109, upload-time = "2026-08-09T13:44:55.501Z" }, + { url = "https://files.pythonhosted.org/packages/f3/f4/29e78102a80601cf034d4e9767022cffeca2c3b4c926e1754572ca95593d/numpy-2.5.2-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:6e8172ddfcf5cf74b811d372b570b83c60bd2de87a6fbfbebdadb4a9bd9c6cbb", size = 5350202, upload-time = "2026-08-09T13:44:58.401Z" }, + { url = "https://files.pythonhosted.org/packages/11/4b/dcd3b7eadaf4035d2c7a4289d232523a6964f602598ef7674e4bd7291f93/numpy-2.5.2-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:65f188481f1669e26f62b701e8205d19e460fa4a9b52a1414ba382330e4a3414", size = 6687736, upload-time = "2026-08-09T13:45:00.813Z" }, + { url = "https://files.pythonhosted.org/packages/e5/21/4947e0e9d6c9fc2e2ff15b8949049ee44f63adb9cacc729ab8793f97e712/numpy-2.5.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8ee9c4eeb8454b3660a8b53493563c3e121c2fc94fbd72b848ef814ed7b676a9", size = 15612696, upload-time = "2026-08-09T13:45:04.151Z" }, + { url = "https://files.pythonhosted.org/packages/3a/5f/62d28cf019460c7f1394105b4d49d9911a9c444cb77ab0bd95a204c5a6de/numpy-2.5.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cdec01fa790a186d430433fdd4d4ffb70eed6f0eeb4bf05c8dbe2dce0a9bcb8", size = 16722264, upload-time = "2026-08-09T13:45:07.714Z" }, + { url = "https://files.pythonhosted.org/packages/14/25/3f0be4c1b9fdf5dd5e708a6806978564d7c46a055c000496309ff2a2f8af/numpy-2.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7999d4ddb0c4025018373fd787510d46e04c769467af22869707b3c1cfd459ab", size = 16974396, upload-time = "2026-08-09T13:45:11.316Z" }, + { url = "https://files.pythonhosted.org/packages/22/72/6262cbdeeb45da9d971e40715f579d791603ba8ec0b5e2db1ac55454421d/numpy-2.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c1f017dc0875c9209d219f97feceb7d54c2661bb243deb4114478e1295808af7", size = 18476044, upload-time = "2026-08-09T13:45:14.869Z" }, + { url = "https://files.pythonhosted.org/packages/36/33/29208b8b075bde62d26a81d14b358c42b0f69b6cabd98d4ff97f37f22b05/numpy-2.5.2-cp312-cp312-win32.whl", hash = "sha256:d6a48072864e3324e194a8fbb3c657bcc5b5c869dbc64c9537b1d5c862572c0a", size = 6072817, upload-time = "2026-08-09T13:45:17.867Z" }, + { url = "https://files.pythonhosted.org/packages/7f/b9/87fea2769fe1c47c1b5b01d8310772c9d1a85d485de7cf386ef7a3332b02/numpy-2.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:28ac63476ec7651484215ee7fa15a1f78b57c14621f01e392afe17b9a1390ce4", size = 12464674, upload-time = "2026-08-09T13:45:20.734Z" }, + { url = "https://files.pythonhosted.org/packages/14/52/032b97e00461ab0809bbe4c588b035620e5a14b8cdee47ecddefc7b17d33/numpy-2.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:27650bb0e7140fa3d37b9923b4803645e0b125d190f326eecfd3f4dad8e8ade1", size = 10397131, upload-time = "2026-08-09T13:45:23.73Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d2/6b24738a0ef4557d189b150046cd07823c50e4273e8aebd651222e24306f/numpy-2.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8e4cb9a754c8a0c62eaa88273a5fba3391f4a610d1dee893c0755da31c083f15", size = 16886595, upload-time = "2026-08-09T13:45:27.323Z" }, + { url = "https://files.pythonhosted.org/packages/65/60/f2d208d366f263f39c6e69ed309290717aab41078b6d04c9be2a84fa2a07/numpy-2.5.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:52c808f96484f5571a5cc863775ce50247c17dfb3b0361f8ed6b4b0456f80080", size = 11896845, upload-time = "2026-08-09T13:45:31.638Z" }, + { url = "https://files.pythonhosted.org/packages/3c/79/81e0bf24f4d020a2b1d5cd297a9f60c3f24eeb116f9bba5870443f7b6a4a/numpy-2.5.2-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:29d81e97f668489cba8ebfd796b9bdd453525d35dd9e162e2daec94bf3fc7740", size = 5343880, upload-time = "2026-08-09T13:45:34.373Z" }, + { url = "https://files.pythonhosted.org/packages/ba/cc/e3141cf06d1a8a2c7e107543fe1269c1d1af760d4d683c0794a4ee1127c2/numpy-2.5.2-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:afb3f0632d6b2e3ba04dbce8d1e48d321b369138b73830b5ca371a0e8d479d56", size = 6682264, upload-time = "2026-08-09T13:45:36.7Z" }, + { url = "https://files.pythonhosted.org/packages/29/f1/2a64a307d92c5d98f5255a4014eb43bb6103ee477087b61ecae44a3aa9b9/numpy-2.5.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0aadf13b60048d501e05fa699efaf7734e2494f3498a4c2a5521d822640324f3", size = 15609566, upload-time = "2026-08-09T13:45:39.518Z" }, + { url = "https://files.pythonhosted.org/packages/7b/44/59a1eb68e773c4098d107ef34a0dbdeca501d72ffcfbff9a7707343921ce/numpy-2.5.2-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29b86ff8a6cc556b47ec6b64b194815cc80e6bf5eedcc6cddfd65318cb0b4eee", size = 16709995, upload-time = "2026-08-09T13:45:43.661Z" }, + { url = "https://files.pythonhosted.org/packages/8a/4c/3e54d4ddbc359a1295f8b633e8106bcd4d7d4a206e82df051bdfb3058755/numpy-2.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6950c4b7dd562453090548ba7f5da7e59f57f85663f15d5dcc60e249192f7e59", size = 16972511, upload-time = "2026-08-09T13:45:47.094Z" }, + { url = "https://files.pythonhosted.org/packages/f2/9f/02e371638ebf19b66d46231e4be52999e87f32d1961b113bc45656608b22/numpy-2.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b9727f472d2f3888053b8a75ab0cb94745a9de224bb5846dbadc0092101bc71d", size = 18465609, upload-time = "2026-08-09T13:45:50.808Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ae/ad6645abc7a3510fe48e8ea1ab4598166f500057ef4ebf38bfad4f1577de/numpy-2.5.2-cp313-cp313-win32.whl", hash = "sha256:4f9744f9fbdcea0bc552e8f19e1f141f811a3f9bc2be2cc6e86d982cab23e3f4", size = 6070204, upload-time = "2026-08-09T13:45:54.111Z" }, + { url = "https://files.pythonhosted.org/packages/15/20/f3489f86d81ea460b2bcdceaed094142ca6579f6be0ec527b781d39afe68/numpy-2.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:85aaccb24182c25df891ad0ec333585967e115269d5f1b17f2c9ae005bc96657", size = 12460532, upload-time = "2026-08-09T13:45:57.167Z" }, + { url = "https://files.pythonhosted.org/packages/d5/21/35b31dde1b283b79de828b80f876afd8c94e28fe1e9c375f89e261cc4c0d/numpy-2.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:bd68ece1553d2023c09a4226d9e41c586ad2d20594d1a456186c33513d2cb3f2", size = 10396725, upload-time = "2026-08-09T13:46:00.478Z" }, + { url = "https://files.pythonhosted.org/packages/ac/f8/c3b222bf075b50afd8e949a07a15c4b312a4a84bd8102a332bcd953cbbb4/numpy-2.5.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d787cf769c3baeb5f6235e778edb52c08dfa923789b5958f28e6450f96107cb1", size = 16885180, upload-time = "2026-08-09T13:46:03.939Z" }, + { url = "https://files.pythonhosted.org/packages/17/e1/2c1d4b1987795a92b5bbf7c24fe249ab96aa2573ab0d7604802c189d7b86/numpy-2.5.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:24b9dc2e3d84aa58523798805194e23e736f3f6ce2d1a5b92583ae734e6dbda8", size = 11907878, upload-time = "2026-08-09T13:46:07.045Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ee/d08226fc858044355983a6e5b94f08ff6f3969e0a2b160a4a89f0ddb3445/numpy-2.5.2-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:9e9413326d726c2545bfa65d2c0876871e8d8386e77f992c1d426e180bbd4323", size = 5354922, upload-time = "2026-08-09T13:46:10.04Z" }, + { url = "https://files.pythonhosted.org/packages/94/f0/6d3d933056440ebbc5e6bad92065fc6c26a48a84a36b1208580e94eea76c/numpy-2.5.2-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:60e902ac295855348a5ca2ea4c89108989a9f5fddfad3dfc0a8f36b10358567e", size = 6679168, upload-time = "2026-08-09T13:46:12.275Z" }, + { url = "https://files.pythonhosted.org/packages/c4/3b/ecd49dd90033cceb2704d88ca905d4d7d89b0e8c739608754ffd325fa820/numpy-2.5.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:50e500dc868e9313530ce12ba470fe50ff3afe3d62993ed6eff652dacd555b65", size = 15624501, upload-time = "2026-08-09T13:46:15.322Z" }, + { url = "https://files.pythonhosted.org/packages/c7/99/461bd36dbdfac6c1c53efa370bd55a83227542d0d118f1677dbf1a3dacd5/numpy-2.5.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318b9a4c845dbea06708a29c84ee429cc3065048db34cdb799047643492050ee", size = 16713701, upload-time = "2026-08-09T13:46:18.949Z" }, + { url = "https://files.pythonhosted.org/packages/f9/9c/2b251df9e8a5d647b62b0cbc1b90a91850c1cf4859ecb532fd0b4eacff6c/numpy-2.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:34c319e2963be042673fb46570501b2f06c41924e17e3563d58646b4380dfb68", size = 16986065, upload-time = "2026-08-09T13:46:23.006Z" }, + { url = "https://files.pythonhosted.org/packages/8f/25/20de43f53ff1390534a124475055a19f01fe10c920a0fd11b8e18d6d6052/numpy-2.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f06571a052127dc1b4e8b83029b4d1b20daa2b64a31cdd181fc6bc774e9000eb", size = 18470031, upload-time = "2026-08-09T13:46:27.102Z" }, + { url = "https://files.pythonhosted.org/packages/56/5e/0c577ca308d6da5eb79b546ba10bbe5b60148192194e2da060913b1de4f1/numpy-2.5.2-cp314-cp314-win32.whl", hash = "sha256:2cc779226e476d1e1f08c74068c419e60f41a9e0e069c92f6671d31d5c985e98", size = 6121028, upload-time = "2026-08-09T13:46:30.046Z" }, + { url = "https://files.pythonhosted.org/packages/15/5c/7bcbd5b11f94199073320410cddcbb80cee62415bfeb540874b265c2d922/numpy-2.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:7587f53dfbd5edc0f7b87c6217b4c6d2d1f2ef9c3da70bc1315e7db5f8d7ec9d", size = 12597627, upload-time = "2026-08-09T13:46:32.886Z" }, + { url = "https://files.pythonhosted.org/packages/87/bc/4d0b06fba0da90ccc75af62823cb9dcedb6c9ea0cffa058cb2c9ee773a77/numpy-2.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:3e4c367352d3747784248a227fbec218e193b56f7e6692e3b64fc805478ecfdf", size = 10680414, upload-time = "2026-08-09T13:46:36.036Z" }, + { url = "https://files.pythonhosted.org/packages/cd/17/f429aac9dc08833a0d0f188eba38c532a751b1a1f2ca6018a37b455cb321/numpy-2.5.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b879fb674276e331513fb136b78dbc6bd3c848309e0d841cfd63be3896c4cfc1", size = 12026967, upload-time = "2026-08-09T13:46:39.084Z" }, + { url = "https://files.pythonhosted.org/packages/ca/9f/d0849de96a2a4ceaa16662f18ee13eaa9c0aa418269fdc8c4857c56b11da/numpy-2.5.2-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:fd0d703772bba096843785bd38371e31bb4a0c1151497ad5739d182114a73f7f", size = 5473874, upload-time = "2026-08-09T13:46:42.075Z" }, + { url = "https://files.pythonhosted.org/packages/89/3c/8df216d4a4a5422a3de045301cf7df8ea47286d76f5cb7160b0128ac26b7/numpy-2.5.2-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:3a2f061cebd9e3d23bdcfaaded5e2293a4c6a5b60fa42df85d410a725ce621bf", size = 6789276, upload-time = "2026-08-09T13:46:44.387Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3a/20d7e9891c4ddfadd6ff8d95bf4b29f353d8e1770553de2099880551dfb9/numpy-2.5.2-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6df895598c0edcb41030126c89e0f353b07d93238116143b7405e937359736c4", size = 15659154, upload-time = "2026-08-09T13:46:47.538Z" }, + { url = "https://files.pythonhosted.org/packages/aa/d6/f3aa3d2688bf501b858835c6bd087ae9b51a56ae6fca8e2b0990abd177af/numpy-2.5.2-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1ab3d4a901f844ea836c3e80bf463c6a27d7f3c14e8e292fcf28d348b25b9bce", size = 16748909, upload-time = "2026-08-09T13:46:51.442Z" }, + { url = "https://files.pythonhosted.org/packages/7d/8f/1c5cae8d2baf86ab802ae97a00be55bc7e21ebc11b12bbc33376c5f05342/numpy-2.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:cebc2d6dbb605a7703d59751dea4bd6b0ab127a5a4338a6f432df1936fef8b26", size = 17027685, upload-time = "2026-08-09T13:46:55.095Z" }, + { url = "https://files.pythonhosted.org/packages/5c/27/71d3467404aedc1c24ce79610f91b52b0b0f466c43a701aa56fc75c145ab/numpy-2.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:eaca7ff36f0f52e2111ec71f169d8fd3e889e7ddc0d2592e0d703fd8d3ce8fac", size = 18501181, upload-time = "2026-08-09T13:46:59.09Z" }, + { url = "https://files.pythonhosted.org/packages/14/2f/42921d27c40aea7e077f4a423ae509fd9220b028cd787bafefd8ab2b3a5f/numpy-2.5.2-cp314-cp314t-win32.whl", hash = "sha256:ddf47472af2e4280d79bac82304f5e80150211f1b9e614b760061d5fdfbb6eba", size = 6271085, upload-time = "2026-08-09T13:47:01.903Z" }, + { url = "https://files.pythonhosted.org/packages/75/e6/bad5f5d56de9b1971bac959963dda276d35c40f1854475005434bbe08692/numpy-2.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:44ef9675d908e65f9953063837c3277730f3f4437615a4cdab67b366cabaf884", size = 12787971, upload-time = "2026-08-09T13:47:04.963Z" }, + { url = "https://files.pythonhosted.org/packages/df/05/f608795cb34391acd67e38d94a3c36abd8d8576293a3a80727d7595c372c/numpy-2.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:eaa088384c46f519dacb93b7ec483a6d6b19a4a2085ae4f25ab9b1c43d387d1e", size = 10750306, upload-time = "2026-08-09T13:47:07.976Z" }, + { url = "https://files.pythonhosted.org/packages/33/c6/28de0191c5f82b7d42a0a51390ba98587048aa93a39fafb05bdbe6e8d00c/numpy-2.5.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:078f9b027b478c9379b9677babbf0f8b8f1ecfada27636d7b9a93990c638739f", size = 16885274, upload-time = "2026-08-09T13:47:11.439Z" }, + { url = "https://files.pythonhosted.org/packages/dd/d1/973ca116000d244897e468ea1aff30b589e5022e3c8744b71706fe33bd57/numpy-2.5.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:50a68f4bacd8a2b33d8da3d2269d0d78500f86ea582e4786dc10f5ef2c2c6842", size = 11907846, upload-time = "2026-08-09T13:47:15.128Z" }, + { url = "https://files.pythonhosted.org/packages/78/d9/8c4b3937ef204cb2fd88d389ccd0f265a2ffb11f35a01d2064cf46714bd6/numpy-2.5.2-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:e79aba74ffaf5f78a050d777c184cddf8fdffabab38acf5f3ef1fecbc17895d6", size = 5354892, upload-time = "2026-08-09T13:47:18.07Z" }, + { url = "https://files.pythonhosted.org/packages/74/9b/b6ee65ea2999fdb7023935e108e6fb776ee4082aa15f159acfa857e578c8/numpy-2.5.2-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:9a0731745a72a184490a582fb4af2533512bd071ace67785b5fdffc0ae58dce8", size = 6679309, upload-time = "2026-08-09T13:47:20.456Z" }, + { url = "https://files.pythonhosted.org/packages/43/f3/acb18d8b137a393c8e7803a8c994c9e64bde3930692a69d826993113a159/numpy-2.5.2-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4ec954036759bcee3aa484f8603bd9c14f3e776293b85578b8734c2d72777c69", size = 15625850, upload-time = "2026-08-09T13:47:24.365Z" }, + { url = "https://files.pythonhosted.org/packages/a9/bf/a8e9bb0db815a0e265b5744ebedd3af0bd5faad8604e5b50a1cd012f3c91/numpy-2.5.2-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dc649493697006bc90614a5f0bbc8cb3cb1866715c474e473694968d7e6b99ab", size = 16713664, upload-time = "2026-08-09T13:47:27.965Z" }, + { url = "https://files.pythonhosted.org/packages/0c/c3/6e913736b3dd6582344af32418b5fb9dab34282e8a8174ae1d54ceb0fc13/numpy-2.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:cf7de32f486e4ac9e2d93b810f9e9ac72a728dd46a32a0bb403222f27f653514", size = 16986749, upload-time = "2026-08-09T13:47:31.541Z" }, + { url = "https://files.pythonhosted.org/packages/80/09/7d3b23eff5c7428ef6c01e6f7052bb60d504c4d33e317b36b8959c24ad97/numpy-2.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2ffa7bacab3e2ee1b19ed31766bb60bb380b68c23f051e199c5cc598afd68710", size = 18470495, upload-time = "2026-08-09T13:47:35.364Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a4/68a321d825374f6eb677ffe8ef8c6b9a328304e6fd2e39d9530822776607/numpy-2.5.2-cp315-cp315-win32.whl", hash = "sha256:6b588cc8f902d6bff201c19fd00c43ab8545671e3554d014e12e14139e5e8617", size = 6120696, upload-time = "2026-08-09T13:47:38.561Z" }, + { url = "https://files.pythonhosted.org/packages/c8/23/deafbb1700f79fae9cd1e91220f133d124cc267de1b584da3fbf6db2f6cd/numpy-2.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:07d4e89f3a9ab0a9ba24264ccdb642b3dd951b2281e8883a5481a4aa79cc31a7", size = 12597324, upload-time = "2026-08-09T13:47:41.401Z" }, + { url = "https://files.pythonhosted.org/packages/33/cd/3272ba105e3bbbdaeb11357eda31e7a6825ffe159e8171665660299a948f/numpy-2.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:a610dc7e3c52edd39c2bc2375ff9c3fd59cb3ad00e4472d36f83bc1457145788", size = 10680466, upload-time = "2026-08-09T13:47:44.873Z" }, + { url = "https://files.pythonhosted.org/packages/0e/0e/58370637b1bb70a5c9ce2b43f4b521ccb224e36ccb76a6596b17ae4b447c/numpy-2.5.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:40f4d451aed46a8046a1aae41c4e55fb3612273df9c502480135e1501576a34b", size = 16993947, upload-time = "2026-08-09T13:47:48.97Z" }, + { url = "https://files.pythonhosted.org/packages/10/93/2abcb807712b289d6d60fe4cf30532f98974a8396d885650f3ba5a13026e/numpy-2.5.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:c081cbe16ba1ab53078e5ff29013621e33c509eedab055775d956427712c236e", size = 12025331, upload-time = "2026-08-09T13:47:52.646Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3a/2898e003a5fbaf87e76c039b4ee1f5eb390471b4ffe74887c1f34c4e791e/numpy-2.5.2-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:0090ccdd57ec2703e9b49d0bf554767370581c1dd0a6b2bb2b2d9def317d042a", size = 5472336, upload-time = "2026-08-09T13:47:55.403Z" }, + { url = "https://files.pythonhosted.org/packages/61/a5/23f69d07c544597b29758b31b55c27dc9d541012a2c1496189fef702aec2/numpy-2.5.2-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:6a9bb119fb8dd21ba30b3f0e555b7e2b081bd9883af21ec9c1c633d161cda3a8", size = 6788387, upload-time = "2026-08-09T13:47:58.192Z" }, + { url = "https://files.pythonhosted.org/packages/15/ea/c0dbdbcf22f43782510a3e492dd3da73c6112b69cac8929d16d127536fc4/numpy-2.5.2-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a839318485284a6fb31be4f8f2c91c8f2cb22f4543c4a8903f12b0671ffe07cc", size = 15667096, upload-time = "2026-08-09T13:48:01.562Z" }, + { url = "https://files.pythonhosted.org/packages/fc/5e/29c73c31748cdb0f7566642125ba17fd5b56780cddf891b085dab27e4466/numpy-2.5.2-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba0a474801b8dc67b66bf465548abc90e82b44d2611b5770f33008dcabffe8ec", size = 16751730, upload-time = "2026-08-09T13:48:05.706Z" }, + { url = "https://files.pythonhosted.org/packages/47/95/02501e8454796bb58dadf7a99d3181e0b464bf264e1003039572f9779fac/numpy-2.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:0a4035ae1129ff8777f08bfbd44f1e5d8e9c049ce0c2dd78fc0d92c13e7251c0", size = 17038686, upload-time = "2026-08-09T13:48:09.627Z" }, + { url = "https://files.pythonhosted.org/packages/0e/b5/53a681d91b5c82687067d8ea5035e02d917b5509d6f334cb06484a954714/numpy-2.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:77843ca236b777e67f8d6b3660ea116e499612703a0ecd7093f316201eb9d8e2", size = 18507727, upload-time = "2026-08-09T13:48:13.744Z" }, + { url = "https://files.pythonhosted.org/packages/42/06/6e11443f7b64ee376c860506091103bf68f92d2cab9e8d96d4501babf07c/numpy-2.5.2-cp315-cp315t-win32.whl", hash = "sha256:7354826bc6f8f69402e9b7fe28d15fcd34feebd74f856f111585c5b0c9fb0251", size = 6269775, upload-time = "2026-08-09T13:48:17.543Z" }, + { url = "https://files.pythonhosted.org/packages/f1/18/195d6b86cd72dbbc501edfa778005fa6b87afd34c153e46028cd3a0938f4/numpy-2.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:e5651f3f87add730ee6608d915009e19c911fba0cb000c7e3ea994b7d768eb12", size = 12782559, upload-time = "2026-08-09T13:48:21.023Z" }, + { url = "https://files.pythonhosted.org/packages/b4/07/458c344f0f0c178f4481dad5cca790626ffe4c34eabf9467069d06ee4999/numpy-2.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:5f8e00be2ec6f45f4e8a41a527f68d44a7d96fee92a650e4d8b1326f77f61e6e", size = 10748103, upload-time = "2026-08-09T13:48:24.21Z" }, +] + +[[package]] +name = "numpydoc" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sphinx" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/3c/dfccc9e7dee357fb2aa13c3890d952a370dd0ed071e0f7ed62ed0df567c1/numpydoc-1.10.0.tar.gz", hash = "sha256:3f7970f6eee30912260a6b31ac72bba2432830cd6722569ec17ee8d3ef5ffa01", size = 94027, upload-time = "2025-12-02T16:39:12.937Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/5e/3a6a3e90f35cea3853c45e5d5fb9b7192ce4384616f932cf7591298ab6e1/numpydoc-1.10.0-py3-none-any.whl", hash = "sha256:3149da9874af890bcc2a82ef7aae5484e5aa81cb2778f08e3c307ba6d963721b", size = 69255, upload-time = "2025-12-02T16:39:11.561Z" }, +] + +[[package]] +name = "obstore" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2e/2f/f83afaab7945509d72245b2b00af0b4834ce78fdd2d9ae9f0ad1a3036a91/obstore-0.11.0.tar.gz", hash = "sha256:a2f55163bcd348b4a60d12e6893eac50eddc742bad8032a1705d49140b992204", size = 130565, upload-time = "2026-06-25T18:29:49.405Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/b2/00c213e7e5ca8065f97e37e55294adab836e3f6a88b23e4029069aaecf95/obstore-0.11.0-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:42f36546c7ac44dbab1173d2330a8a1b1a3f0e37950e553b8c904e3dd0744b25", size = 5491935, upload-time = "2026-06-25T18:28:32.029Z" }, + { url = "https://files.pythonhosted.org/packages/ac/37/6a6b9a5e15a8a37c24d14317a87648097c4888593b588510c03c030d2e90/obstore-0.11.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:687bb9d3962d568b7c439c5d0c6fea19b2749862a8e5c8eebd0c058c4eccde9e", size = 4672619, upload-time = "2026-06-25T18:28:33.852Z" }, + { url = "https://files.pythonhosted.org/packages/28/f9/6745ce8c4f7bfac19dc14a4438b48a2e93a689b92b0cecfc695e41a4e8b1/obstore-0.11.0-cp311-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:010b51578c7514a41719d795cdb7a1e6529be509dac3772e477187a59422bb97", size = 5072806, upload-time = "2026-06-25T18:28:36.127Z" }, + { url = "https://files.pythonhosted.org/packages/6c/18/991d3b3cdd851c0225e55f3dc45b47fd9e249827d188995011469f805132/obstore-0.11.0-cp311-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cfaa8129a3f5d8518a3a75184d4b02348db0f6263177cd1f0951f6568243cc9e", size = 5303777, upload-time = "2026-06-25T18:28:37.89Z" }, + { url = "https://files.pythonhosted.org/packages/8d/e9/90e56015a45b5e56a84fc3188c4e5fb088b288d41992c73a629e10df6760/obstore-0.11.0-cp311-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c790a5cb9ff2970d1f464a6a708d734dce9939e9f668cb6708c5dba5d61589b2", size = 5493871, upload-time = "2026-06-25T18:28:39.981Z" }, + { url = "https://files.pythonhosted.org/packages/66/02/f1744091d59ce71c5523174eb860fbb298275c901e89b9ea6fbf3e654a33/obstore-0.11.0-cp311-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:827113e12fe8088e0281a9d57b90b2b8dbc8a6ffe3b15dadb9baa5feb3d266c1", size = 5361913, upload-time = "2026-06-25T18:28:42.089Z" }, + { url = "https://files.pythonhosted.org/packages/5d/59/3f47822683ee2b6db8685faa25829946d6343a561251ec2704548455d946/obstore-0.11.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a2ff6d3ed553298828fb760b4aef6347fbcc7b5c5e3ce3f8381ce805c370021a", size = 5638724, upload-time = "2026-06-25T18:28:43.897Z" }, + { url = "https://files.pythonhosted.org/packages/23/50/1df335fdf9b527b3933f1e94ab6fc720ad314260fab8591cb0b6668ff192/obstore-0.11.0-cp311-abi3-manylinux_2_24_aarch64.whl", hash = "sha256:39d04b324fcf984e7050734ebda77b81764025b0c011750201a0d8954087f7aa", size = 5413508, upload-time = "2026-06-25T18:28:45.624Z" }, + { url = "https://files.pythonhosted.org/packages/de/dc/a259aba149b841ca7c91fea177df9972a60a636b54077beed1a35b254994/obstore-0.11.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:37c0d15d775b1370ef5204ee3919a5ddf7e2592d11815213105f8db031f2ab8d", size = 5619995, upload-time = "2026-06-25T18:28:47.599Z" }, + { url = "https://files.pythonhosted.org/packages/e5/b4/ec25fdb4d6b060bc6eea647fc0e88f75fcc20fe8d16d67fb0dbe999d323b/obstore-0.11.0-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:7f468caf9b6e0f12ff151e5fe618de5fc9192befa9bd02734b06de4efd2e49f6", size = 5299512, upload-time = "2026-06-25T18:28:49.629Z" }, + { url = "https://files.pythonhosted.org/packages/a8/e5/29be060d06ec13e2af3d1b6cfb77b7c37f8be6c56b77295c945fefad73e4/obstore-0.11.0-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:42d8e8fad85be8ee488c1a9a9b7c6a42128abb84e67175da40d3d1165c1846df", size = 5427026, upload-time = "2026-06-25T18:28:51.317Z" }, + { url = "https://files.pythonhosted.org/packages/57/b7/577a965f440e9ea64243518663f9d16be7df8eafc7123818e8e841fa21ce/obstore-0.11.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9c8fd2a544e2e0b926669c47fcfb8d2314e234abc240ea165dae04ee42e1d7ac", size = 5869187, upload-time = "2026-06-25T18:28:53.166Z" }, + { url = "https://files.pythonhosted.org/packages/e2/18/8fdbaee22bfd5b9c44e1fdff8ca0508e2fe60c42bf9fc85f0c9c27b4ecf2/obstore-0.11.0-cp311-abi3-win_amd64.whl", hash = "sha256:6fb3d4678c0f4242d3109362e9b1df5d7b27765f43d5aacb2e81af53a75cb9ef", size = 5329384, upload-time = "2026-06-25T18:28:55.305Z" }, + { url = "https://files.pythonhosted.org/packages/8b/8b/7555e48ec768728fcfc71a051c6b28d6ddaf1bececf492ce5ef995aab5f0/obstore-0.11.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f3132393eff9f3f2b543ecbb3bcc12319a7c433fef06493b4350d6854d505a14", size = 5515763, upload-time = "2026-06-25T18:28:57.527Z" }, + { url = "https://files.pythonhosted.org/packages/23/8f/94d83f3336421cbb5e436ab0ae5695eae72f7c82990d6b1ac090712c8052/obstore-0.11.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a3a8da19b47af4c14ecc694209b3c18ac6d89f96be5656ee3a19b77947c14155", size = 4649491, upload-time = "2026-06-25T18:28:59.386Z" }, + { url = "https://files.pythonhosted.org/packages/fe/86/11f4e1f51a8c6cf21a5915c018d2357201ad3c5799d418f0c6529fafaab2/obstore-0.11.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e91298b9b6c3a0408c28eece62bca6c5b6cda2f6350351d84e07b4dc8fb2631f", size = 5060659, upload-time = "2026-06-25T18:29:01.139Z" }, + { url = "https://files.pythonhosted.org/packages/49/e7/fd3036b0923d10e878e2073020f1ef692a618ed1cc3980d3e4a468c93713/obstore-0.11.0-cp314-cp314t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3422c532486671dfb5e3e739bf15ec9ca2a8da544a3c23b74ae3857dcab1c6a8", size = 5277058, upload-time = "2026-06-25T18:29:02.96Z" }, + { url = "https://files.pythonhosted.org/packages/2f/a7/b016c3ac6857ac856326dc0a292e3871b8500d03f25f3b90e168b05de357/obstore-0.11.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3de027ce46cf0592c2b41654e2c27dbc52a4a726f6fbc511380acc0da3a9f658", size = 5475852, upload-time = "2026-06-25T18:29:05.032Z" }, + { url = "https://files.pythonhosted.org/packages/85/9e/644ffe8db7757de7f71f94a036ab24222bccb4de290d3ca69f76547e812d/obstore-0.11.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1a80a95548678210bc336b866e37139c293565c3b163eb3fef2433d5d6640a33", size = 5363082, upload-time = "2026-06-25T18:29:06.878Z" }, + { url = "https://files.pythonhosted.org/packages/ae/0b/26af6b5fa6ba96af84086f44f78b4e5b0af1729c31402d7b28c68989d174/obstore-0.11.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acaa261dc15efb95bbeca06f8fe9b47ee23d7302a6aa1fa3a9654baab8b23d7c", size = 5629116, upload-time = "2026-06-25T18:29:08.771Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ce/f30d502991c6719b2fbd7b8385ef3e39da07bfca099108bcc5eeed8b9c20/obstore-0.11.0-cp314-cp314t-manylinux_2_24_aarch64.whl", hash = "sha256:a3300cabbc3129670987b3723629c791d83c117ef1b6a0c670c2043648e000a1", size = 5404534, upload-time = "2026-06-25T18:29:11.294Z" }, + { url = "https://files.pythonhosted.org/packages/52/20/d5bf5f816e868717ba647ed9a2109e800deb402d0265d410456b3fcb4376/obstore-0.11.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:f4e6a9480843645cd4ee122c41d5c5a46a56f1e9cdda85638826f2e0e439fe5c", size = 5613159, upload-time = "2026-06-25T18:29:13.414Z" }, + { url = "https://files.pythonhosted.org/packages/db/b4/6d4c1c211e3b06cc8554189e0d4406e8fa1f98ed55f9213b8e398a11599f/obstore-0.11.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:9fb2b1814c4314b8903f4e2ebbe8c3365fea6543669615ee9a0288b0d3a2edeb", size = 5286279, upload-time = "2026-06-25T18:29:15.424Z" }, + { url = "https://files.pythonhosted.org/packages/02/5e/d7b5589424a56171b16ab94cf92eb493490c300aaa044913bbdd94cace68/obstore-0.11.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:63fb9b072815eafe4705f617f567d896b1c858adcb390795fa1e269367791031", size = 5401780, upload-time = "2026-06-25T18:29:17.514Z" }, + { url = "https://files.pythonhosted.org/packages/c4/18/841baea8936e51a18b0e5d4c51f09c0a7798cb73b027e9794be2362a0f0b/obstore-0.11.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:086fafba314ff98cfab1c4bf7814699e862513e8889720cf6f7462296cb32787", size = 5853618, upload-time = "2026-06-25T18:29:19.354Z" }, + { url = "https://files.pythonhosted.org/packages/83/9a/d6127f5422b78e0222b0a9eadcfd7a5aa8d873a9498da7d4a77d4ac8ce2e/obstore-0.11.0-cp314-cp314t-win_amd64.whl", hash = "sha256:676d1154f6f08721110f9b7d14ee3a3c0293abaf9da135bb90f54e276dca1cac", size = 5314113, upload-time = "2026-06-25T18:29:21.209Z" }, +] + +[[package]] +name = "openapi-schema-validator" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonschema" }, + { name = "jsonschema-specifications" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, + { name = "referencing" }, + { name = "rfc3339-validator" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/4b/67b24b2b23d96ea862be2cca3632a546f67a22461200831213e80c3c6011/openapi_schema_validator-0.8.1.tar.gz", hash = "sha256:4c57266ce8cbfa37bb4eb4d62cdb7d19356c3a468e3535743c4562863e1790da", size = 23134, upload-time = "2026-03-02T08:46:29.807Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6f/87/e9f29f463b230d4b47d65e17858c595153a8ca8c1775f16e406aa82d455d/openapi_schema_validator-0.8.1-py3-none-any.whl", hash = "sha256:0f5859794c5bfa433d478dc5ac5e5768d50adc56b14380c8a6fd3a8113e89c9b", size = 19211, upload-time = "2026-03-02T08:46:28.154Z" }, +] + +[[package]] +name = "openapi-spec-validator" +version = "0.8.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonschema" }, + { name = "jsonschema-path" }, + { name = "lazy-object-proxy" }, + { name = "openapi-schema-validator" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/3f/aa0c1150627b4e683ae5673486b7d5cf2623a8821601863ee389e430965a/openapi_spec_validator-0.8.5.tar.gz", hash = "sha256:93b04ef5321d5866b2502371123d86333e5c1444f051d323e02525d9e83c7622", size = 1756845, upload-time = "2026-04-24T15:25:21.334Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/96/d7dfe1cc0be2df22d7a97ffb0f8bb00b10d92749aa6e64ffa7cc9a041580/openapi_spec_validator-0.8.5-py3-none-any.whl", hash = "sha256:3669106361856934153991e30714616a294865a33f6411a4c25d1dc2d08cfbc2", size = 50334, upload-time = "2026-04-24T15:25:19.65Z" }, +] + +[[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 = "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 = "pathable" +version = "0.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/55/b748445cb4ea6b125626f15379be7c96d1035d4fa3e8fee362fa92298abf/pathable-0.5.0.tar.gz", hash = "sha256:d81938348a1cacb525e7c75166270644782c0fb9c8cecc16be033e71427e0ef1", size = 16655, upload-time = "2026-02-20T08:47:00.748Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/52/96/5a770e5c461462575474468e5af931cff9de036e7c2b4fea23c1c58d2cbe/pathable-0.5.0-py3-none-any.whl", hash = "sha256:646e3d09491a6351a0c82632a09c02cdf70a252e73196b36d8a15ba0a114f0a6", size = 16867, upload-time = "2026-02-20T08:46:59.536Z" }, +] + +[[package]] +name = "pathlib-abc" +version = "0.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/cb/448649d7f25d228bf0be3a04590ab7afa77f15e056f8fa976ed05ec9a78f/pathlib_abc-0.5.2.tar.gz", hash = "sha256:fcd56f147234645e2c59c7ae22808b34c364bb231f685ddd9f96885aed78a94c", size = 33342, upload-time = "2025-10-10T18:37:20.524Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/29/c028a0731e202035f0e2e0bfbf1a3e46ad6c628cbb17f6f1cc9eea5d9ff1/pathlib_abc-0.5.2-py3-none-any.whl", hash = "sha256:4c9d94cf1b23af417ce7c0417b43333b06a106c01000b286c99de230d95eefbb", size = 19070, upload-time = "2025-10-10T18:37:19.437Z" }, +] + +[[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 = "pillow" +version = "12.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" }, + { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" }, + { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" }, + { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" }, + { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" }, + { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" }, + { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" }, + { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" }, + { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" }, + { url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" }, + { url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" }, + { url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" }, + { url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" }, + { url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" }, + { url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" }, + { url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" }, + { url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" }, + { url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" }, + { url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" }, + { url = "https://files.pythonhosted.org/packages/dc/01/001f65b68192f0228cc1dbbc8d2530ab5d58b61037ba0587f946fea607cd/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330", size = 4161736, upload-time = "2026-07-01T11:54:51.156Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d2/0219746d0fd16fc8a84498e79452375be3797d3ce4044596ce565164b84f/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217", size = 4255435, upload-time = "2026-07-01T11:54:53.414Z" }, + { url = "https://files.pythonhosted.org/packages/c8/02/8d0bc62ef0302318c46ff2a512822d2610e81c7aa46c9b3abe6cbaca5ad0/pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930", size = 3696262, upload-time = "2026-07-01T11:54:55.739Z" }, + { url = "https://files.pythonhosted.org/packages/85/e2/73c77d218410b14f5f2d565e8a998d5317b7b9c75368d29985139f7a46f0/pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8", size = 5350344, upload-time = "2026-07-01T11:54:57.657Z" }, + { url = "https://files.pythonhosted.org/packages/c7/da/32c752228ae345f489e3a42499d817b6c3996da7e8a3bc7a04fc806b243b/pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0", size = 4780131, upload-time = "2026-07-01T11:54:59.713Z" }, + { url = "https://files.pythonhosted.org/packages/b1/9d/8b2c807dbef61a5197c047afe99823787eb66f63daf9fb2432f91d6f0462/pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321", size = 6263757, upload-time = "2026-07-01T11:55:01.778Z" }, + { url = "https://files.pythonhosted.org/packages/5c/44/c85361f65dbe00eea8576ee467c768d25129989efb76e94f205e9ca9bb46/pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b", size = 6936962, upload-time = "2026-07-01T11:55:03.93Z" }, + { url = "https://files.pythonhosted.org/packages/18/7e/e483414b35800b86b6f08dbbc7803fb5cd52c4d6f897f47d53ea2c7e6f65/pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198", size = 6339171, upload-time = "2026-07-01T11:55:05.989Z" }, + { url = "https://files.pythonhosted.org/packages/f0/f4/68c491844841ede6bed70189546b3ee9731cf9f2cbad396faff5e1ccba45/pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130", size = 7048116, upload-time = "2026-07-01T11:55:08.131Z" }, + { url = "https://files.pythonhosted.org/packages/a3/34/77f3f793fed8efc7d243f21b33c5a3f0d1c97ee70346d3db855587e155ff/pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a", size = 6467209, upload-time = "2026-07-01T11:55:10.408Z" }, + { url = "https://files.pythonhosted.org/packages/f1/e0/492879f69d94f91f60fc8cd05ba03650e9520afebb2fb7aa12777d7c7f38/pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d", size = 7237707, upload-time = "2026-07-01T11:55:12.745Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ac/6b11f2875f1c2ac040d84e1bbf9cf22a88038f901ca1037898b280b38365/pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838", size = 2565995, upload-time = "2026-07-01T11:55:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/52/69/c2208e56af9bfc1913afb24020297a691eb1d4ef688474c8a04913f65e04/pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e", size = 5352503, upload-time = "2026-07-01T11:55:17.076Z" }, + { url = "https://files.pythonhosted.org/packages/07/70/e5686d753e898a45d778ff1718dba8516ead6ab6b95d85fc8c4b70650cf2/pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17", size = 4782956, upload-time = "2026-07-01T11:55:19.448Z" }, + { url = "https://files.pythonhosted.org/packages/d5/37/25c6692f06927ee973ff18c8d9ee98ad0b4d84ee67a09610c2dd1447958e/pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385", size = 6322855, upload-time = "2026-07-01T11:55:21.613Z" }, + { url = "https://files.pythonhosted.org/packages/cc/91/420637fcb8f1bc11029e403b4538e6694744428d8246118e45719f944556/pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c", size = 6989642, upload-time = "2026-07-01T11:55:24.006Z" }, + { url = "https://files.pythonhosted.org/packages/10/08/b94d7811281ccf0d143a1cf768d1c49e1e54af63e7b708ab2ee3eb87face/pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d", size = 6391281, upload-time = "2026-07-01T11:55:26.252Z" }, + { url = "https://files.pythonhosted.org/packages/d2/87/24233f785f55474dc02ce3e739c5528a77e3a862e9333d1dd7a25cc31f70/pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931", size = 7096716, upload-time = "2026-07-01T11:55:28.318Z" }, + { url = "https://files.pythonhosted.org/packages/23/26/fcb2f6e37175b04f53570b59937867e2b80ee1685e744023153028fc14f9/pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7", size = 6474125, upload-time = "2026-07-01T11:55:30.956Z" }, + { url = "https://files.pythonhosted.org/packages/90/de/3634abee5f1c9e13c56787b7d5517b0ba8d6de51700b95578cf338349c9f/pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c", size = 7242939, upload-time = "2026-07-01T11:55:34.044Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2a/fd13f8eb24de5714a6eb444a3d67e2842c6c576e159a43793adf23051351/pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45", size = 2567506, upload-time = "2026-07-01T11:55:35.988Z" }, + { url = "https://files.pythonhosted.org/packages/5d/dc/8fdce34ec725a33c81c6ba122b904d6b9024e50ea9ac7bede62fab54506c/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139", size = 4162063, upload-time = "2026-07-01T11:55:37.941Z" }, + { url = "https://files.pythonhosted.org/packages/76/66/2044b9a63d3b84ff048228dfcb7cd9bf0df983e8470971bf7d4c57b693de/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402", size = 4255549, upload-time = "2026-07-01T11:55:40.022Z" }, + { url = "https://files.pythonhosted.org/packages/52/7e/1f67e6f4ece6b582ee4b539decbcc9f848dc245a93ed8cd7338bafef72f1/pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c", size = 3696331, upload-time = "2026-07-01T11:55:41.98Z" }, + { url = "https://files.pythonhosted.org/packages/12/40/d306fc2c8e4d45d7f175c77edca7063be7b86fe7fe6e68f4353bf71d808c/pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f", size = 5350370, upload-time = "2026-07-01T11:55:44.028Z" }, + { url = "https://files.pythonhosted.org/packages/dd/44/668fb1437e8ce420f62d6106eb66e44a5971602a4d794615bdf79315d82d/pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701", size = 4780147, upload-time = "2026-07-01T11:55:46.073Z" }, + { url = "https://files.pythonhosted.org/packages/0c/08/93fa2e70e30a2d81547e481b6ee2bb9522117221fb1e0ce4b5df70967677/pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace", size = 6273659, upload-time = "2026-07-01T11:55:48.264Z" }, + { url = "https://files.pythonhosted.org/packages/f8/6d/043e96ff814fc31a33077e4cba86082167db520c93632afdf2042febbb0c/pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4", size = 6947439, upload-time = "2026-07-01T11:55:50.503Z" }, + { url = "https://files.pythonhosted.org/packages/af/92/ba71d2ee2ac0edf3fa33bd9d5ee9ee080da70b1766f3ca3934f9938ddac9/pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39", size = 6353577, upload-time = "2026-07-01T11:55:52.697Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ce/e63064e2122923ff687c8ad792d0d736a7b3920a56a46982e81a7fdd25d6/pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71", size = 7060394, upload-time = "2026-07-01T11:55:55.149Z" }, + { url = "https://files.pythonhosted.org/packages/54/76/a09cc3ccc8d773a7283d34c38bec1708f9e3cc932093cbc4c5e71ac4060b/pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827", size = 6467375, upload-time = "2026-07-01T11:55:57.769Z" }, + { url = "https://files.pythonhosted.org/packages/3e/03/1846c49ba3b1d5550392a4bbd06d6fb4578e1cd91a803198b5c90f5f7d53/pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5", size = 7237048, upload-time = "2026-07-01T11:55:59.975Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bb/89f35dcc79610423f9f195504d7def7f0d1416a711541b42867e25fe3412/pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658", size = 2566006, upload-time = "2026-07-01T11:56:02.143Z" }, + { url = "https://files.pythonhosted.org/packages/30/88/707027ba09942dfa2c28759b5c222d769290a41c6d20ea60ec250801941f/pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf", size = 5352509, upload-time = "2026-07-01T11:56:04.2Z" }, + { url = "https://files.pythonhosted.org/packages/b0/6d/00352fa25332c2569cd387851f568cc5a4b75a9adbfb37ac4fbce4c02eec/pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64", size = 4783167, upload-time = "2026-07-01T11:56:06.631Z" }, + { url = "https://files.pythonhosted.org/packages/13/4f/9e049dfa21af7c22427275720e2490267ba8138120add5c4c574deb69782/pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e", size = 6329237, upload-time = "2026-07-01T11:56:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/36/16/cf6eeaae8d0fce8dd390a33437cf68c5d5bd73834a2bc6e2f14efda0ab45/pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777", size = 6997047, upload-time = "2026-07-01T11:56:11.379Z" }, + { url = "https://files.pythonhosted.org/packages/1e/69/dbf769bdd55f48bf5733cac28edc6364ffaa072ec9ba336266e4fe66be55/pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1", size = 6400440, upload-time = "2026-07-01T11:56:13.908Z" }, + { url = "https://files.pythonhosted.org/packages/a0/e1/ffc9cfc2eea0d178da8018e18e959301ad9d6bc9f3edb7181e748a474b97/pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9", size = 7105895, upload-time = "2026-07-01T11:56:16.575Z" }, + { url = "https://files.pythonhosted.org/packages/18/f0/a5595c1e8c3ae44b9828cb2f0fa8155e5095ef04d6327b8f61cf44a3df85/pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8", size = 6474384, upload-time = "2026-07-01T11:56:18.855Z" }, + { url = "https://files.pythonhosted.org/packages/e4/04/62bcd9f844984c5938d3b05264a61d797a29d3e0812341a8204af70bbdee/pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418", size = 7243537, upload-time = "2026-07-01T11:56:21.214Z" }, + { url = "https://files.pythonhosted.org/packages/3d/68/1f3066acedf37673694a7141381d8f811ae97f30d34413d236abe7d489f1/pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59", size = 2567491, upload-time = "2026-07-01T11:56:23.506Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.9.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9f/4a/0883b8e3802965322523f0b200ecf33d31f10991d0401162f4b23c698b42/platformdirs-4.9.6.tar.gz", hash = "sha256:3bfa75b0ad0db84096ae777218481852c0ebc6c727b3168c1b9e0118e458cf0a", size = 29400, upload-time = "2026-04-09T00:04:10.812Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/a6/a0a304dc33b49145b21f4808d763822111e67d1c3a32b524a1baf947b6e1/platformdirs-4.9.6-py3-none-any.whl", hash = "sha256:e61adb1d5e5cb3441b4b7710bea7e4c12250ca49439228cc1021c00dcfac0917", size = 21348, upload-time = "2026-04-09T00:04:09.463Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/44/c87281c333769159c50594f22610f77398a47ccbfbbf23074e744e86f87c/propcache-0.5.2.tar.gz", hash = "sha256:01c4fc7480cd0598bb4b57022df55b9ca296da7fc5a8760bd8451a7e63a7d427", size = 50208, upload-time = "2026-05-08T21:02:12.199Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4a/cb/e27bc2b2737a0bb49962b275efa051e8f1c35a936df7d5139b6b658b7dc9/propcache-0.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:806719138ecd720339a12410fb9614ac9b2b2d3a5fdf8235d56981c36f4039ba", size = 95887, upload-time = "2026-05-08T21:00:11.277Z" }, + { url = "https://files.pythonhosted.org/packages/e6/13/b8ae04c59392f8d11c6cd9fb4011d1dc7c86b81225c770280300e259ffe1/propcache-0.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:db2b80ea58eab4f86b2beec3cc8b39e8ff9276ac20e96b7cce43c8ae84cd6b5a", size = 54654, upload-time = "2026-05-08T21:00:12.604Z" }, + { url = "https://files.pythonhosted.org/packages/2c/7d/49777a3e20b55863d4794384a38acd460c04157b0a00f8602b0d508b8431/propcache-0.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e5cbfac9f61484f7e9f3597775500cd3ebe8274e9b050c38f9525c77c97520bf", size = 55190, upload-time = "2026-05-08T21:00:13.935Z" }, + { url = "https://files.pythonhosted.org/packages/44/c7/085d0cd63062e84044e3f05797749c3f8e3938ff3aeb0eb2f69d43fafc91/propcache-0.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbc581d2814337da56222fab8dc5f161cd798a434e49bac27930aaef798e144", size = 59995, upload-time = "2026-05-08T21:00:15.526Z" }, + { url = "https://files.pythonhosted.org/packages/9c/42/32cf8e3009e92b2645cf1e944f701e8ea4e924dffde1ee26db860bcbf7e4/propcache-0.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:857187f381f88c8e2fa2fe56ab94879d011b883d5a2ee5a1b60a8cd2a06846d9", size = 63422, upload-time = "2026-05-08T21:00:16.824Z" }, + { url = "https://files.pythonhosted.org/packages/9e/1b/f112433f99fc979431b87a39ef169e3f8df070d99a72792c56d6937ac48b/propcache-0.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:178b4a2cdaac1818e2bf1c5a99b94383fa73ea5382e032a48dec07dc5668dc42", size = 64342, upload-time = "2026-05-08T21:00:18.362Z" }, + { url = "https://files.pythonhosted.org/packages/14/15/5574111ae50dd6e879456888c0eadd4c5a869959775854e18e18a6b345f3/propcache-0.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f328175a2cde1f0ff2c4ed8ce968b9dcfb55f3a7153f39e2957ed994da13476", size = 61639, upload-time = "2026-05-08T21:00:19.692Z" }, + { url = "https://files.pythonhosted.org/packages/cc/da/4d775080b1490c0ae604acda868bd71aabe3a89ed16f2aa4339eb8a283e7/propcache-0.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5671d09a36b06d0fd4a3da0fccbcae360e9b1570924171a15e9e0997f0249fba", size = 61588, upload-time = "2026-05-08T21:00:21.155Z" }, + { url = "https://files.pythonhosted.org/packages/04/ac/f076982cbe2195ee9cf32de5a1e46951d9fb399fc207f390562dd0fd8fb2/propcache-0.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:80168e2ebe4d3ec6599d10ad8f520304ae1cad9b6c5a95372aef1b66b7bfb53a", size = 60029, upload-time = "2026-05-08T21:00:22.713Z" }, + { url = "https://files.pythonhosted.org/packages/70/60/189be62e0dd898dce3b331e1b8c7a543cd3a405ac0c81fe8ee8a9d5d77e1/propcache-0.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:45f11346f884bc47444f6e6647131055844134c3175b629f84952e2b5cd62b64", size = 56774, upload-time = "2026-05-08T21:00:24.001Z" }, + { url = "https://files.pythonhosted.org/packages/ea/9e/93377b9c7939c1ffae98f878dee955efadfd638078bc86dbc21f9d52f651/propcache-0.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8e778ebd44ef4f66ed60a0416b06b489687db264a9c0b3620362f26489492913", size = 63532, upload-time = "2026-05-08T21:00:25.545Z" }, + { url = "https://files.pythonhosted.org/packages/14/f9/590ef6cfb9b8028d516d287812ece32bb0bc5f11fbb9c8bf6b2e6313fec8/propcache-0.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:c0cb9ed24c8964e172768d455a38254c2dd8a552905729ce006cad3d3dda59b1", size = 61592, upload-time = "2026-05-08T21:00:27.186Z" }, + { url = "https://files.pythonhosted.org/packages/b4/5e/70958b3034c297a630bba2f17ca7abc2d5f39a803ad7e370ab79d1ecd022/propcache-0.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:1d1ad32d9d4355e2be65574fd0bfd3677e7066b009cd5b9b2dee8aa6a6393b33", size = 64788, upload-time = "2026-05-08T21:00:28.8Z" }, + { url = "https://files.pythonhosted.org/packages/12/fd/77fe5936d8c3086ca9048f7f415f122ed82e53884a9ec193646b42deef06/propcache-0.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c80f4ba3e8f00189165999a742ee526ebeccedf6c3f7beb0c7df821e9772435a", size = 62514, upload-time = "2026-05-08T21:00:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/cf/74/66bd798b5b3be70aa1b391f5cc9d6a0a5532d7fd3b19ec0b213e72e6ad9d/propcache-0.5.2-cp312-cp312-win32.whl", hash = "sha256:8c7972d8f193740d9175f0998ab38717e6cd322d5935c5b0fef8c0d323fd9031", size = 39018, upload-time = "2026-05-08T21:00:31.622Z" }, + { url = "https://files.pythonhosted.org/packages/61/7c/5c0d34aa3024694d6dcb9271cdbdd08c4e47c1c0ad95ec7e7bc74cdea145/propcache-0.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:d9ee8826a7d47863a08ac44e1a5f611a462eefc3a194b492da242128bec75b42", size = 42322, upload-time = "2026-05-08T21:00:32.918Z" }, + { url = "https://files.pythonhosted.org/packages/4d/91/875812f1a3feb20ceba818ef39fbe4d92f1081e04ac815c822496d0d038b/propcache-0.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:2800a4a8ead6b28cccd1ec54b59346f0def7922ee1c7598e8499c733cfbb7c84", size = 38172, upload-time = "2026-05-08T21:00:35.124Z" }, + { url = "https://files.pythonhosted.org/packages/c5/09/f049e45385503fe67db75a6b6186a7b9f0c3930366dc960522c312a825b1/propcache-0.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:099aaf4b4d1a02265b92a977edf00b5c4f63b3b17ac6de39b0d637c9cac0188a", size = 94457, upload-time = "2026-05-08T21:00:36.355Z" }, + { url = "https://files.pythonhosted.org/packages/6b/65/83d1d05655baf63113731bd5a1008435e14f8d1e5a06cbe4ec5b23ad7a31/propcache-0.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:68ce1c44c7a813a7f71ea04315a8c7b330b63db99d059a797a4651bb6f69f117", size = 53835, upload-time = "2026-05-08T21:00:38.072Z" }, + { url = "https://files.pythonhosted.org/packages/a9/12/a6ba6482bb5ea3260c000c9b20881c95fa11c6b30173715668259f844ed7/propcache-0.5.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fc299c129490f55f254cd90be0deca4764e36e9a7c08b4aa588479a3bbed3098", size = 54545, upload-time = "2026-05-08T21:00:39.319Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/7fa086f5764c59ec8a8e157cd93aa8497acc00aba9dcdec56bfffb32602d/propcache-0.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a6ae2198be502c10f09b2516e7b5d019816924bc3183a43ce792a7bd6625e6f4", size = 59886, upload-time = "2026-05-08T21:00:40.621Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e4/5d7663dc8235956c8f5281698a3af1d351d8820341ddd890f59d9a9127f2/propcache-0.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6041d31504dc1779d700e1edcfb08eea334b357620b06681a4eabb57a74e574e", size = 63261, upload-time = "2026-05-08T21:00:41.775Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4a/15a03adee24d6350da4292caeac44c34c033d2afe5e87eb370f38854560f/propcache-0.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f7eabc04151c78a9f4d5bbb5f1faf571e4defeb4b585e0fe95b60ff2dbe4d3d7", size = 64184, upload-time = "2026-05-08T21:00:43.018Z" }, + { url = "https://files.pythonhosted.org/packages/8b/c6/979176efdaa3d239e36d503d5af63a0a773b36662ed8f52e5b6a6d9fd40e/propcache-0.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4db0ba63d693afd40d249bd93f842b5f144f8fcbb83de05660373bcf30517b1d", size = 61534, upload-time = "2026-05-08T21:00:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/c8/22/63e8cd1bae4c2d2be6493b6b7d10566ddafad88137cfbc99964a1119853c/propcache-0.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1dbcf7675229b35d31abb6547d8ebc8c27a830ac3f9a794edff6254873ec7c0a", size = 61500, upload-time = "2026-05-08T21:00:45.796Z" }, + { url = "https://files.pythonhosted.org/packages/60/5a/28e5d9acbac1cc9ccb67045e8c1b943aa8d79fdf39c93bd73cacd68008ea/propcache-0.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d310c013aad2c72f1c3f2f8dd3279d460a858c551f97aeb8c63e4693cca7b4d2", size = 59994, upload-time = "2026-05-08T21:00:47.093Z" }, + { url = "https://files.pythonhosted.org/packages/f3/40/db650677f554a95b9c01a7c9d93d629e93a15562f5deb4573c9ee136fed2/propcache-0.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:06187263ddad280d05b4d8a8b3bb7d164cbebd469236544a42e6d9b28ac6a4fa", size = 56884, upload-time = "2026-05-08T21:00:48.376Z" }, + { url = "https://files.pythonhosted.org/packages/80/45/70b39b89516ff8b96bf732fa6fded8cef20f293cb1508690101c3c07ec51/propcache-0.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3115559b8effafd63b142ea5ed53d63a16ea6469cbc63dce4ee194b42db5d853", size = 63464, upload-time = "2026-05-08T21:00:49.954Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e2/fa59d3a89eac5534293124af4f1d0d0ada091ce4a0ab4610ce03fd2bdd8d/propcache-0.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:c60462af8e6dc30c35407c7237ea908d777b22862bbee27bc4699c0d8bcdc45a", size = 61588, upload-time = "2026-05-08T21:00:51.281Z" }, + { url = "https://files.pythonhosted.org/packages/0b/97/efb547a55c4bc7381cfb202d6a2239ac621045277bc1ea5dfd3a7f0516c0/propcache-0.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:40314bca9ac559716fe374094fc81c11dcc34b64fd6c585360f5775690505704", size = 64667, upload-time = "2026-05-08T21:00:52.602Z" }, + { url = "https://files.pythonhosted.org/packages/92/56/f5c7d9b4b7595d5127da38974d791b2153f3d1eae6c674af3583ace92ad3/propcache-0.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cfa21e036ce1e1db2be04ba3b85d2df1bb1702fa01932d984c5464c665228ff4", size = 62463, upload-time = "2026-05-08T21:00:54.303Z" }, + { url = "https://files.pythonhosted.org/packages/bd/3b/484a3a65fc9f9f60c41dcd17b428bace5389544e2c680994534a20755066/propcache-0.5.2-cp313-cp313-win32.whl", hash = "sha256:f156a3529f38063b6dbaf356e15602a7f95f8055b1295a438433a6386f10463d", size = 38621, upload-time = "2026-05-08T21:00:55.808Z" }, + { url = "https://files.pythonhosted.org/packages/1c/fd/3f0f10dba4dabad3bf53102be007abf55481067952bde0fdddff439e7c61/propcache-0.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:dfed59d0a5aeb01e242e66ff0300bc4a265a7c05f612d30016f0b60b1017d757", size = 41649, upload-time = "2026-05-08T21:00:57.061Z" }, + { url = "https://files.pythonhosted.org/packages/90/ec/6ce619cc32bb500a482f811f9cd509368b4e58e638d13f2c68f370d6b475/propcache-0.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:ba338430e87ceb9c8f0cf754de38a9860560261e56c00376debd628698a7364f", size = 37636, upload-time = "2026-05-08T21:00:58.646Z" }, + { url = "https://files.pythonhosted.org/packages/1b/82/c1d268bbbf2ef981c5bf0fbbe746db617c66e3bcefe431a1aa8943fbe23a/propcache-0.5.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:a592f5f3da71c8691c788c13cb6734b6d17663d2e1cb8caddf0673d01ef8847d", size = 98872, upload-time = "2026-05-08T21:00:59.889Z" }, + { url = "https://files.pythonhosted.org/packages/f4/d4/52c871e73e864e6b34c0e2d58ac1ec5ccd149497ddc7ad2137ae98323a35/propcache-0.5.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:6a997d0489e9668a384fcfd5061b857aa5361de73191cac204d04b889cfbbafa", size = 56257, upload-time = "2026-05-08T21:01:01.195Z" }, + { url = "https://files.pythonhosted.org/packages/67/f0/9b90ca2a210b3d09bcfcd96ecd0f55545c091535abce2a45de2775cfd357/propcache-0.5.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:10734b5484ea113152ee25a91dccedf81631791805d2c9ccb054958e51842c94", size = 56696, upload-time = "2026-05-08T21:01:02.941Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0e/6e9d4ba07c8e56e21ddec1e75f12148142b21ca83a51871babce095334f4/propcache-0.5.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cafca7e56c12bb02ae16d283742bef25a61122e9dab2b5b3f2ccbe589ce32164", size = 62378, upload-time = "2026-05-08T21:01:04.475Z" }, + { url = "https://files.pythonhosted.org/packages/65/19/c10badaa463dde8a27ce884f8ee2ec37e6035b7c9f5ff0c8f74f06f08dac/propcache-0.5.2-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f064f8d2b59177878b7615df1735cd8fe3462ed6be8c7b217d17a276489c2b7f", size = 65283, upload-time = "2026-05-08T21:01:05.959Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b6/93bea99ca80e19cef6512a8580e5b7857bbe09422d9daa7fd4ef5723306c/propcache-0.5.2-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f78abfa8dfc32376fd1aacf597b2f2fbbe0ea751419aee718af5d4f82537ef8c", size = 66616, upload-time = "2026-05-08T21:01:07.228Z" }, + { url = "https://files.pythonhosted.org/packages/83/e4/5c7462e50625f051f37fb38b8224f7639f667184bbd34424ec83819bb1b7/propcache-0.5.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f7467da8a9822bf1a55336f877340c5bcbd3c482afc43a99771169f74a26dedc", size = 63773, upload-time = "2026-05-08T21:01:08.514Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b6/99238894047b13c823be25027e736626cd414a52a5e30d2c3347c2733529/propcache-0.5.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a6ddc6ac9e25de626c1f129c1b467d7ecd33ce2237d3fd0c4e429feef0a7ee1f", size = 63664, upload-time = "2026-05-08T21:01:09.874Z" }, + { url = "https://files.pythonhosted.org/packages/85/1e/a3a1a63116a2b8edb415a8bb9a6f0c34bd03830b1e18e8ce2904e1dc1cf4/propcache-0.5.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:2f22cbbac9e26a8e864c0985ff1268d5d939d53d9d9411a9824279097e03a2cb", size = 62643, upload-time = "2026-05-08T21:01:11.132Z" }, + { url = "https://files.pythonhosted.org/packages/e4/03/893cf147de2fc6543c5eaa07ad833170e7e2a2385725bbebe8c0503723bb/propcache-0.5.2-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:fc76378c62a0f04d0cd82fbb1a2cd2d7e28fcb40d5873f28a6c44e388aaa2751", size = 59595, upload-time = "2026-05-08T21:01:12.387Z" }, + { url = "https://files.pythonhosted.org/packages/86/3b/04c1a2e12c57766568ba75ba72b3bf2042818d4c1425fab6fc07155c7cff/propcache-0.5.2-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:acd2c8edba48e31e58a363b8cf4e5c7db3b04b3f9e371f601df30d9b0d244836", size = 65711, upload-time = "2026-05-08T21:01:13.676Z" }, + { url = "https://files.pythonhosted.org/packages/1c/34/80f8d0099f8d6bacc4de1624c85672681c8cd1149ca2da0e38fd120b817f/propcache-0.5.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:452b5065457eb9991ec5eb38ff41d6cd4c991c9ac7c531c4d5849ae473a9a13f", size = 64247, upload-time = "2026-05-08T21:01:14.936Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1a/8b08f3a5f1037e9e370c55883ceeeee0f6dd0416fb2d2d67b8bfc91f2a79/propcache-0.5.2-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:3430bb2bfe1331885c427745a751e774ee679fd4344f80b97bf879815fe8fa55", size = 67102, upload-time = "2026-05-08T21:01:16.281Z" }, + { url = "https://files.pythonhosted.org/packages/34/68/8bdb7bb7756d76e005490649d10e4a8369e610c74d619f71e1aedf889e9c/propcache-0.5.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:cef6cea3922890dd6c9654971001fa797b526c16ab5e1e46c05fd6f877be7568", size = 64964, upload-time = "2026-05-08T21:01:17.57Z" }, + { url = "https://files.pythonhosted.org/packages/0a/aa/50fb0b5d3968b61a510926ff8b8465f1d6e976b3ab74496d7a4b9fc42515/propcache-0.5.2-cp313-cp313t-win32.whl", hash = "sha256:72d61e16dd78228b58c5d47be830ff3da7e5f139abdf0aef9d86cde1c5cf2191", size = 42546, upload-time = "2026-05-08T21:01:18.946Z" }, + { url = "https://files.pythonhosted.org/packages/ae/4c/0ddbae64321bd4a95bcbfc19307238016b5b1fee645c84626c8d539e5b74/propcache-0.5.2-cp313-cp313t-win_amd64.whl", hash = "sha256:0958834041a0166d343b8d2cedcd8bcbaeb4fdbe0cf08320c5379f143c3be6e7", size = 46330, upload-time = "2026-05-08T21:01:20.162Z" }, + { url = "https://files.pythonhosted.org/packages/00/d9/9cddc8efb78d8af264c5ec9f6d10b62f57c515feda8d321595f56010fb23/propcache-0.5.2-cp313-cp313t-win_arm64.whl", hash = "sha256:6de8bd93ddde9b992cf2b2e0d796d501a19026b5b9fd87356d7d0779531a8d96", size = 40521, upload-time = "2026-05-08T21:01:21.399Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ea/23ee535d90ce8bcc465a3028eb3cc0ce3bd1005f4bb27710b30587de798d/propcache-0.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:46088abff4cba581dea21ae0467a480526cb25aa5f3c269e909f800328bc3999", size = 94662, upload-time = "2026-05-08T21:01:22.683Z" }, + { url = "https://files.pythonhosted.org/packages/b5/06/c5a52f419b5d8972f8d46a7577476090d8e3263ff589ce40b5ca4968d5be/propcache-0.5.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fc88b26f08d634f7bc819a7852e5214f5802641ab8d9fd5326892292eee1993e", size = 53928, upload-time = "2026-05-08T21:01:23.986Z" }, + { url = "https://files.pythonhosted.org/packages/63/b1/4260d67d6bd85e58a66b72d54ce15d5de789b6f3870cc6bedf8ff9667401/propcache-0.5.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:97797ebb098e670a2f92dd66f32897e30d7615b14e7f59711de23e30a9072539", size = 54650, upload-time = "2026-05-08T21:01:25.305Z" }, + { url = "https://files.pythonhosted.org/packages/70/06/2f46c318e3307cd7a6a7481def374ce838c0fe20084b39dd54b0879d0e99/propcache-0.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ba57fffe4ac99c5d30076161b5866336d97600769bad35cc68f7774b15298a4e", size = 59912, upload-time = "2026-05-08T21:01:26.545Z" }, + { url = "https://files.pythonhosted.org/packages/4c/29/fe1aebec2ce57ab985a9c382bded1124431f85078113aa222c5d278430d4/propcache-0.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:583c19759d9eec1e5b69e2fbef36a7d9c326041be9746cb822d335c8cedc2979", size = 63300, upload-time = "2026-05-08T21:01:27.937Z" }, + { url = "https://files.pythonhosted.org/packages/b4/18/2334b26768b6c82be8c69e83671b767d5ef426aa09b0cba6c2ea47816774/propcache-0.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d0326e2e5e1f3163fa306c834e48e8d490e5fae607a097a40c0648109b47ba80", size = 64208, upload-time = "2026-05-08T21:01:29.484Z" }, + { url = "https://files.pythonhosted.org/packages/2b/76/7f1bfd6afff4c5e38e36a3c6d68eb5f4b7311ea80baf693db78d95b603c4/propcache-0.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e00820e192c8dbebcafb383ebbf99030895f09905e7a0eb2e0340a0bcc2bc825", size = 61633, upload-time = "2026-05-08T21:01:31.068Z" }, + { url = "https://files.pythonhosted.org/packages/c4/46/b3ff8aba2b4953a3e50de2cf72f1b5748b8eca93b15f3dc2c84339084c09/propcache-0.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c66afea89b1e43725731d2004732a046fe6fe955d51f952c3e95a7314a284a39", size = 61724, upload-time = "2026-05-08T21:01:32.374Z" }, + { url = "https://files.pythonhosted.org/packages/c5/01/814cfcafbcff954f94c01cf30e097ddc88a076b5440fbcf4570753437d40/propcache-0.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d4dc37dec6c6cdad0b57881a5658fd14fbf53e333b1a86cf86559f190e1d9ec4", size = 60069, upload-time = "2026-05-08T21:01:33.67Z" }, + { url = "https://files.pythonhosted.org/packages/da/68/5c6f7622d510cc666a300687e06fd060c1a43361c0c9b20d284f06d8096a/propcache-0.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:5570dbcc97571c15f68068e529c92715a12f8d54030e272d264b377e22bd17a5", size = 57099, upload-time = "2026-05-08T21:01:34.915Z" }, + { url = "https://files.pythonhosted.org/packages/55/27/9cb0b4c679124085327957d42521c99dba04c88c90c3e55a6f0b633ebccc/propcache-0.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f814362777a9f841adddb200ecdf8f5cb1e5a3c4b7a86378edbd6ccb26edd702", size = 63391, upload-time = "2026-05-08T21:01:36.231Z" }, + { url = "https://files.pythonhosted.org/packages/f0/9d/7258aaa5bdf60fc6f27591eef6fe52768cb0beda7140be477c8b12c9794a/propcache-0.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:196913dea116aeb5a2ba95af4ddcb7ea85559ae07d8eee8751688310d09168c3", size = 61626, upload-time = "2026-05-08T21:01:37.545Z" }, + { url = "https://files.pythonhosted.org/packages/8e/0d/41c602003e8a9b16fe1e7eadf62c7bfba9d5474370b24200bf48b315f45f/propcache-0.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6e7b8719005dd1175be4ab1cd25e9b98659a5e0347331506ec6760d2773a7fb5", size = 64781, upload-time = "2026-05-08T21:01:38.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f3/38e66b1856e9bd079deea015bc4a55f7767c0e4db2f7dcf69e7e680ba4ce/propcache-0.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:51f96d685ab16e88cab128cd37a52c5da540809c8b879fa047731bfcb4ad35a4", size = 62570, upload-time = "2026-05-08T21:01:40.415Z" }, + { url = "https://files.pythonhosted.org/packages/95/ca/bbfe9b910ce57dde8bb4876b4520fc02a4e89497c10de26be936758a3aaa/propcache-0.5.2-cp314-cp314-win32.whl", hash = "sha256:cc6fc3cc62e8501d3ed62894425040d2728ecddb1ed072737a5c70bd537aa9f0", size = 39436, upload-time = "2026-05-08T21:01:41.654Z" }, + { url = "https://files.pythonhosted.org/packages/61/d2/45c9defbaa1ea297035d9d4cce9e8f80daafbf19319c6007f157c6256ea9/propcache-0.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:81e3a30b0bb60caa22033dd0f8a3618d1d67356212514f62c57db75cb0ef410c", size = 42373, upload-time = "2026-05-08T21:01:43.041Z" }, + { url = "https://files.pythonhosted.org/packages/44/68/9ea5103f41d5217d7d6ec24db90018e23aebec070c3f9a6e54d12b841fd8/propcache-0.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:0d2c9bf8528f135dbb805ce027567e09164f7efa51a2be07458a2c0420f292d0", size = 38554, upload-time = "2026-05-08T21:01:44.336Z" }, + { url = "https://files.pythonhosted.org/packages/8a/81/fadf555f42d3b762eea8a53950b0489fdc0aa9da5f8ed9e10ce0a4e01b48/propcache-0.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4bc8ff1feffc6a61c7002ffe84634c41b822e104990ae009f44a0834430070bb", size = 99395, upload-time = "2026-05-08T21:01:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/f5/c9/c61e134a686949cf7971af3a390148b1156f7be81c73bc0cd12c873e2d48/propcache-0.5.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79aa3ff0a9b566633b642fa9caf7e21ed1c13d6feca718187873f199e1514078", size = 56653, upload-time = "2026-05-08T21:01:47.307Z" }, + { url = "https://files.pythonhosted.org/packages/cb/73/daf935ea7048ddd7ec8eec5345b4a40b619d2d178b3c0a0900796bc3c794/propcache-0.5.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1b31822f4474c4036bae62de9402710051d431a606d6a0f907fec79935a071aa", size = 56914, upload-time = "2026-05-08T21:01:48.573Z" }, + { url = "https://files.pythonhosted.org/packages/79/9f/aba959b435ea18617edd7cf0a7ad0b9c574b8fc7e3d2cd55fb59cb255d33/propcache-0.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13fef48778b5a2a756523fdb781326b028ca75e32858b04f2cdd19f394564917", size = 62567, upload-time = "2026-05-08T21:01:49.903Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a1/859942de9a791ff42f6141736f5b37749b8f53e65edfa49638c67dd67e6a/propcache-0.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8b73ab70f1a3351fbc71f663b3e645af6dd0329100c353081cf69c37433fc6fe", size = 65542, upload-time = "2026-05-08T21:01:51.204Z" }, + { url = "https://files.pythonhosted.org/packages/b5/61/315bc0fd6c0fc7f80a528b8afd209e5fc4a875ea79571b91b8f50f442907/propcache-0.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5538d2c13d93e4698af7e092b57bc7298fd35d1d58e656ae18f23ee0d0378e03", size = 66845, upload-time = "2026-05-08T21:01:52.539Z" }, + { url = "https://files.pythonhosted.org/packages/47/f7/9f8122e3132e8e354ac41975ef8f1099be7d5a16bc7ae562734e993665c0/propcache-0.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cd645f03898405cabe694fb8bc35241e3a9c332ec85627584fe3de201452b335", size = 63985, upload-time = "2026-05-08T21:01:53.847Z" }, + { url = "https://files.pythonhosted.org/packages/c8/54/c317819ec157cbf6f35df9df9657a6f82daf34d5faf15948b2f639c2192e/propcache-0.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a473b3440261e0c60706e732b2ed2f517857344fc21bf48fdfe211e2d98eb285", size = 63999, upload-time = "2026-05-08T21:01:55.179Z" }, + { url = "https://files.pythonhosted.org/packages/5a/56/387e3f7dfce0a9233df41fb888aa1c30222cb4bbbf09537c02dd9bd85fe2/propcache-0.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7afa37062e6650640e932e4cc9297d81f9f42d9944029cc386b8247dea4da837", size = 62779, upload-time = "2026-05-08T21:01:57.489Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9c/596784cb5824ed61ee960d3f8655a3f0993e107c6e98ab6c818b7fb92ccb/propcache-0.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:8a90efd5777e996e42d568db9ac740b944d691e565cbfd31b2f7832f9184b2b8", size = 59796, upload-time = "2026-05-08T21:01:58.736Z" }, + { url = "https://files.pythonhosted.org/packages/c2/3d/1a6cfa1726a48542c1e8784a0761421476a5b68e09b7f36bf95eb954aaba/propcache-0.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:f19bb891234d72535764d703bfed1153cc34f4214d5bd7150aee1eec9e8f4366", size = 66023, upload-time = "2026-05-08T21:02:00.228Z" }, + { url = "https://files.pythonhosted.org/packages/e4/0e/05fd6990369477076e4e280bcb970de760fddf0161a46e988bc95f7940ec/propcache-0.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:32775082acd2d807ee3db715c7770d38767b817870acfa08c29e057f3c4d5b56", size = 64448, upload-time = "2026-05-08T21:02:01.888Z" }, + { url = "https://files.pythonhosted.org/packages/cd/86/5f8da315a4309c62c10c0b2516b17492d5d3bbe1bb862b96604db67e2a37/propcache-0.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9282fb1a3bccd038da9f768b927b24a0c753e466c086b7c4f3c6982851eefb2d", size = 67329, upload-time = "2026-05-08T21:02:03.484Z" }, + { url = "https://files.pythonhosted.org/packages/da/d3/3368efe79ab21f0cdf86ef49895811c9cc933131d4cde1f28a624e22e712/propcache-0.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cc49723e2f60d6b32a0f0b08a3fd6d13203c07f1cd9566cfce0f12a917c967a2", size = 65172, upload-time = "2026-05-08T21:02:04.745Z" }, + { url = "https://files.pythonhosted.org/packages/d5/07/127e8b0bacfb325396196f9d976a22453049b89b9b2b08477cc3145faa44/propcache-0.5.2-cp314-cp314t-win32.whl", hash = "sha256:2d7aa89ebca5acc98cba9d1472d976e394782f587bad6661003602a619fd1821", size = 43813, upload-time = "2026-05-08T21:02:06.025Z" }, + { url = "https://files.pythonhosted.org/packages/88/fb/46dad6c0ae49ed230ab1b16c890c2b6314e2403e6c412976f4a72d64a527/propcache-0.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:d447bb0b3054be5818458fbb171208b1d9ff11eba14e18ca18b90cbb45767370", size = 47764, upload-time = "2026-05-08T21:02:07.353Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c4/a47d0a63aa309d10d59ede6e9d4cff03a344a79d1f0f4cd0cd74997b53e0/propcache-0.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:fe67a3d11cd9b4efabfa45c3d00ffba2b26811442a73a581a94b67c2b5faccf6", size = 41140, upload-time = "2026-05-08T21:02:09.065Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ed/1cdcab6ba3d6ab7feca11fc14f0eeea80755bb53ef4e892079f31b10a25f/propcache-0.5.2-py3-none-any.whl", hash = "sha256:be1ddfcbb376e3de5d2e2db1d58d6d67463e6b4f9f040c000de8e300295465fe", size = 14036, upload-time = "2026-05-08T21:02:10.673Z" }, +] + +[[package]] +name = "properdocs" +version = "1.6.7" +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 = "packaging" }, + { name = "pathspec" }, + { name = "platformdirs" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ec/29/f27a4e1eddf72ed3db6e47818fbafe6debbf09fd7051f9c1a007239b46ef/properdocs-1.6.7.tar.gz", hash = "sha256:adc7b16e562890af0e098a7e5b02e3a81c20894a87d6a28d345c9300de73c26e", size = 276141, upload-time = "2026-03-20T20:07:48.167Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bd/4d/fc923f5c85318ee8cc903566dc4e0ebe41b2dfc1d2ecf5546db232397ed6/properdocs-1.6.7-py3-none-any.whl", hash = "sha256:6fa0cfa2e01bf338f684892c8a506cf70ea88ae7f3479c933b6fa20168101cbd", size = 225406, upload-time = "2026-03-20T20:07:46.875Z" }, +] + +[[package]] +name = "py-cpuinfo" +version = "9.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/37/a8/d832f7293ebb21690860d2e01d8115e5ff6f2ae8bbdc953f0eb0fa4bd2c7/py-cpuinfo-9.0.0.tar.gz", hash = "sha256:3cdbbf3fac90dc6f118bfd64384f309edeadd902d7c8fb17f02ffa1fc3f49690", size = 104716, upload-time = "2022-10-25T20:38:06.303Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/a9/023730ba63db1e494a271cb018dcd361bd2c917ba7004c3e49d5daf795a2/py_cpuinfo-9.0.0-py3-none-any.whl", hash = "sha256:859625bc251f64e21f077d099d4162689c762b5d6a4c3c97553d56241c9674d5", size = 22335, upload-time = "2022-10-25T20:38:27.636Z" }, +] + +[[package]] +name = "py-partiql-parser" +version = "0.6.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/7a/a0f6bda783eb4df8e3dfd55973a1ac6d368a89178c300e1b5b91cd181e5e/py_partiql_parser-0.6.3.tar.gz", hash = "sha256:09cecf916ce6e3da2c050f0cb6106166de42c33d34a078ec2eb19377ea70389a", size = 17456, upload-time = "2025-10-18T13:56:13.441Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/33/a7cbfccc39056a5cf8126b7aab4c8bafbedd4f0ca68ae40ecb627a2d2cd3/py_partiql_parser-0.6.3-py2.py3-none-any.whl", hash = "sha256:deb0769c3346179d2f590dcbde556f708cdb929059fb654bad75f4cf6e07f582", size = 23752, upload-time = "2025-10-18T13:56:12.256Z" }, +] + +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + +[[package]] +name = "pydantic" +version = "2.12.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/69/44/36f1a6e523abc58ae5f928898e4aca2e0ea509b5aa6f6f392a5d882be928/pydantic-2.12.5.tar.gz", hash = "sha256:4d351024c75c0f085a9febbb665ce8c0c6ec5d30e903bdb6394b7ede26aebb49", size = 821591, upload-time = "2025-11-26T15:11:46.471Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/87/b70ad306ebb6f9b585f114d0ac2137d792b48be34d732d60e597c2f8465a/pydantic-2.12.5-py3-none-any.whl", hash = "sha256:e561593fccf61e8a20fc46dfc2dfe075b8be7d0188df33f221ad1f0139180f9d", size = 463580, upload-time = "2025-11-26T15:11:44.605Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.41.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/71/70/23b021c950c2addd24ec408e9ab05d59b035b39d97cdc1130e1bce647bb6/pydantic_core-2.41.5.tar.gz", hash = "sha256:08daa51ea16ad373ffd5e7606252cc32f07bc72b28284b6bc9c6df804816476e", size = 460952, upload-time = "2025-11-04T13:43:49.098Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5f/5d/5f6c63eebb5afee93bcaae4ce9a898f3373ca23df3ccaef086d0233a35a7/pydantic_core-2.41.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:f41a7489d32336dbf2199c8c0a215390a751c5b014c2c1c5366e817202e9cdf7", size = 2110990, upload-time = "2025-11-04T13:39:58.079Z" }, + { url = "https://files.pythonhosted.org/packages/aa/32/9c2e8ccb57c01111e0fd091f236c7b371c1bccea0fa85247ac55b1e2b6b6/pydantic_core-2.41.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:070259a8818988b9a84a449a2a7337c7f430a22acc0859c6b110aa7212a6d9c0", size = 1896003, upload-time = "2025-11-04T13:39:59.956Z" }, + { url = "https://files.pythonhosted.org/packages/68/b8/a01b53cb0e59139fbc9e4fda3e9724ede8de279097179be4ff31f1abb65a/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e96cea19e34778f8d59fe40775a7a574d95816eb150850a85a7a4c8f4b94ac69", size = 1919200, upload-time = "2025-11-04T13:40:02.241Z" }, + { url = "https://files.pythonhosted.org/packages/38/de/8c36b5198a29bdaade07b5985e80a233a5ac27137846f3bc2d3b40a47360/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ed2e99c456e3fadd05c991f8f437ef902e00eedf34320ba2b0842bd1c3ca3a75", size = 2052578, upload-time = "2025-11-04T13:40:04.401Z" }, + { url = "https://files.pythonhosted.org/packages/00/b5/0e8e4b5b081eac6cb3dbb7e60a65907549a1ce035a724368c330112adfdd/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:65840751b72fbfd82c3c640cff9284545342a4f1eb1586ad0636955b261b0b05", size = 2208504, upload-time = "2025-11-04T13:40:06.072Z" }, + { url = "https://files.pythonhosted.org/packages/77/56/87a61aad59c7c5b9dc8caad5a41a5545cba3810c3e828708b3d7404f6cef/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e536c98a7626a98feb2d3eaf75944ef6f3dbee447e1f841eae16f2f0a72d8ddc", size = 2335816, upload-time = "2025-11-04T13:40:07.835Z" }, + { url = "https://files.pythonhosted.org/packages/0d/76/941cc9f73529988688a665a5c0ecff1112b3d95ab48f81db5f7606f522d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eceb81a8d74f9267ef4081e246ffd6d129da5d87e37a77c9bde550cb04870c1c", size = 2075366, upload-time = "2025-11-04T13:40:09.804Z" }, + { url = "https://files.pythonhosted.org/packages/d3/43/ebef01f69baa07a482844faaa0a591bad1ef129253ffd0cdaa9d8a7f72d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d38548150c39b74aeeb0ce8ee1d8e82696f4a4e16ddc6de7b1d8823f7de4b9b5", size = 2171698, upload-time = "2025-11-04T13:40:12.004Z" }, + { url = "https://files.pythonhosted.org/packages/b1/87/41f3202e4193e3bacfc2c065fab7706ebe81af46a83d3e27605029c1f5a6/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c23e27686783f60290e36827f9c626e63154b82b116d7fe9adba1fda36da706c", size = 2132603, upload-time = "2025-11-04T13:40:13.868Z" }, + { url = "https://files.pythonhosted.org/packages/49/7d/4c00df99cb12070b6bccdef4a195255e6020a550d572768d92cc54dba91a/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:482c982f814460eabe1d3bb0adfdc583387bd4691ef00b90575ca0d2b6fe2294", size = 2329591, upload-time = "2025-11-04T13:40:15.672Z" }, + { url = "https://files.pythonhosted.org/packages/cc/6a/ebf4b1d65d458f3cda6a7335d141305dfa19bdc61140a884d165a8a1bbc7/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:bfea2a5f0b4d8d43adf9d7b8bf019fb46fdd10a2e5cde477fbcb9d1fa08c68e1", size = 2319068, upload-time = "2025-11-04T13:40:17.532Z" }, + { url = "https://files.pythonhosted.org/packages/49/3b/774f2b5cd4192d5ab75870ce4381fd89cf218af999515baf07e7206753f0/pydantic_core-2.41.5-cp312-cp312-win32.whl", hash = "sha256:b74557b16e390ec12dca509bce9264c3bbd128f8a2c376eaa68003d7f327276d", size = 1985908, upload-time = "2025-11-04T13:40:19.309Z" }, + { url = "https://files.pythonhosted.org/packages/86/45/00173a033c801cacf67c190fef088789394feaf88a98a7035b0e40d53dc9/pydantic_core-2.41.5-cp312-cp312-win_amd64.whl", hash = "sha256:1962293292865bca8e54702b08a4f26da73adc83dd1fcf26fbc875b35d81c815", size = 2020145, upload-time = "2025-11-04T13:40:21.548Z" }, + { url = "https://files.pythonhosted.org/packages/f9/22/91fbc821fa6d261b376a3f73809f907cec5ca6025642c463d3488aad22fb/pydantic_core-2.41.5-cp312-cp312-win_arm64.whl", hash = "sha256:1746d4a3d9a794cacae06a5eaaccb4b8643a131d45fbc9af23e353dc0a5ba5c3", size = 1976179, upload-time = "2025-11-04T13:40:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/06/8806241ff1f70d9939f9af039c6c35f2360cf16e93c2ca76f184e76b1564/pydantic_core-2.41.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:941103c9be18ac8daf7b7adca8228f8ed6bb7a1849020f643b3a14d15b1924d9", size = 2120403, upload-time = "2025-11-04T13:40:25.248Z" }, + { url = "https://files.pythonhosted.org/packages/94/02/abfa0e0bda67faa65fef1c84971c7e45928e108fe24333c81f3bfe35d5f5/pydantic_core-2.41.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:112e305c3314f40c93998e567879e887a3160bb8689ef3d2c04b6cc62c33ac34", size = 1896206, upload-time = "2025-11-04T13:40:27.099Z" }, + { url = "https://files.pythonhosted.org/packages/15/df/a4c740c0943e93e6500f9eb23f4ca7ec9bf71b19e608ae5b579678c8d02f/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0cbaad15cb0c90aa221d43c00e77bb33c93e8d36e0bf74760cd00e732d10a6a0", size = 1919307, upload-time = "2025-11-04T13:40:29.806Z" }, + { url = "https://files.pythonhosted.org/packages/9a/e3/6324802931ae1d123528988e0e86587c2072ac2e5394b4bc2bc34b61ff6e/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:03ca43e12fab6023fc79d28ca6b39b05f794ad08ec2feccc59a339b02f2b3d33", size = 2063258, upload-time = "2025-11-04T13:40:33.544Z" }, + { url = "https://files.pythonhosted.org/packages/c9/d4/2230d7151d4957dd79c3044ea26346c148c98fbf0ee6ebd41056f2d62ab5/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dc799088c08fa04e43144b164feb0c13f9a0bc40503f8df3e9fde58a3c0c101e", size = 2214917, upload-time = "2025-11-04T13:40:35.479Z" }, + { url = "https://files.pythonhosted.org/packages/e6/9f/eaac5df17a3672fef0081b6c1bb0b82b33ee89aa5cec0d7b05f52fd4a1fa/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:97aeba56665b4c3235a0e52b2c2f5ae9cd071b8a8310ad27bddb3f7fb30e9aa2", size = 2332186, upload-time = "2025-11-04T13:40:37.436Z" }, + { url = "https://files.pythonhosted.org/packages/cf/4e/35a80cae583a37cf15604b44240e45c05e04e86f9cfd766623149297e971/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:406bf18d345822d6c21366031003612b9c77b3e29ffdb0f612367352aab7d586", size = 2073164, upload-time = "2025-11-04T13:40:40.289Z" }, + { url = "https://files.pythonhosted.org/packages/bf/e3/f6e262673c6140dd3305d144d032f7bd5f7497d3871c1428521f19f9efa2/pydantic_core-2.41.5-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b93590ae81f7010dbe380cdeab6f515902ebcbefe0b9327cc4804d74e93ae69d", size = 2179146, upload-time = "2025-11-04T13:40:42.809Z" }, + { url = "https://files.pythonhosted.org/packages/75/c7/20bd7fc05f0c6ea2056a4565c6f36f8968c0924f19b7d97bbfea55780e73/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:01a3d0ab748ee531f4ea6c3e48ad9dac84ddba4b0d82291f87248f2f9de8d740", size = 2137788, upload-time = "2025-11-04T13:40:44.752Z" }, + { url = "https://files.pythonhosted.org/packages/3a/8d/34318ef985c45196e004bc46c6eab2eda437e744c124ef0dbe1ff2c9d06b/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:6561e94ba9dacc9c61bce40e2d6bdc3bfaa0259d3ff36ace3b1e6901936d2e3e", size = 2340133, upload-time = "2025-11-04T13:40:46.66Z" }, + { url = "https://files.pythonhosted.org/packages/9c/59/013626bf8c78a5a5d9350d12e7697d3d4de951a75565496abd40ccd46bee/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:915c3d10f81bec3a74fbd4faebe8391013ba61e5a1a8d48c4455b923bdda7858", size = 2324852, upload-time = "2025-11-04T13:40:48.575Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d9/c248c103856f807ef70c18a4f986693a46a8ffe1602e5d361485da502d20/pydantic_core-2.41.5-cp313-cp313-win32.whl", hash = "sha256:650ae77860b45cfa6e2cdafc42618ceafab3a2d9a3811fcfbd3bbf8ac3c40d36", size = 1994679, upload-time = "2025-11-04T13:40:50.619Z" }, + { url = "https://files.pythonhosted.org/packages/9e/8b/341991b158ddab181cff136acd2552c9f35bd30380422a639c0671e99a91/pydantic_core-2.41.5-cp313-cp313-win_amd64.whl", hash = "sha256:79ec52ec461e99e13791ec6508c722742ad745571f234ea6255bed38c6480f11", size = 2019766, upload-time = "2025-11-04T13:40:52.631Z" }, + { url = "https://files.pythonhosted.org/packages/73/7d/f2f9db34af103bea3e09735bb40b021788a5e834c81eedb541991badf8f5/pydantic_core-2.41.5-cp313-cp313-win_arm64.whl", hash = "sha256:3f84d5c1b4ab906093bdc1ff10484838aca54ef08de4afa9de0f5f14d69639cd", size = 1981005, upload-time = "2025-11-04T13:40:54.734Z" }, + { url = "https://files.pythonhosted.org/packages/ea/28/46b7c5c9635ae96ea0fbb779e271a38129df2550f763937659ee6c5dbc65/pydantic_core-2.41.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:3f37a19d7ebcdd20b96485056ba9e8b304e27d9904d233d7b1015db320e51f0a", size = 2119622, upload-time = "2025-11-04T13:40:56.68Z" }, + { url = "https://files.pythonhosted.org/packages/74/1a/145646e5687e8d9a1e8d09acb278c8535ebe9e972e1f162ed338a622f193/pydantic_core-2.41.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1d1d9764366c73f996edd17abb6d9d7649a7eb690006ab6adbda117717099b14", size = 1891725, upload-time = "2025-11-04T13:40:58.807Z" }, + { url = "https://files.pythonhosted.org/packages/23/04/e89c29e267b8060b40dca97bfc64a19b2a3cf99018167ea1677d96368273/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25e1c2af0fce638d5f1988b686f3b3ea8cd7de5f244ca147c777769e798a9cd1", size = 1915040, upload-time = "2025-11-04T13:41:00.853Z" }, + { url = "https://files.pythonhosted.org/packages/84/a3/15a82ac7bd97992a82257f777b3583d3e84bdb06ba6858f745daa2ec8a85/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:506d766a8727beef16b7adaeb8ee6217c64fc813646b424d0804d67c16eddb66", size = 2063691, upload-time = "2025-11-04T13:41:03.504Z" }, + { url = "https://files.pythonhosted.org/packages/74/9b/0046701313c6ef08c0c1cf0e028c67c770a4e1275ca73131563c5f2a310a/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4819fa52133c9aa3c387b3328f25c1facc356491e6135b459f1de698ff64d869", size = 2213897, upload-time = "2025-11-04T13:41:05.804Z" }, + { url = "https://files.pythonhosted.org/packages/8a/cd/6bac76ecd1b27e75a95ca3a9a559c643b3afcd2dd62086d4b7a32a18b169/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2b761d210c9ea91feda40d25b4efe82a1707da2ef62901466a42492c028553a2", size = 2333302, upload-time = "2025-11-04T13:41:07.809Z" }, + { url = "https://files.pythonhosted.org/packages/4c/d2/ef2074dc020dd6e109611a8be4449b98cd25e1b9b8a303c2f0fca2f2bcf7/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:22f0fb8c1c583a3b6f24df2470833b40207e907b90c928cc8d3594b76f874375", size = 2064877, upload-time = "2025-11-04T13:41:09.827Z" }, + { url = "https://files.pythonhosted.org/packages/18/66/e9db17a9a763d72f03de903883c057b2592c09509ccfe468187f2a2eef29/pydantic_core-2.41.5-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2782c870e99878c634505236d81e5443092fba820f0373997ff75f90f68cd553", size = 2180680, upload-time = "2025-11-04T13:41:12.379Z" }, + { url = "https://files.pythonhosted.org/packages/d3/9e/3ce66cebb929f3ced22be85d4c2399b8e85b622db77dad36b73c5387f8f8/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:0177272f88ab8312479336e1d777f6b124537d47f2123f89cb37e0accea97f90", size = 2138960, upload-time = "2025-11-04T13:41:14.627Z" }, + { url = "https://files.pythonhosted.org/packages/a6/62/205a998f4327d2079326b01abee48e502ea739d174f0a89295c481a2272e/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:63510af5e38f8955b8ee5687740d6ebf7c2a0886d15a6d65c32814613681bc07", size = 2339102, upload-time = "2025-11-04T13:41:16.868Z" }, + { url = "https://files.pythonhosted.org/packages/3c/0d/f05e79471e889d74d3d88f5bd20d0ed189ad94c2423d81ff8d0000aab4ff/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:e56ba91f47764cc14f1daacd723e3e82d1a89d783f0f5afe9c364b8bb491ccdb", size = 2326039, upload-time = "2025-11-04T13:41:18.934Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e1/e08a6208bb100da7e0c4b288eed624a703f4d129bde2da475721a80cab32/pydantic_core-2.41.5-cp314-cp314-win32.whl", hash = "sha256:aec5cf2fd867b4ff45b9959f8b20ea3993fc93e63c7363fe6851424c8a7e7c23", size = 1995126, upload-time = "2025-11-04T13:41:21.418Z" }, + { url = "https://files.pythonhosted.org/packages/48/5d/56ba7b24e9557f99c9237e29f5c09913c81eeb2f3217e40e922353668092/pydantic_core-2.41.5-cp314-cp314-win_amd64.whl", hash = "sha256:8e7c86f27c585ef37c35e56a96363ab8de4e549a95512445b85c96d3e2f7c1bf", size = 2015489, upload-time = "2025-11-04T13:41:24.076Z" }, + { url = "https://files.pythonhosted.org/packages/4e/bb/f7a190991ec9e3e0ba22e4993d8755bbc4a32925c0b5b42775c03e8148f9/pydantic_core-2.41.5-cp314-cp314-win_arm64.whl", hash = "sha256:e672ba74fbc2dc8eea59fb6d4aed6845e6905fc2a8afe93175d94a83ba2a01a0", size = 1977288, upload-time = "2025-11-04T13:41:26.33Z" }, + { url = "https://files.pythonhosted.org/packages/92/ed/77542d0c51538e32e15afe7899d79efce4b81eee631d99850edc2f5e9349/pydantic_core-2.41.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8566def80554c3faa0e65ac30ab0932b9e3a5cd7f8323764303d468e5c37595a", size = 2120255, upload-time = "2025-11-04T13:41:28.569Z" }, + { url = "https://files.pythonhosted.org/packages/bb/3d/6913dde84d5be21e284439676168b28d8bbba5600d838b9dca99de0fad71/pydantic_core-2.41.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b80aa5095cd3109962a298ce14110ae16b8c1aece8b72f9dafe81cf597ad80b3", size = 1863760, upload-time = "2025-11-04T13:41:31.055Z" }, + { url = "https://files.pythonhosted.org/packages/5a/f0/e5e6b99d4191da102f2b0eb9687aaa7f5bea5d9964071a84effc3e40f997/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3006c3dd9ba34b0c094c544c6006cc79e87d8612999f1a5d43b769b89181f23c", size = 1878092, upload-time = "2025-11-04T13:41:33.21Z" }, + { url = "https://files.pythonhosted.org/packages/71/48/36fb760642d568925953bcc8116455513d6e34c4beaa37544118c36aba6d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:72f6c8b11857a856bcfa48c86f5368439f74453563f951e473514579d44aa612", size = 2053385, upload-time = "2025-11-04T13:41:35.508Z" }, + { url = "https://files.pythonhosted.org/packages/20/25/92dc684dd8eb75a234bc1c764b4210cf2646479d54b47bf46061657292a8/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5cb1b2f9742240e4bb26b652a5aeb840aa4b417c7748b6f8387927bc6e45e40d", size = 2218832, upload-time = "2025-11-04T13:41:37.732Z" }, + { url = "https://files.pythonhosted.org/packages/e2/09/f53e0b05023d3e30357d82eb35835d0f6340ca344720a4599cd663dca599/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bd3d54f38609ff308209bd43acea66061494157703364ae40c951f83ba99a1a9", size = 2327585, upload-time = "2025-11-04T13:41:40Z" }, + { url = "https://files.pythonhosted.org/packages/aa/4e/2ae1aa85d6af35a39b236b1b1641de73f5a6ac4d5a7509f77b814885760c/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2ff4321e56e879ee8d2a879501c8e469414d948f4aba74a2d4593184eb326660", size = 2041078, upload-time = "2025-11-04T13:41:42.323Z" }, + { url = "https://files.pythonhosted.org/packages/cd/13/2e215f17f0ef326fc72afe94776edb77525142c693767fc347ed6288728d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d0d2568a8c11bf8225044aa94409e21da0cb09dcdafe9ecd10250b2baad531a9", size = 2173914, upload-time = "2025-11-04T13:41:45.221Z" }, + { url = "https://files.pythonhosted.org/packages/02/7a/f999a6dcbcd0e5660bc348a3991c8915ce6599f4f2c6ac22f01d7a10816c/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:a39455728aabd58ceabb03c90e12f71fd30fa69615760a075b9fec596456ccc3", size = 2129560, upload-time = "2025-11-04T13:41:47.474Z" }, + { url = "https://files.pythonhosted.org/packages/3a/b1/6c990ac65e3b4c079a4fb9f5b05f5b013afa0f4ed6780a3dd236d2cbdc64/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:239edca560d05757817c13dc17c50766136d21f7cd0fac50295499ae24f90fdf", size = 2329244, upload-time = "2025-11-04T13:41:49.992Z" }, + { url = "https://files.pythonhosted.org/packages/d9/02/3c562f3a51afd4d88fff8dffb1771b30cfdfd79befd9883ee094f5b6c0d8/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:2a5e06546e19f24c6a96a129142a75cee553cc018ffee48a460059b1185f4470", size = 2331955, upload-time = "2025-11-04T13:41:54.079Z" }, + { url = "https://files.pythonhosted.org/packages/5c/96/5fb7d8c3c17bc8c62fdb031c47d77a1af698f1d7a406b0f79aaa1338f9ad/pydantic_core-2.41.5-cp314-cp314t-win32.whl", hash = "sha256:b4ececa40ac28afa90871c2cc2b9ffd2ff0bf749380fbdf57d165fd23da353aa", size = 1988906, upload-time = "2025-11-04T13:41:56.606Z" }, + { url = "https://files.pythonhosted.org/packages/22/ed/182129d83032702912c2e2d8bbe33c036f342cc735737064668585dac28f/pydantic_core-2.41.5-cp314-cp314t-win_amd64.whl", hash = "sha256:80aa89cad80b32a912a65332f64a4450ed00966111b6615ca6816153d3585a8c", size = 1981607, upload-time = "2025-11-04T13:41:58.889Z" }, + { url = "https://files.pythonhosted.org/packages/9f/ed/068e41660b832bb0b1aa5b58011dea2a3fe0ba7861ff38c4d4904c1c1a99/pydantic_core-2.41.5-cp314-cp314t-win_arm64.whl", hash = "sha256:35b44f37a3199f771c3eaa53051bc8a70cd7b54f333531c59e29fd4db5d15008", size = 1974769, upload-time = "2025-11-04T13:42:01.186Z" }, + { url = "https://files.pythonhosted.org/packages/09/32/59b0c7e63e277fa7911c2fc70ccfb45ce4b98991e7ef37110663437005af/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:7da7087d756b19037bc2c06edc6c170eeef3c3bafcb8f532ff17d64dc427adfd", size = 2110495, upload-time = "2025-11-04T13:42:49.689Z" }, + { url = "https://files.pythonhosted.org/packages/aa/81/05e400037eaf55ad400bcd318c05bb345b57e708887f07ddb2d20e3f0e98/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:aabf5777b5c8ca26f7824cb4a120a740c9588ed58df9b2d196ce92fba42ff8dc", size = 1915388, upload-time = "2025-11-04T13:42:52.215Z" }, + { url = "https://files.pythonhosted.org/packages/6e/0d/e3549b2399f71d56476b77dbf3cf8937cec5cd70536bdc0e374a421d0599/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c007fe8a43d43b3969e8469004e9845944f1a80e6acd47c150856bb87f230c56", size = 1942879, upload-time = "2025-11-04T13:42:56.483Z" }, + { url = "https://files.pythonhosted.org/packages/f7/07/34573da085946b6a313d7c42f82f16e8920bfd730665de2d11c0c37a74b5/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76d0819de158cd855d1cbb8fcafdf6f5cf1eb8e470abe056d5d161106e38062b", size = 2139017, upload-time = "2025-11-04T13:42:59.471Z" }, +] + +[[package]] +name = "pydantic-settings" +version = "2.14.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "python-dotenv" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5c/b5/8f48e906c3e0205276e8bd8cb7512217a87b2685304d64be27cad5b3019f/pydantic_settings-2.14.2.tar.gz", hash = "sha256:c19dd64b19097f1de80184f0cc7b0272a13ae6e170cbf240a3e27e381ed14a5f", size = 237700, upload-time = "2026-06-19T13:44:56.324Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/c1/6e422f34e569cf8e18df68d1939c81c099d2b61e4f7d9621c8a77560799c/pydantic_settings-2.14.2-py3-none-any.whl", hash = "sha256:a20c97b37910b6550d5ea50fbcc2d4187defe58cd57070b73863d069419c9440", size = 61715, upload-time = "2026-06-19T13:44:55.02Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[package]] +name = "pygments-ansi-color" +version = "0.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/50/f9/7f417aaee98a74b4f757f2b72971245181fcf25d824d2e7a190345669eaf/pygments-ansi-color-0.3.0.tar.gz", hash = "sha256:7018954cf5b11d1e734383a1bafab5af613213f246109417fee3f76da26d5431", size = 7317, upload-time = "2023-05-18T22:44:35.792Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/17/8306a0bcd8c88d7761c2e73e831b0be026cd6873ce1f12beb3b4c9a03ffa/pygments_ansi_color-0.3.0-py3-none-any.whl", hash = "sha256:7eb063feaecadad9d4d1fd3474cbfeadf3486b64f760a8f2a00fc25392180aba", size = 10242, upload-time = "2023-05-18T22:44:34.287Z" }, +] + +[[package]] +name = "pymdown-extensions" +version = "11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/47/67/f1e79672a5f91985577c7984c9709ca110e4fd37fe7fd167b60422e6ccc2/pymdown_extensions-11.0.tar.gz", hash = "sha256:8269cef0247f9e2d0a62fcea10860aba05c1cbab5470fd4b63230b96434dc589", size = 857049, upload-time = "2026-06-23T02:27:45.146Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/b6/1ae53367e28b9cffa3be7574e13fbe4589694272fd47710fbdbafd3d63c6/pymdown_extensions-11.0-py3-none-any.whl", hash = "sha256:fbc4acb641814fa9d17521bbd21a5240ef739a662f11c06330c4b78c93e954d6", size = 269415, upload-time = "2026-06-23T02:27:43.826Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +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/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "pytest-accept" +version = "0.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "astor" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/42/573e6dcd8d1a5fc779d525268d5036f710d018cdeefbae2bd5559687a6d5/pytest_accept-0.3.0.tar.gz", hash = "sha256:6f4e03e2492621e10b7678a331828274498cca04686b15b0f3e704e16e651068", size = 29744, upload-time = "2026-06-11T18:44:39.03Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/06/40/79f6f13e616f580b9c35110376818c76cacc54b70d2965bf1f82be336c66/pytest_accept-0.3.0-py3-none-any.whl", hash = "sha256:5e73f27020853b861a63dc630dfe63124af4bd60e0e0bb692e1376b99798f2b5", size = 39846, upload-time = "2026-06-11T18:44:37.965Z" }, +] + +[[package]] +name = "pytest-asyncio" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, +] + +[[package]] +name = "pytest-benchmark" +version = "5.2.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "py-cpuinfo" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/24/34/9f732b76456d64faffbef6232f1f9dbec7a7c4999ff46282fa418bd1af66/pytest_benchmark-5.2.3.tar.gz", hash = "sha256:deb7317998a23c650fd4ff76e1230066a76cb45dcece0aca5607143c619e7779", size = 341340, upload-time = "2025-11-09T18:48:43.215Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/29/e756e715a48959f1c0045342088d7ca9762a2f509b945f362a316e9412b7/pytest_benchmark-5.2.3-py3-none-any.whl", hash = "sha256:bc839726ad20e99aaa0d11a127445457b4219bdb9e80a1afc4b51da7f96b0803", size = 45255, upload-time = "2025-11-09T18:48:39.765Z" }, +] + +[[package]] +name = "pytest-codspeed" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, + { name = "rich" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e1/b4/cf932fcd1960a2fd6d9b09eb403253a8709aeee975961afa6299239a830e/pytest_codspeed-5.0.3.tar.gz", hash = "sha256:91afef90e6a96b013495e4702ef5d6358614a449e71008cdc194ef668778b92f", size = 324571, upload-time = "2026-05-22T16:20:49.231Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/22/456c48160b761d5028c8afa119f085a9fc42855a783a13d73918078969f0/pytest_codspeed-5.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2eeb25fb1ac3f73c4de50e739e78fea396b89782bdb740bf2a7cd2df21f8d4ee", size = 366255, upload-time = "2026-05-22T16:20:56.214Z" }, + { url = "https://files.pythonhosted.org/packages/74/33/ac7441fa937c9d9f158083a8c46920a5a5c81ed3c5f96240fc8d650db5c2/pytest_codspeed-5.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:73c5c9d98a3372a42611989ccfa437cce3842431ac6d6b9ab42c4f0e59c070f7", size = 932325, upload-time = "2026-05-22T16:21:08.814Z" }, + { url = "https://files.pythonhosted.org/packages/77/bc/8b994adcb9e9016e7d9a808056a3dd9cca21441e432ef456eae2b697d7fe/pytest_codspeed-5.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a2e0ab65df73e837666d12357280ca50ff6d6ac03ea5266703be518b68170edf", size = 934885, upload-time = "2026-05-22T16:21:01.444Z" }, + { url = "https://files.pythonhosted.org/packages/dc/8e/e032451e9e0a06b0c4bff53105f62b693d9a54595dd8c024693741ce3380/pytest_codspeed-5.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6524c57fec279a22ffef6112af404036afc71b4704758ae9f0abda429b8478d4", size = 366253, upload-time = "2026-05-22T16:20:46.192Z" }, + { url = "https://files.pythonhosted.org/packages/a9/7b/ae76fd8ac656b9695806a6aafd5f22ec32e6ce20e266a58f9112e01d3cd8/pytest_codspeed-5.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c383c9121deb58a69f174188e9e4488ffc0daced0ed276abf87747182511901", size = 932360, upload-time = "2026-05-22T16:20:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/a6/4a/dfd43d943fdb143be4fd62f34c2793ba349dc27aa188e521d19d629aa7ab/pytest_codspeed-5.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a4bcdb4b6522738152885ef067e0c8524d5699828d780fb6f464cdb3db44369c", size = 934928, upload-time = "2026-05-22T16:20:38.62Z" }, + { url = "https://files.pythonhosted.org/packages/04/6a/fdcec19c7f267c195f147c51d3fd2245f6b8d09b80495ed0a90c008e0842/pytest_codspeed-5.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:25464363c7f9b9bd5022e969c0addba616fa40ac9b8f0fc9e030c4538863b32d", size = 366259, upload-time = "2026-05-22T16:21:06.039Z" }, + { url = "https://files.pythonhosted.org/packages/6a/96/c6b03b81dcd21ae3d6b32cca0b3c10149fa378eb21b338d4b63c9eb8050b/pytest_codspeed-5.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:efd43f82ea03ced8488a767ded9473f050791ab7783ea8654107e1e0ac66af40", size = 932395, upload-time = "2026-05-22T16:21:04.804Z" }, + { url = "https://files.pythonhosted.org/packages/96/08/56ad8f1cc7d6962f8a680141b361e93467a2abc53d976cd9d5e1edd740e3/pytest_codspeed-5.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:782f9985b6f6b45b8bc20152d206d3a52b56dd088ba81cb70a71f0b39841be9e", size = 934994, upload-time = "2026-05-22T16:20:28.809Z" }, + { url = "https://files.pythonhosted.org/packages/0b/54/9096c4545f09da94b1b00f3be2fe4952949e86c9bcafca9a29b26aed1a75/pytest_codspeed-5.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:9aa0815b90196f3c20d736ea8691381e97f12bbe8c7d87af10a351e434b452cb", size = 366311, upload-time = "2026-05-22T16:20:41.791Z" }, + { url = "https://files.pythonhosted.org/packages/a7/3c/24c53f67a38ad48cb087105ac30a8aa0923223ee274ea9bf2dc705edaa59/pytest_codspeed-5.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:85505c96a3477c346ec2d2b7dced8478f4c651e2b1666ee102d53a832b511853", size = 933169, upload-time = "2026-05-22T16:20:43.178Z" }, + { url = "https://files.pythonhosted.org/packages/d1/de/2213f868fa7694f743f96cccbc07e757f45c920c523cccc2da97bc8652df/pytest_codspeed-5.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:20eba63765be9d1b6cacbbfad84b87d49eb04b357a7045a0899880da181f81e3", size = 935522, upload-time = "2026-05-22T16:21:03.398Z" }, + { url = "https://files.pythonhosted.org/packages/df/85/5dfea1c031d6cccc11653464828edf205c30f798caf5b2a85375aacd914a/pytest_codspeed-5.0.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:ec9fa6f0af0a9feb0e0bd517fb59ef28f806fbd50c0c6900ac26cbb4d080eba5", size = 366275, upload-time = "2026-05-22T16:20:59.463Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2b/af4d1b612f03b98a6cf3c7d5f62678917a60110a8bf380d49ab408b31137/pytest_codspeed-5.0.3-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8df77b3409f54f4a268f77f3ff74992fe1d995cdbaf2cecf8ad74d32db217ce7", size = 932537, upload-time = "2026-05-22T16:20:54.945Z" }, + { url = "https://files.pythonhosted.org/packages/f5/a2/c7ec45e36a61b418efb2a3cccaa67a0c2fcf1f21d5880f64c33114f0c249/pytest_codspeed-5.0.3-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5d8695a227ea1c3a41d25db5b3fe720bf1b4808bd38862be811a4efd902c792", size = 934153, upload-time = "2026-05-22T16:21:07.494Z" }, + { url = "https://files.pythonhosted.org/packages/cf/c7/d5bada9618a0af56a5c8065fc61280849cab8e7c1e24025807a51c3157ce/pytest_codspeed-5.0.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bf4cc4178cbace8f4d2bd240408276bc4da3850ac5fcb5fb5f8a74ab417615bb", size = 366339, upload-time = "2026-05-22T16:20:51.968Z" }, + { url = "https://files.pythonhosted.org/packages/a8/37/fb27aeb40a81320e7349553b877a21333c897b27c8dfe215630452908f36/pytest_codspeed-5.0.3-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:abe793da40f87295d33988673d34f06ea569848b44490b847552cd416816258a", size = 933055, upload-time = "2026-05-22T16:20:44.861Z" }, + { url = "https://files.pythonhosted.org/packages/f3/d9/6f2d69e96deaf0475a695fc9195af59e7a3b5fab50782855e65c63a7bc28/pytest_codspeed-5.0.3-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c3a9ed38dfa776443b86f4b49a982e8443d0953db4974bd2673d63cc904ae1ad", size = 934481, upload-time = "2026-05-22T16:20:58.264Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b2/1d2a993c532146dce9eca5b5942d51898021c3579ce18b2454f932a915f8/pytest_codspeed-5.0.3-py3-none-any.whl", hash = "sha256:fe2ea83c924c2250675b75686c3ee456b8cf0208d83d552e182a195fdf467378", size = 74033, upload-time = "2026-05-22T16:20:26.814Z" }, +] + +[[package]] +name = "pytest-cov" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "coverage" }, + { name = "pluggy" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/51/a849f96e117386044471c8ec2bd6cfebacda285da9525c9106aeb28da671/pytest_cov-7.1.0.tar.gz", hash = "sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2", size = 55592, upload-time = "2026-03-21T20:11:16.284Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, +] + +[[package]] +name = "pytest-reportlog" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/93/d5/2f4a73822efaad1d6aea6660468d6290963e5f61d2f9d9ca707f7f0b1c13/pytest_reportlog-1.0.0.tar.gz", hash = "sha256:75aec3a92bb53456c3e028605a636579d26f31c6f1e035ad9f706c203cfcb74e", size = 5646, upload-time = "2025-11-11T16:05:15.98Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/70/807cbdac584629623c1c2f76b7a39a343e3989510cd52385f1f40581e963/pytest_reportlog-1.0.0-py3-none-any.whl", hash = "sha256:3fc837ef3be6e50f33b52aaf99f88bfbb2ec525febbc3990389d24bbfba28753", size = 6015, upload-time = "2025-11-11T16:05:14.585Z" }, +] + +[[package]] +name = "pytest-xdist" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "execnet" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "python-dotenv" +version = "1.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/ed/0301aeeac3e5353ef3d94b6ec08bbcabd04a72018415dcb29e588514bba8/python_dotenv-1.2.2.tar.gz", hash = "sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3", size = 50135, upload-time = "2026-03-01T16:00:26.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl", hash = "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", size = 22101, upload-time = "2026-03-01T16:00:25.09Z" }, +] + +[[package]] +name = "pywin32" +version = "311" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/ab/01ea1943d4eba0f850c3c61e78e8dd59757ff815ff3ccd0a84de5f541f42/pywin32-311-cp312-cp312-win32.whl", hash = "sha256:750ec6e621af2b948540032557b10a2d43b0cee2ae9758c54154d711cc852d31", size = 8706543, upload-time = "2025-07-14T20:13:20.765Z" }, + { url = "https://files.pythonhosted.org/packages/d1/a8/a0e8d07d4d051ec7502cd58b291ec98dcc0c3fff027caad0470b72cfcc2f/pywin32-311-cp312-cp312-win_amd64.whl", hash = "sha256:b8c095edad5c211ff31c05223658e71bf7116daa0ecf3ad85f3201ea3190d067", size = 9495040, upload-time = "2025-07-14T20:13:22.543Z" }, + { url = "https://files.pythonhosted.org/packages/ba/3a/2ae996277b4b50f17d61f0603efd8253cb2d79cc7ae159468007b586396d/pywin32-311-cp312-cp312-win_arm64.whl", hash = "sha256:e286f46a9a39c4a18b319c28f59b61de793654af2f395c102b4f819e584b5852", size = 8710102, upload-time = "2025-07-14T20:13:24.682Z" }, + { url = "https://files.pythonhosted.org/packages/a5/be/3fd5de0979fcb3994bfee0d65ed8ca9506a8a1260651b86174f6a86f52b3/pywin32-311-cp313-cp313-win32.whl", hash = "sha256:f95ba5a847cba10dd8c4d8fefa9f2a6cf283b8b88ed6178fa8a6c1ab16054d0d", size = 8705700, upload-time = "2025-07-14T20:13:26.471Z" }, + { url = "https://files.pythonhosted.org/packages/e3/28/e0a1909523c6890208295a29e05c2adb2126364e289826c0a8bc7297bd5c/pywin32-311-cp313-cp313-win_amd64.whl", hash = "sha256:718a38f7e5b058e76aee1c56ddd06908116d35147e133427e59a3983f703a20d", size = 9494700, upload-time = "2025-07-14T20:13:28.243Z" }, + { url = "https://files.pythonhosted.org/packages/04/bf/90339ac0f55726dce7d794e6d79a18a91265bdf3aa70b6b9ca52f35e022a/pywin32-311-cp313-cp313-win_arm64.whl", hash = "sha256:7b4075d959648406202d92a2310cb990fea19b535c7f4a78d3f5e10b926eeb8a", size = 8709318, upload-time = "2025-07-14T20:13:30.348Z" }, + { url = "https://files.pythonhosted.org/packages/c9/31/097f2e132c4f16d99a22bfb777e0fd88bd8e1c634304e102f313af69ace5/pywin32-311-cp314-cp314-win32.whl", hash = "sha256:b7a2c10b93f8986666d0c803ee19b5990885872a7de910fc460f9b0c2fbf92ee", size = 8840714, upload-time = "2025-07-14T20:13:32.449Z" }, + { url = "https://files.pythonhosted.org/packages/90/4b/07c77d8ba0e01349358082713400435347df8426208171ce297da32c313d/pywin32-311-cp314-cp314-win_amd64.whl", hash = "sha256:3aca44c046bd2ed8c90de9cb8427f581c479e594e99b5c0bb19b29c10fd6cb87", size = 9656800, upload-time = "2025-07-14T20:13:34.312Z" }, + { url = "https://files.pythonhosted.org/packages/c0/d2/21af5c535501a7233e734b8af901574572da66fcc254cb35d0609c9080dd/pywin32-311-cp314-cp314-win_arm64.whl", hash = "sha256:a508e2d9025764a8270f93111a970e1d0fbfc33f4153b388bb649b7eec4f9b42", size = 8932540, upload-time = "2025-07-14T20:13:36.379Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[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 = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + +[[package]] +name = "regex" +version = "2026.5.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/0e/49aee608ad09480e7fd276898c99ec6192985fa331abe4eb3a986094490b/regex-2026.5.9.tar.gz", hash = "sha256:a8234aa23ec39894bfe4a3f1b85616a7032481964a13ac6fc9f10de4f6fca270", size = 416074, upload-time = "2026-05-09T23:15:19.37Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/50/9b/6550044bc44e17c84d312c031c2ec42fbdb6a4ec4e29093be3a172d08772/regex-2026.5.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:57eeeb05db7979413dec5438f2db21d7ecbba787cde7a711df1a6f6df672aa06", size = 490451, upload-time = "2026-05-09T23:12:34.72Z" }, + { url = "https://files.pythonhosted.org/packages/1e/95/fc7ba4303b5a0f92446a12ee6778ef2c6c799233f5060042a31bf390cfe9/regex-2026.5.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:398c521292f4c7fb807001dcd54694d3a1fcafc179a36ad9cc56f98df85930b6", size = 292112, upload-time = "2026-05-09T23:12:36.285Z" }, + { url = "https://files.pythonhosted.org/packages/54/4b/ee27938d1b2c443e89a9a10e00d2d19aa5ee300cd3d61140644e93bb083e/regex-2026.5.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f7a7c26137296beba7784de6eba69c6a93a63ccebc385e4962fe67e267a91225", size = 289599, upload-time = "2026-05-09T23:12:38.089Z" }, + { url = "https://files.pythonhosted.org/packages/d8/dd/ba103dc19614e25f3880800ca67ce093d6e21b325d72b8383c7bf906e9fa/regex-2026.5.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6441cc660d76107934a09c22167200839a0e89604a6297f78a974e66e931d2c0", size = 796732, upload-time = "2026-05-09T23:12:40.062Z" }, + { url = "https://files.pythonhosted.org/packages/cf/e7/f035b4fd858b050b0080bf302968dc0f59ba34e391872d54936758e6844e/regex-2026.5.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:91328f1c23d47595ca3ef0a7557fa129c5a23404b775c770697d2f35b33e0107", size = 865440, upload-time = "2026-05-09T23:12:42.059Z" }, + { url = "https://files.pythonhosted.org/packages/0a/51/8cd301ecc899aea28124357f729f4272f44de7806fc7ca02490bfbe253e8/regex-2026.5.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:93a7860539414dddaefba2b40f8771765ae17949d4c7182b876ce429e11a8309", size = 912329, upload-time = "2026-05-09T23:12:44.373Z" }, + { url = "https://files.pythonhosted.org/packages/cc/1e/3fbe2fa1e8cebd62f3bb7d3321cff1640aca2e240b51d9bd624aad949260/regex-2026.5.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dd2810d22146b6d838acc5ec15602cb6b47920aa4e33015df3868eedfd20bab8", size = 801239, upload-time = "2026-05-09T23:12:46.268Z" }, + { url = "https://files.pythonhosted.org/packages/17/2f/6f6008682bf2cf98040a0d3153a8e557b6ab728d7713d045cee4ce544ab8/regex-2026.5.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:daff2bdbaf1d23e52fdff7c0b7bc2048b68f978df6a4d107ac981f94caef2e66", size = 777054, upload-time = "2026-05-09T23:12:48.051Z" }, + { url = "https://files.pythonhosted.org/packages/19/2b/eee0d20a6842ba04df4b8847a920b57ef56853f14ef85405473e586b605a/regex-2026.5.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4eeb011098fcb77af513dcef521a3dbecbf8849b1e38940759d293b7a93f5026", size = 785098, upload-time = "2026-05-09T23:12:49.851Z" }, + { url = "https://files.pythonhosted.org/packages/4a/98/6fc1e6410feefb92159edaed5041992bfe390e8d26c721865434acbca558/regex-2026.5.9-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ea9c8ecfa1b73c73b626534d6626e5340d429630943672b8480724f44e84b962", size = 860095, upload-time = "2026-05-09T23:12:51.666Z" }, + { url = "https://files.pythonhosted.org/packages/18/a3/bd855e0f2cb1a978ecf6fa6bb69632dd9c3f6ea3b81cde62fde14c9daec7/regex-2026.5.9-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:cd2846168eb9ee3c513902bc8225409cb1caab31d04728b145171fa1625d9621", size = 765762, upload-time = "2026-05-09T23:12:53.413Z" }, + { url = "https://files.pythonhosted.org/packages/dc/66/0ae8c092e60b14c79d24f8e0b7f0aea5bfbffdcab00b5483d13404d3c3a5/regex-2026.5.9-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:39617fb0cde9c0e6306dc70e3bfc096f3da793219879f7ae7aa341a69fbdcf6d", size = 852100, upload-time = "2026-05-09T23:12:55.256Z" }, + { url = "https://files.pythonhosted.org/packages/21/de/8dfde60fc1b21c946a893ba273403b72617edb261370cb1087099a83f088/regex-2026.5.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fd03c4f0e33280d15cae17159b899245d6b7c53d21def19b263b39655061f5ce", size = 789479, upload-time = "2026-05-09T23:12:57.573Z" }, + { url = "https://files.pythonhosted.org/packages/c3/1c/bdcc98f9a4af4fdd166c74941174619ccff4726d3ce32faa8e9a2ecd38dd/regex-2026.5.9-cp312-cp312-win32.whl", hash = "sha256:164eba9b755ea6f244b0d881196fbc1fac09714e9782c9e2732b813142033c8e", size = 266699, upload-time = "2026-05-09T23:12:59.14Z" }, + { url = "https://files.pythonhosted.org/packages/78/87/240d36864f9e48ace85f72e79ced97ceb7f27ce87739a947dcb834b4e6bc/regex-2026.5.9-cp312-cp312-win_amd64.whl", hash = "sha256:86f40a5d6444db30a125c9c9177e6b25dad981cbc37451fd838f145e6edac92e", size = 277783, upload-time = "2026-05-09T23:13:00.789Z" }, + { url = "https://files.pythonhosted.org/packages/4f/b5/7b30f312b0669dff5beebe5b0989dc2d1a312b1a44fab852199c387a5b96/regex-2026.5.9-cp312-cp312-win_arm64.whl", hash = "sha256:96f5f58b54a063d7ea9dca08e1cf57bfe10499c4d579ee672da284f57f5f0070", size = 270513, upload-time = "2026-05-09T23:13:02.426Z" }, + { url = "https://files.pythonhosted.org/packages/aa/da/797e91ecec6f84135da778ddce78c20e0af5d2a15c26f87a81bc3eadb6db/regex-2026.5.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:d626b84406444b165fc0ba981604edea39f0588ff1f92baa23fe50799ea9afdb", size = 490303, upload-time = "2026-05-09T23:13:04.382Z" }, + { url = "https://files.pythonhosted.org/packages/44/da/bf30abaaa737b58f4a4b8c4a03659e02fd92092c822e0197ed9e0daab917/regex-2026.5.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d7bdc0ab8f3dd7e1b4f9ab88634e13374669db86bb3c72e8292f07ae313f539f", size = 292019, upload-time = "2026-05-09T23:13:06.022Z" }, + { url = "https://files.pythonhosted.org/packages/2d/e7/d0eaf5713828417b9e5648cf81fa9bacd4961f6ab98c380c2034f8716e35/regex-2026.5.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a8820737949116ffff55fe18f9fc644530063ba6ebfcb8314239416e78f1347c", size = 289468, upload-time = "2026-05-09T23:13:08.214Z" }, + { url = "https://files.pythonhosted.org/packages/d3/9b/b3fdd62b003baa1a9b593cd8c8699c9651c2e80cc21a5c715707983c42d7/regex-2026.5.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aa0fbdbac82cb3e4450d0ccde7d7a35607f4cb2dd9fba4b8b69bfaf8c9fa6aed", size = 796749, upload-time = "2026-05-09T23:13:10.573Z" }, + { url = "https://files.pythonhosted.org/packages/d4/30/66ab84588765f5b4b271a9ca09ef7ce2b87caa95176ec3d2ad65d7bc4902/regex-2026.5.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:57e8915c7986aa33d25e4d3629cef711cd2863f2961b10409f0c04cb8b7d9020", size = 865445, upload-time = "2026-05-09T23:13:12.523Z" }, + { url = "https://files.pythonhosted.org/packages/1a/89/f05169e8588aac365f35ffc7f3bc3184f095ef4cfded7cfaa3c7fd5dbd89/regex-2026.5.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:508f56a89ba9cb26e4168cbc37dbd60a28d82430a9e18ad1d25fe0883c314ca2", size = 912322, upload-time = "2026-05-09T23:13:14.281Z" }, + { url = "https://files.pythonhosted.org/packages/30/e1/c93444052cf41581f3c884ab3fb5823daf0992f11cd4388d4275ca610558/regex-2026.5.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6d189041f15691cfa2b6c4290448ec221244d225b3f5fe9e7771b34ffcdf6e2", size = 801269, upload-time = "2026-05-09T23:13:16.569Z" }, + { url = "https://files.pythonhosted.org/packages/50/fe/0cf96b882f540e62e8b9956599798203d599c44cf4c77917ca27400ff69b/regex-2026.5.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e82db382b44d0111b22601c509c89f64434816c9e0eef9d1989cda8cc6ff1c04", size = 777085, upload-time = "2026-05-09T23:13:18.675Z" }, + { url = "https://files.pythonhosted.org/packages/23/5c/d78d4924e7fc875557b9e9b768423925fdfaac5549d06da7810019a9bd26/regex-2026.5.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2acfb48634f64996b57f90f39afa692ff362162722581921fe92239a59960f3c", size = 785153, upload-time = "2026-05-09T23:13:20.525Z" }, + { url = "https://files.pythonhosted.org/packages/bf/e0/5214774090e7b4524dcea3e3c4aa74141d43043f8beb49c1599db1c8b53a/regex-2026.5.9-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:d29eebfc9525db68cad3c97eedd7f754fa265aa5cd0cf4f863b2421e1b48fc9f", size = 860164, upload-time = "2026-05-09T23:13:22.263Z" }, + { url = "https://files.pythonhosted.org/packages/6e/e1/4a57a83350319b1271f0d7a249b8672513ed928b237a741631270de6caea/regex-2026.5.9-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:debb893095e944091c16e641a6e33c1b0f4cb61ab945ec5afbf53ce7068834d8", size = 765731, upload-time = "2026-05-09T23:13:24.277Z" }, + { url = "https://files.pythonhosted.org/packages/12/f4/499e74a20c156fc75836ee04a72a38d1a063978f600937f9760467beb1b0/regex-2026.5.9-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d659eee77986549c9ea45b861c7567e44d6287c3dc9a4565478853f7b9fe2ff6", size = 852062, upload-time = "2026-05-09T23:13:26.125Z" }, + { url = "https://files.pythonhosted.org/packages/5b/92/7eebc0d0a01e78629695f342ba17e0deaff8fb45e79cc0d7b98287da6e3e/regex-2026.5.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2efa205e6d98b24d1f3ab395c11aa15cdf10935bca283d0285e0499c284fba21", size = 789577, upload-time = "2026-05-09T23:13:27.814Z" }, + { url = "https://files.pythonhosted.org/packages/05/a4/018e71f7d2ad48c1ebe6d3ae0026f9b7cb4802fd15c7cc02fdf724355102/regex-2026.5.9-cp313-cp313-win32.whl", hash = "sha256:f3844f134e834076677dd369976e9f5068679fcb8e50102fdf6b7ac96a3ec127", size = 266691, upload-time = "2026-05-09T23:13:29.549Z" }, + { url = "https://files.pythonhosted.org/packages/e6/1d/861a93719fb9ee7dbfc3761b3797b7a3e112a5d42c6129459d2d741be9b5/regex-2026.5.9-cp313-cp313-win_amd64.whl", hash = "sha256:3527bb4942d2c14552155406cdedd906567456821848aed1cb4933a391bf5eca", size = 277747, upload-time = "2026-05-09T23:13:31.859Z" }, + { url = "https://files.pythonhosted.org/packages/d9/c6/0a2436ae4da1ba76e51cb98943c6838a9a721faa40ebe2dce07694ae34e3/regex-2026.5.9-cp313-cp313-win_arm64.whl", hash = "sha256:56a33f191f17d8c417f99945ebdc1e691d3af9605d86ec68c7e54a57e3e17af6", size = 270500, upload-time = "2026-05-09T23:13:33.525Z" }, + { url = "https://files.pythonhosted.org/packages/e8/e9/d21346f7b60ed58789371358ed66b09d00f832e1bd7c06e55d9da5679882/regex-2026.5.9-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:01f28d868834624c934b8d2e0aa1c8341337e37831f4a012f18a5afcba4cbaf3", size = 494172, upload-time = "2026-05-09T23:13:35.935Z" }, + { url = "https://files.pythonhosted.org/packages/c4/43/fd1177a2032037c681baecdb3422ee4e1424aec4e4f470ef47793d325274/regex-2026.5.9-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:48036f6374aaa79eb3b754ec29c61d1c6b1606749d705a13f8854fa2539671f6", size = 293952, upload-time = "2026-05-09T23:13:38.307Z" }, + { url = "https://files.pythonhosted.org/packages/f2/7d/9fbf919768368d3f8a4f6c692cf2aa61e482b2b81ec6a298ace4cbf02480/regex-2026.5.9-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:b96350aa424e79d4fd6b567b344dcbe2b2d6bfc48dfe7717587e1fa6d43da6ff", size = 292314, upload-time = "2026-05-09T23:13:40.353Z" }, + { url = "https://files.pythonhosted.org/packages/e2/6c/e41bfeecb589716843e7c4df09ba46ff2a42961457afece19059d85caeef/regex-2026.5.9-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8f3af7a4903c5c04a11a196a5aa75cdd7dd3f8508132f9fb3259d9f5908e3b88", size = 811681, upload-time = "2026-05-09T23:13:42.543Z" }, + { url = "https://files.pythonhosted.org/packages/87/83/a5c1c525fba0aa656e88ad0face0b1829788ef4c2fb6b26df58aa1151b84/regex-2026.5.9-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7e87577720152d2caae19fe2baaf1f8d5ca12091e9e229f03915c37d1e4b9178", size = 871135, upload-time = "2026-05-09T23:13:44.326Z" }, + { url = "https://files.pythonhosted.org/packages/18/d4/80882e799e440dd878b0979cbebf8fa4d54624a332c83037c7a701649e3f/regex-2026.5.9-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c8b9b9d294cfea3cd19c718ade7cc93492b2c4991abd9a68d0b3477ae6d8e100", size = 917265, upload-time = "2026-05-09T23:13:47.295Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ff/8db60211e2286e396aad7dc7725356c502bff0901ea05bd6cdc2e1a042b9/regex-2026.5.9-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:728d8bfd28a8845c8b6bc5dc7ce010453d206396786c0765c2740cb65f37791e", size = 816311, upload-time = "2026-05-09T23:13:49.885Z" }, + { url = "https://files.pythonhosted.org/packages/4c/47/742ef579c61730f8d268e5cf1f9ce0e37e2ea041ad0f5644724f2378e463/regex-2026.5.9-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7e30b874d341fac767d7df5a0870540541c2c054b80cfaac116e8d367a8a7ff2", size = 785498, upload-time = "2026-05-09T23:13:52.25Z" }, + { url = "https://files.pythonhosted.org/packages/7f/ab/cb0999802dcb0fb95b1ab005e8d4163d8afdd67efc2cb6b6630ac13f8cb1/regex-2026.5.9-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:fd190e88a895a8901325fad284a3f74ea52b1da8525b76cc811fa9b1edf0ce2b", size = 801348, upload-time = "2026-05-09T23:13:54.127Z" }, + { url = "https://files.pythonhosted.org/packages/7d/62/8ca59a24c55bc34d166eefaf3717bd77772f329fdbf984d86581e0a3571c/regex-2026.5.9-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:8e76e8161ad00694cfce6767d5dea860c6391ac5b83e5c3a39661e696f11fc7e", size = 866493, upload-time = "2026-05-09T23:13:56.067Z" }, + { url = "https://files.pythonhosted.org/packages/8d/3d/30f2ae62cef3278bb5bb821f467277a55fb73f01032cf85997e15e8289a8/regex-2026.5.9-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:ddda5340e6c01a293027dd46232fa79eaff1b48058ce7a98f572b6445b088041", size = 772811, upload-time = "2026-05-09T23:13:57.867Z" }, + { url = "https://files.pythonhosted.org/packages/d8/ae/7d2089bcd78ad0c0161bc684339df50032acb438a7bd3305e7ddb1193cec/regex-2026.5.9-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:205109e96b3cf5adf8f4cd62bedde9487feb282b9497a3535451e5a24cd706a0", size = 856584, upload-time = "2026-05-09T23:13:59.679Z" }, + { url = "https://files.pythonhosted.org/packages/a9/29/92ff47f75990131ea4f24ba17819e5a9d141e10819807e09addd73409af6/regex-2026.5.9-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:dfbe4579b9f08036aa7d101d1835437a20783574ac66327e6b29b4018a138081", size = 803453, upload-time = "2026-05-09T23:14:01.978Z" }, + { url = "https://files.pythonhosted.org/packages/04/99/eff29f1037dcab36702c9ee5d6858cf1ce2336ea8ea2987f64245b99ea5e/regex-2026.5.9-cp313-cp313t-win32.whl", hash = "sha256:ed2c9e8068b614c574d8d30e543d617cf5379b0535d46f97ef00e904745a08b5", size = 269951, upload-time = "2026-05-09T23:14:03.661Z" }, + { url = "https://files.pythonhosted.org/packages/0e/9d/8870b8981d27b22cda77bb26a5ac7ebfa9c7d9e0dea195a834a82380e748/regex-2026.5.9-cp313-cp313t-win_amd64.whl", hash = "sha256:b46b0f094dc1d3b90356c85a0bd2c9bafc4a6a190b9d6f8ddd5a033b6e088ed4", size = 281240, upload-time = "2026-05-09T23:14:05.56Z" }, + { url = "https://files.pythonhosted.org/packages/72/b1/3379415e8f135c13ac551353397cc4fe97b4978f3cac73c5fcbcded548b8/regex-2026.5.9-cp313-cp313t-win_arm64.whl", hash = "sha256:872acc074bd29ffc9913ecdfedf6ea77502312ca44a4aa0d3779089c6069d8de", size = 272383, upload-time = "2026-05-09T23:14:07.843Z" }, + { url = "https://files.pythonhosted.org/packages/13/3e/9c3cd292d8808b3645a2ce517e200179b6d0e903f176300bd8b542e14de5/regex-2026.5.9-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:1bd7587a2948b4085195d5a3374eaf4a425dc3e55784c038175355ecf3bbbf8a", size = 490376, upload-time = "2026-05-09T23:14:09.64Z" }, + { url = "https://files.pythonhosted.org/packages/60/70/d43ee8a2ca0a8b68d167f21658b85520ac0574617c7f320367c5047f7556/regex-2026.5.9-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:dea2e88e1cce4522496cce630e11e67b98b7076620bc4336c3f674bc21a375f4", size = 291964, upload-time = "2026-05-09T23:14:11.424Z" }, + { url = "https://files.pythonhosted.org/packages/21/91/9d50b433828d8e74196904e168a43abf1e6e88b2a15d47ed742456720c37/regex-2026.5.9-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:2099f7e7ff7b6aa3192312650a56e91cc091e49d50b04e4f6f8b6e28b3b27f1c", size = 289682, upload-time = "2026-05-09T23:14:13.123Z" }, + { url = "https://files.pythonhosted.org/packages/3e/d2/b835e3cafbb9d977736912436259ff551d60919f7d7b3d37d46659c63564/regex-2026.5.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecd353045824e4477562a2ac718c25799cdaaa41f7aa925a806a8a3e6848a5b9", size = 796996, upload-time = "2026-05-09T23:14:14.923Z" }, + { url = "https://files.pythonhosted.org/packages/2c/a6/9f992d00019166b9de01c546dd4549bc679f2a68df11b877740b0760b7c2/regex-2026.5.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:65c8c8c37377794bd5b2f3ebe51919042bf17aec802e23c833d89782ed0c78af", size = 866089, upload-time = "2026-05-09T23:14:17.757Z" }, + { url = "https://files.pythonhosted.org/packages/e0/08/4d32af657e049b19cb62b02e46e38fe1518797bfb2203ee93a510b21b0dc/regex-2026.5.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5b73ab8afcf66c622db143d1c6fda4e58e4d537ee4f125229ad47b1ab80f34c0", size = 911530, upload-time = "2026-05-09T23:14:20.353Z" }, + { url = "https://files.pythonhosted.org/packages/d9/27/2af43dd1dc201d1fecefda64a45f4ad0995855b92724f795a777b402ee69/regex-2026.5.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0de5cf193997384ed2ca6f1cd4f78055b255d93d82d5a8cd6ba0d11c10b167e4", size = 800643, upload-time = "2026-05-09T23:14:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/a4/dd/23a249047013b5321d4a60c4d2437462086f601b061776a525e5fba2a59f/regex-2026.5.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d641a8c9a61618047796d572a39a79b26167b0411d2c3031937b2fe2d081e2cf", size = 777223, upload-time = "2026-05-09T23:14:24.179Z" }, + { url = "https://files.pythonhosted.org/packages/94/6a/e85ed9538cd19586d0465076a4578a12e093ce776d15f3f8ce92733a8dd6/regex-2026.5.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:24b2355ef5cc9aa5b8f07d17704face1c166fdcc2290fa7bd6e6c925655a8346", size = 785760, upload-time = "2026-05-09T23:14:26.065Z" }, + { url = "https://files.pythonhosted.org/packages/2a/c4/f25473209438638e947c55f9156fd8f236f74169229028cc99116380868e/regex-2026.5.9-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:a24852d3c29ad9e47593593d8a247c44ccc3d0548ef12c822d6ed0810affe676", size = 860891, upload-time = "2026-05-09T23:14:28.17Z" }, + { url = "https://files.pythonhosted.org/packages/f9/f7/f4f86e3c74419c37370e91f150ae0c2ef7d34b2e0e4cdd5da046a02e4022/regex-2026.5.9-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:916714069da19329ef7de197dcbc77bb3104145c7c2c864dbfbe318f46b88b14", size = 765891, upload-time = "2026-05-09T23:14:30.06Z" }, + { url = "https://files.pythonhosted.org/packages/26/70/704d8e13765939146b1cd0ef4e2feb71d7929727d2290f026eed10095955/regex-2026.5.9-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:fa411799ca8da32a8d38d020a88faa5b6f91657d284761352940ecf9f7c3bbdd", size = 851380, upload-time = "2026-05-09T23:14:32.123Z" }, + { url = "https://files.pythonhosted.org/packages/26/29/1a13582a8460038edc38e49f64ceb0dd7c60f5caba77571f4bf6601965d9/regex-2026.5.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:1e6da47d679b7010ef27556b6e0f99771b744936db1792a10ceac6547ae1503e", size = 789350, upload-time = "2026-05-09T23:14:34.799Z" }, + { url = "https://files.pythonhosted.org/packages/73/56/3dcafe34fc72e271d62ad9a291801e88a1457bb251c132f15fcc2e5aad1a/regex-2026.5.9-cp314-cp314-win32.whl", hash = "sha256:98bd73080e8756255137e1bd3f3f00295bbc5aa383c0e0f973920e9134d7c4ad", size = 272130, upload-time = "2026-05-09T23:14:36.729Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9c/02eebf0be95efe416c664db7fb8b6b05b7a0b06a7544f2884f2558b0526f/regex-2026.5.9-cp314-cp314-win_amd64.whl", hash = "sha256:ff8d372ac2acdc048d1c19916f27ee61bc5722728458ba6ca5052f2c72d51763", size = 280999, upload-time = "2026-05-09T23:14:39.126Z" }, + { url = "https://files.pythonhosted.org/packages/70/5a/1dd1abee76cb7a846a0bcf42fdc87e5720c3c33c24f3e37814310a513d9f/regex-2026.5.9-cp314-cp314-win_arm64.whl", hash = "sha256:e1d93bf647916292e8edcec150c07ddf3dc50179ccaf770c04a7f9e452155372", size = 273500, upload-time = "2026-05-09T23:14:41.059Z" }, + { url = "https://files.pythonhosted.org/packages/86/c1/c5f619b0057a7965cb78ec559c1d7a45ce8c99a35bea95483d64959a93d9/regex-2026.5.9-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:83d0ee4a57d1c87cb549e195ec300b8f0ec3a82eba66d835e4e2ed8634fe4499", size = 494269, upload-time = "2026-05-09T23:14:42.869Z" }, + { url = "https://files.pythonhosted.org/packages/05/2c/5d01f1aee33de4bbe60c8452945bfc8477ca7c5ae4450f6bfe711036cb36/regex-2026.5.9-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:d3d7eb5c9a7f6df82ed3cfac9beb93882a5cbcb5b8b157b56cb2b3b276574ac1", size = 293954, upload-time = "2026-05-09T23:14:44.822Z" }, + { url = "https://files.pythonhosted.org/packages/7a/fe/e8988b2ae2108c6ef71bd4aa8d87fbe257976dd0810e826cd75f701c68b6/regex-2026.5.9-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:075160bf16658e16d35233300b8453aac25de4cbea808d22348b6979668e924d", size = 292405, upload-time = "2026-05-09T23:14:47.211Z" }, + { url = "https://files.pythonhosted.org/packages/79/34/d2b0937faa7859263f7f0a3c6b103a1296306be6952dc173d0154e9a2f49/regex-2026.5.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45375819235558a4ff1c4971dc32881f022613abdb180128f5cb4768c1765a1c", size = 811855, upload-time = "2026-05-09T23:14:49.21Z" }, + { url = "https://files.pythonhosted.org/packages/80/fe/daf53a47457a8486db66c66c01ceb9c2303eecee3f87197f1e77eb1a736d/regex-2026.5.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ead4b163ac30a29574510cd4b3e2e985ac5290c05fc7095557d6a5f403fc31b5", size = 871189, upload-time = "2026-05-09T23:14:51.555Z" }, + { url = "https://files.pythonhosted.org/packages/1c/75/058fc4470cbfbf57d800aff1a0022b929a3f9fa553ee10a0cdf2070eb31f/regex-2026.5.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8c6e4218fbdfbcd4f6c19efca40930d24a621bf4b48cb76bc6640543bd28ef20", size = 917485, upload-time = "2026-05-09T23:14:53.633Z" }, + { url = "https://files.pythonhosted.org/packages/88/e7/179cfda3a28bc843b5c6cfe7f79f23489c791ed95f151083803660878432/regex-2026.5.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6351571c8a42b505eb555c0dc47d740d0fb66977dc142919eea6f4325b7c56a0", size = 816369, upload-time = "2026-05-09T23:14:56.198Z" }, + { url = "https://files.pythonhosted.org/packages/41/90/6f0cc422071688266d344fca8462d787cba0a2c144acb25721f9a61ec265/regex-2026.5.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:002205cafd2a9e78c6290c7d1df277bf3277b3b7a30e0b4bb0dac2e2e3f7cb2d", size = 785869, upload-time = "2026-05-09T23:14:58.602Z" }, + { url = "https://files.pythonhosted.org/packages/02/67/a31f1760f09c27b251ef39e9beb541f462cf977381d067faa764c2c0e393/regex-2026.5.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8abd33fef90b2a9efac5557d6033ca82d1195ed3a15fea5af15ba7b463c6a63b", size = 801427, upload-time = "2026-05-09T23:15:00.642Z" }, + { url = "https://files.pythonhosted.org/packages/e3/c4/1a80654597b6bc1e1ea0494824c31200e8a956abe290afae9b19a166a148/regex-2026.5.9-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:31037c82eccb44b7ea2e9e221d7c01429430e989a1f4b91ea5a855f6017b509a", size = 866482, upload-time = "2026-05-09T23:15:03.384Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/960724e06482c08466ff5611e242e86f80062949cdf6b4b9cc317b9dd93d/regex-2026.5.9-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:5604dfd046dc37eca90250fc3be938b076c8059fa772ac0ed6f499b0f0fb0415", size = 773022, upload-time = "2026-05-09T23:15:05.625Z" }, + { url = "https://files.pythonhosted.org/packages/50/a8/a9979c3e7918280e93159ebcab5ef1a65116dd4f3bd6091be0eae4a126e8/regex-2026.5.9-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:0e1b1b4e496afbb24f4a62aba855ee4f88f25578927697b340702e48c9ee6bc2", size = 856642, upload-time = "2026-05-09T23:15:07.966Z" }, + { url = "https://files.pythonhosted.org/packages/fe/d4/a9b732f2f0072c0ab12227483abb24fffcb9f73f8a2b203df0a6d0434735/regex-2026.5.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:be3372b9df6ddecff6486d37e19095a7b4973137caf5512407a89f4455361f41", size = 803552, upload-time = "2026-05-09T23:15:10.215Z" }, + { url = "https://files.pythonhosted.org/packages/d5/fe/1b3113817447a1d4155e4ac76d2e072f42c0bcba2f43fa8a0e756ea2cd91/regex-2026.5.9-cp314-cp314t-win32.whl", hash = "sha256:3ddd90103f9e5c471c49c7852ecc1fe27c7e45eb99e977aefe7caa4e779f4f58", size = 275746, upload-time = "2026-05-09T23:15:12.609Z" }, + { url = "https://files.pythonhosted.org/packages/92/73/93d42045302636c91f2e5ef588b65b84b01428f28ec77de256b1dfdfbe5c/regex-2026.5.9-cp314-cp314t-win_amd64.whl", hash = "sha256:ca518ed29c46eecba6010b15f1b9a479314d2de409536e71b6a13aa04e3b8a77", size = 285685, upload-time = "2026-05-09T23:15:15.086Z" }, + { url = "https://files.pythonhosted.org/packages/da/80/35b4c33c804a165a7f55289afda3ea9e3eb6d15800341a2d66455c0f1f30/regex-2026.5.9-cp314-cp314t-win_arm64.whl", hash = "sha256:5e41809d2683fcde7d5a8c87a6567ba1fb1ce0de9f31bff578de00a4b2d76daa", size = 275713, upload-time = "2026-05-09T23:15:16.98Z" }, +] + +[[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 = "responses" +version = "0.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, + { name = "requests" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9f/b4/b7e040379838cc71bf5aabdb26998dfbe5ee73904c92c1c161faf5de8866/responses-0.26.0.tar.gz", hash = "sha256:c7f6923e6343ef3682816ba421c006626777893cb0d5e1434f674b649bac9eb4", size = 81303, upload-time = "2026-02-19T14:38:05.574Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ce/04/7f73d05b556da048923e31a0cc878f03be7c5425ed1f268082255c75d872/responses-0.26.0-py3-none-any.whl", hash = "sha256:03ec4409088cd5c66b71ecbbbd27fe2c58ddfad801c66203457b3e6a04868c37", size = 35099, upload-time = "2026-02-19T14:38:03.847Z" }, +] + +[[package]] +name = "rfc3339-validator" +version = "0.1.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/ea/a9387748e2d111c3c2b275ba970b735e04e15cdb1eb30693b6b5708c4dbd/rfc3339_validator-0.1.4.tar.gz", hash = "sha256:138a2abdf93304ad60530167e51d2dfb9549521a836871b88d7f4695d0022f6b", size = 5513, upload-time = "2021-05-12T16:37:54.178Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/44/4e421b96b67b2daff264473f7465db72fbdf36a07e05494f50300cc7b0c6/rfc3339_validator-0.1.4-py2.py3-none-any.whl", hash = "sha256:24f6ec1eda14ef823da9e36ec7113124b39c04d50a4d3d3a3c2859577e7791fa", size = 3490, upload-time = "2021-05-12T16:37:52.536Z" }, +] + +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + +[[package]] +name = "roman-numerals" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ae/f9/41dc953bbeb056c17d5f7a519f50fdf010bd0553be2d630bc69d1e022703/roman_numerals-4.1.0.tar.gz", hash = "sha256:1af8b147eb1405d5839e78aeb93131690495fe9da5c91856cb33ad55a7f1e5b2", size = 9077, upload-time = "2025-12-17T18:25:34.381Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/54/6f679c435d28e0a568d8e8a7c0a93a09010818634c3c3907fc98d8983770/roman_numerals-4.1.0-py3-none-any.whl", hash = "sha256:647ba99caddc2cc1e55a51e4360689115551bf4476d90e8162cf8c345fe233c7", size = 7676, upload-time = "2025-12-17T18:25:33.098Z" }, +] + +[[package]] +name = "rpds-py" +version = "0.30.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/20/af/3f2f423103f1113b36230496629986e0ef7e199d2aa8392452b484b38ced/rpds_py-0.30.0.tar.gz", hash = "sha256:dd8ff7cf90014af0c0f787eea34794ebf6415242ee1d6fa91eaba725cc441e84", size = 69469, upload-time = "2025-11-30T20:24:38.837Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e7/98a2f4ac921d82f33e03f3835f5bf3a4a40aa1bfdc57975e74a97b2b4bdd/rpds_py-0.30.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a161f20d9a43006833cd7068375a94d035714d73a172b681d8881820600abfad", size = 375086, upload-time = "2025-11-30T20:22:17.93Z" }, + { url = "https://files.pythonhosted.org/packages/4d/a1/bca7fd3d452b272e13335db8d6b0b3ecde0f90ad6f16f3328c6fb150c889/rpds_py-0.30.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6abc8880d9d036ecaafe709079969f56e876fcf107f7a8e9920ba6d5a3878d05", size = 359053, upload-time = "2025-11-30T20:22:19.297Z" }, + { url = "https://files.pythonhosted.org/packages/65/1c/ae157e83a6357eceff62ba7e52113e3ec4834a84cfe07fa4b0757a7d105f/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca28829ae5f5d569bb62a79512c842a03a12576375d5ece7d2cadf8abe96ec28", size = 390763, upload-time = "2025-11-30T20:22:21.661Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/eb2eb8515e2ad24c0bd43c3ee9cd74c33f7ca6430755ccdb240fd3144c44/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a1010ed9524c73b94d15919ca4d41d8780980e1765babf85f9a2f90d247153dd", size = 408951, upload-time = "2025-11-30T20:22:23.408Z" }, + { url = "https://files.pythonhosted.org/packages/d6/65/ad8dc1784a331fabbd740ef6f71ce2198c7ed0890dab595adb9ea2d775a1/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f8d1736cfb49381ba528cd5baa46f82fdc65c06e843dab24dd70b63d09121b3f", size = 514622, upload-time = "2025-11-30T20:22:25.16Z" }, + { url = "https://files.pythonhosted.org/packages/63/8e/0cfa7ae158e15e143fe03993b5bcd743a59f541f5952e1546b1ac1b5fd45/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d948b135c4693daff7bc2dcfc4ec57237a29bd37e60c2fabf5aff2bbacf3e2f1", size = 414492, upload-time = "2025-11-30T20:22:26.505Z" }, + { url = "https://files.pythonhosted.org/packages/60/1b/6f8f29f3f995c7ffdde46a626ddccd7c63aefc0efae881dc13b6e5d5bb16/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47f236970bccb2233267d89173d3ad2703cd36a0e2a6e92d0560d333871a3d23", size = 394080, upload-time = "2025-11-30T20:22:27.934Z" }, + { url = "https://files.pythonhosted.org/packages/6d/d5/a266341051a7a3ca2f4b750a3aa4abc986378431fc2da508c5034d081b70/rpds_py-0.30.0-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:2e6ecb5a5bcacf59c3f912155044479af1d0b6681280048b338b28e364aca1f6", size = 408680, upload-time = "2025-11-30T20:22:29.341Z" }, + { url = "https://files.pythonhosted.org/packages/10/3b/71b725851df9ab7a7a4e33cf36d241933da66040d195a84781f49c50490c/rpds_py-0.30.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a8fa71a2e078c527c3e9dc9fc5a98c9db40bcc8a92b4e8858e36d329f8684b51", size = 423589, upload-time = "2025-11-30T20:22:31.469Z" }, + { url = "https://files.pythonhosted.org/packages/00/2b/e59e58c544dc9bd8bd8384ecdb8ea91f6727f0e37a7131baeff8d6f51661/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:73c67f2db7bc334e518d097c6d1e6fed021bbc9b7d678d6cc433478365d1d5f5", size = 573289, upload-time = "2025-11-30T20:22:32.997Z" }, + { url = "https://files.pythonhosted.org/packages/da/3e/a18e6f5b460893172a7d6a680e86d3b6bc87a54c1f0b03446a3c8c7b588f/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:5ba103fb455be00f3b1c2076c9d4264bfcb037c976167a6047ed82f23153f02e", size = 599737, upload-time = "2025-11-30T20:22:34.419Z" }, + { url = "https://files.pythonhosted.org/packages/5c/e2/714694e4b87b85a18e2c243614974413c60aa107fd815b8cbc42b873d1d7/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7cee9c752c0364588353e627da8a7e808a66873672bcb5f52890c33fd965b394", size = 563120, upload-time = "2025-11-30T20:22:35.903Z" }, + { url = "https://files.pythonhosted.org/packages/6f/ab/d5d5e3bcedb0a77f4f613706b750e50a5a3ba1c15ccd3665ecc636c968fd/rpds_py-0.30.0-cp312-cp312-win32.whl", hash = "sha256:1ab5b83dbcf55acc8b08fc62b796ef672c457b17dbd7820a11d6c52c06839bdf", size = 223782, upload-time = "2025-11-30T20:22:37.271Z" }, + { url = "https://files.pythonhosted.org/packages/39/3b/f786af9957306fdc38a74cef405b7b93180f481fb48453a114bb6465744a/rpds_py-0.30.0-cp312-cp312-win_amd64.whl", hash = "sha256:a090322ca841abd453d43456ac34db46e8b05fd9b3b4ac0c78bcde8b089f959b", size = 240463, upload-time = "2025-11-30T20:22:39.021Z" }, + { url = "https://files.pythonhosted.org/packages/f3/d2/b91dc748126c1559042cfe41990deb92c4ee3e2b415f6b5234969ffaf0cc/rpds_py-0.30.0-cp312-cp312-win_arm64.whl", hash = "sha256:669b1805bd639dd2989b281be2cfd951c6121b65e729d9b843e9639ef1fd555e", size = 230868, upload-time = "2025-11-30T20:22:40.493Z" }, + { url = "https://files.pythonhosted.org/packages/ed/dc/d61221eb88ff410de3c49143407f6f3147acf2538c86f2ab7ce65ae7d5f9/rpds_py-0.30.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:f83424d738204d9770830d35290ff3273fbb02b41f919870479fab14b9d303b2", size = 374887, upload-time = "2025-11-30T20:22:41.812Z" }, + { url = "https://files.pythonhosted.org/packages/fd/32/55fb50ae104061dbc564ef15cc43c013dc4a9f4527a1f4d99baddf56fe5f/rpds_py-0.30.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e7536cd91353c5273434b4e003cbda89034d67e7710eab8761fd918ec6c69cf8", size = 358904, upload-time = "2025-11-30T20:22:43.479Z" }, + { url = "https://files.pythonhosted.org/packages/58/70/faed8186300e3b9bdd138d0273109784eea2396c68458ed580f885dfe7ad/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2771c6c15973347f50fece41fc447c054b7ac2ae0502388ce3b6738cd366e3d4", size = 389945, upload-time = "2025-11-30T20:22:44.819Z" }, + { url = "https://files.pythonhosted.org/packages/bd/a8/073cac3ed2c6387df38f71296d002ab43496a96b92c823e76f46b8af0543/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:0a59119fc6e3f460315fe9d08149f8102aa322299deaa5cab5b40092345c2136", size = 407783, upload-time = "2025-11-30T20:22:46.103Z" }, + { url = "https://files.pythonhosted.org/packages/77/57/5999eb8c58671f1c11eba084115e77a8899d6e694d2a18f69f0ba471ec8b/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:76fec018282b4ead0364022e3c54b60bf368b9d926877957a8624b58419169b7", size = 515021, upload-time = "2025-11-30T20:22:47.458Z" }, + { url = "https://files.pythonhosted.org/packages/e0/af/5ab4833eadc36c0a8ed2bc5c0de0493c04f6c06de223170bd0798ff98ced/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:692bef75a5525db97318e8cd061542b5a79812d711ea03dbc1f6f8dbb0c5f0d2", size = 414589, upload-time = "2025-11-30T20:22:48.872Z" }, + { url = "https://files.pythonhosted.org/packages/b7/de/f7192e12b21b9e9a68a6d0f249b4af3fdcdff8418be0767a627564afa1f1/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9027da1ce107104c50c81383cae773ef5c24d296dd11c99e2629dbd7967a20c6", size = 394025, upload-time = "2025-11-30T20:22:50.196Z" }, + { url = "https://files.pythonhosted.org/packages/91/c4/fc70cd0249496493500e7cc2de87504f5aa6509de1e88623431fec76d4b6/rpds_py-0.30.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:9cf69cdda1f5968a30a359aba2f7f9aa648a9ce4b580d6826437f2b291cfc86e", size = 408895, upload-time = "2025-11-30T20:22:51.87Z" }, + { url = "https://files.pythonhosted.org/packages/58/95/d9275b05ab96556fefff73a385813eb66032e4c99f411d0795372d9abcea/rpds_py-0.30.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a4796a717bf12b9da9d3ad002519a86063dcac8988b030e405704ef7d74d2d9d", size = 422799, upload-time = "2025-11-30T20:22:53.341Z" }, + { url = "https://files.pythonhosted.org/packages/06/c1/3088fc04b6624eb12a57eb814f0d4997a44b0d208d6cace713033ff1a6ba/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5d4c2aa7c50ad4728a094ebd5eb46c452e9cb7edbfdb18f9e1221f597a73e1e7", size = 572731, upload-time = "2025-11-30T20:22:54.778Z" }, + { url = "https://files.pythonhosted.org/packages/d8/42/c612a833183b39774e8ac8fecae81263a68b9583ee343db33ab571a7ce55/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ba81a9203d07805435eb06f536d95a266c21e5b2dfbf6517748ca40c98d19e31", size = 599027, upload-time = "2025-11-30T20:22:56.212Z" }, + { url = "https://files.pythonhosted.org/packages/5f/60/525a50f45b01d70005403ae0e25f43c0384369ad24ffe46e8d9068b50086/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:945dccface01af02675628334f7cf49c2af4c1c904748efc5cf7bbdf0b579f95", size = 563020, upload-time = "2025-11-30T20:22:58.2Z" }, + { url = "https://files.pythonhosted.org/packages/0b/5d/47c4655e9bcd5ca907148535c10e7d489044243cc9941c16ed7cd53be91d/rpds_py-0.30.0-cp313-cp313-win32.whl", hash = "sha256:b40fb160a2db369a194cb27943582b38f79fc4887291417685f3ad693c5a1d5d", size = 223139, upload-time = "2025-11-30T20:23:00.209Z" }, + { url = "https://files.pythonhosted.org/packages/f2/e1/485132437d20aa4d3e1d8b3fb5a5e65aa8139f1e097080c2a8443201742c/rpds_py-0.30.0-cp313-cp313-win_amd64.whl", hash = "sha256:806f36b1b605e2d6a72716f321f20036b9489d29c51c91f4dd29a3e3afb73b15", size = 240224, upload-time = "2025-11-30T20:23:02.008Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/ffd128ed1146a153d928617b0ef673960130be0009c77d8fbf0abe306713/rpds_py-0.30.0-cp313-cp313-win_arm64.whl", hash = "sha256:d96c2086587c7c30d44f31f42eae4eac89b60dabbac18c7669be3700f13c3ce1", size = 230645, upload-time = "2025-11-30T20:23:03.43Z" }, + { url = "https://files.pythonhosted.org/packages/ff/1b/b10de890a0def2a319a2626334a7f0ae388215eb60914dbac8a3bae54435/rpds_py-0.30.0-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:eb0b93f2e5c2189ee831ee43f156ed34e2a89a78a66b98cadad955972548be5a", size = 364443, upload-time = "2025-11-30T20:23:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/0d/bf/27e39f5971dc4f305a4fb9c672ca06f290f7c4e261c568f3dea16a410d47/rpds_py-0.30.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:922e10f31f303c7c920da8981051ff6d8c1a56207dbdf330d9047f6d30b70e5e", size = 353375, upload-time = "2025-11-30T20:23:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/40/58/442ada3bba6e8e6615fc00483135c14a7538d2ffac30e2d933ccf6852232/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cdc62c8286ba9bf7f47befdcea13ea0e26bf294bda99758fd90535cbaf408000", size = 383850, upload-time = "2025-11-30T20:23:07.825Z" }, + { url = "https://files.pythonhosted.org/packages/14/14/f59b0127409a33c6ef6f5c1ebd5ad8e32d7861c9c7adfa9a624fc3889f6c/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:47f9a91efc418b54fb8190a6b4aa7813a23fb79c51f4bb84e418f5476c38b8db", size = 392812, upload-time = "2025-11-30T20:23:09.228Z" }, + { url = "https://files.pythonhosted.org/packages/b3/66/e0be3e162ac299b3a22527e8913767d869e6cc75c46bd844aa43fb81ab62/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1f3587eb9b17f3789ad50824084fa6f81921bbf9a795826570bda82cb3ed91f2", size = 517841, upload-time = "2025-11-30T20:23:11.186Z" }, + { url = "https://files.pythonhosted.org/packages/3d/55/fa3b9cf31d0c963ecf1ba777f7cf4b2a2c976795ac430d24a1f43d25a6ba/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:39c02563fc592411c2c61d26b6c5fe1e51eaa44a75aa2c8735ca88b0d9599daa", size = 408149, upload-time = "2025-11-30T20:23:12.864Z" }, + { url = "https://files.pythonhosted.org/packages/60/ca/780cf3b1a32b18c0f05c441958d3758f02544f1d613abf9488cd78876378/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:51a1234d8febafdfd33a42d97da7a43f5dcb120c1060e352a3fbc0c6d36e2083", size = 383843, upload-time = "2025-11-30T20:23:14.638Z" }, + { url = "https://files.pythonhosted.org/packages/82/86/d5f2e04f2aa6247c613da0c1dd87fcd08fa17107e858193566048a1e2f0a/rpds_py-0.30.0-cp313-cp313t-manylinux_2_31_riscv64.whl", hash = "sha256:eb2c4071ab598733724c08221091e8d80e89064cd472819285a9ab0f24bcedb9", size = 396507, upload-time = "2025-11-30T20:23:16.105Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9a/453255d2f769fe44e07ea9785c8347edaf867f7026872e76c1ad9f7bed92/rpds_py-0.30.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6bdfdb946967d816e6adf9a3d8201bfad269c67efe6cefd7093ef959683c8de0", size = 414949, upload-time = "2025-11-30T20:23:17.539Z" }, + { url = "https://files.pythonhosted.org/packages/a3/31/622a86cdc0c45d6df0e9ccb6becdba5074735e7033c20e401a6d9d0e2ca0/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c77afbd5f5250bf27bf516c7c4a016813eb2d3e116139aed0096940c5982da94", size = 565790, upload-time = "2025-11-30T20:23:19.029Z" }, + { url = "https://files.pythonhosted.org/packages/1c/5d/15bbf0fb4a3f58a3b1c67855ec1efcc4ceaef4e86644665fff03e1b66d8d/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:61046904275472a76c8c90c9ccee9013d70a6d0f73eecefd38c1ae7c39045a08", size = 590217, upload-time = "2025-11-30T20:23:20.885Z" }, + { url = "https://files.pythonhosted.org/packages/6d/61/21b8c41f68e60c8cc3b2e25644f0e3681926020f11d06ab0b78e3c6bbff1/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4c5f36a861bc4b7da6516dbdf302c55313afa09b81931e8280361a4f6c9a2d27", size = 555806, upload-time = "2025-11-30T20:23:22.488Z" }, + { url = "https://files.pythonhosted.org/packages/f9/39/7e067bb06c31de48de3eb200f9fc7c58982a4d3db44b07e73963e10d3be9/rpds_py-0.30.0-cp313-cp313t-win32.whl", hash = "sha256:3d4a69de7a3e50ffc214ae16d79d8fbb0922972da0356dcf4d0fdca2878559c6", size = 211341, upload-time = "2025-11-30T20:23:24.449Z" }, + { url = "https://files.pythonhosted.org/packages/0a/4d/222ef0b46443cf4cf46764d9c630f3fe4abaa7245be9417e56e9f52b8f65/rpds_py-0.30.0-cp313-cp313t-win_amd64.whl", hash = "sha256:f14fc5df50a716f7ece6a80b6c78bb35ea2ca47c499e422aa4463455dd96d56d", size = 225768, upload-time = "2025-11-30T20:23:25.908Z" }, + { url = "https://files.pythonhosted.org/packages/86/81/dad16382ebbd3d0e0328776d8fd7ca94220e4fa0798d1dc5e7da48cb3201/rpds_py-0.30.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:68f19c879420aa08f61203801423f6cd5ac5f0ac4ac82a2368a9fcd6a9a075e0", size = 362099, upload-time = "2025-11-30T20:23:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/2b/60/19f7884db5d5603edf3c6bce35408f45ad3e97e10007df0e17dd57af18f8/rpds_py-0.30.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:ec7c4490c672c1a0389d319b3a9cfcd098dcdc4783991553c332a15acf7249be", size = 353192, upload-time = "2025-11-30T20:23:29.151Z" }, + { url = "https://files.pythonhosted.org/packages/bf/c4/76eb0e1e72d1a9c4703c69607cec123c29028bff28ce41588792417098ac/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f251c812357a3fed308d684a5079ddfb9d933860fc6de89f2b7ab00da481e65f", size = 384080, upload-time = "2025-11-30T20:23:30.785Z" }, + { url = "https://files.pythonhosted.org/packages/72/87/87ea665e92f3298d1b26d78814721dc39ed8d2c74b86e83348d6b48a6f31/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ac98b175585ecf4c0348fd7b29c3864bda53b805c773cbf7bfdaffc8070c976f", size = 394841, upload-time = "2025-11-30T20:23:32.209Z" }, + { url = "https://files.pythonhosted.org/packages/77/ad/7783a89ca0587c15dcbf139b4a8364a872a25f861bdb88ed99f9b0dec985/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3e62880792319dbeb7eb866547f2e35973289e7d5696c6e295476448f5b63c87", size = 516670, upload-time = "2025-11-30T20:23:33.742Z" }, + { url = "https://files.pythonhosted.org/packages/5b/3c/2882bdac942bd2172f3da574eab16f309ae10a3925644e969536553cb4ee/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4e7fc54e0900ab35d041b0601431b0a0eb495f0851a0639b6ef90f7741b39a18", size = 408005, upload-time = "2025-11-30T20:23:35.253Z" }, + { url = "https://files.pythonhosted.org/packages/ce/81/9a91c0111ce1758c92516a3e44776920b579d9a7c09b2b06b642d4de3f0f/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47e77dc9822d3ad616c3d5759ea5631a75e5809d5a28707744ef79d7a1bcfcad", size = 382112, upload-time = "2025-11-30T20:23:36.842Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8e/1da49d4a107027e5fbc64daeab96a0706361a2918da10cb41769244b805d/rpds_py-0.30.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:b4dc1a6ff022ff85ecafef7979a2c6eb423430e05f1165d6688234e62ba99a07", size = 399049, upload-time = "2025-11-30T20:23:38.343Z" }, + { url = "https://files.pythonhosted.org/packages/df/5a/7ee239b1aa48a127570ec03becbb29c9d5a9eb092febbd1699d567cae859/rpds_py-0.30.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4559c972db3a360808309e06a74628b95eaccbf961c335c8fe0d590cf587456f", size = 415661, upload-time = "2025-11-30T20:23:40.263Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/caa143cf6b772f823bc7929a45da1fa83569ee49b11d18d0ada7f5ee6fd6/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:0ed177ed9bded28f8deb6ab40c183cd1192aa0de40c12f38be4d59cd33cb5c65", size = 565606, upload-time = "2025-11-30T20:23:42.186Z" }, + { url = "https://files.pythonhosted.org/packages/64/91/ac20ba2d69303f961ad8cf55bf7dbdb4763f627291ba3d0d7d67333cced9/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ad1fa8db769b76ea911cb4e10f049d80bf518c104f15b3edb2371cc65375c46f", size = 591126, upload-time = "2025-11-30T20:23:44.086Z" }, + { url = "https://files.pythonhosted.org/packages/21/20/7ff5f3c8b00c8a95f75985128c26ba44503fb35b8e0259d812766ea966c7/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:46e83c697b1f1c72b50e5ee5adb4353eef7406fb3f2043d64c33f20ad1c2fc53", size = 553371, upload-time = "2025-11-30T20:23:46.004Z" }, + { url = "https://files.pythonhosted.org/packages/72/c7/81dadd7b27c8ee391c132a6b192111ca58d866577ce2d9b0ca157552cce0/rpds_py-0.30.0-cp314-cp314-win32.whl", hash = "sha256:ee454b2a007d57363c2dfd5b6ca4a5d7e2c518938f8ed3b706e37e5d470801ed", size = 215298, upload-time = "2025-11-30T20:23:47.696Z" }, + { url = "https://files.pythonhosted.org/packages/3e/d2/1aaac33287e8cfb07aab2e6b8ac1deca62f6f65411344f1433c55e6f3eb8/rpds_py-0.30.0-cp314-cp314-win_amd64.whl", hash = "sha256:95f0802447ac2d10bcc69f6dc28fe95fdf17940367b21d34e34c737870758950", size = 228604, upload-time = "2025-11-30T20:23:49.501Z" }, + { url = "https://files.pythonhosted.org/packages/e8/95/ab005315818cc519ad074cb7784dae60d939163108bd2b394e60dc7b5461/rpds_py-0.30.0-cp314-cp314-win_arm64.whl", hash = "sha256:613aa4771c99f03346e54c3f038e4cc574ac09a3ddfb0e8878487335e96dead6", size = 222391, upload-time = "2025-11-30T20:23:50.96Z" }, + { url = "https://files.pythonhosted.org/packages/9e/68/154fe0194d83b973cdedcdcc88947a2752411165930182ae41d983dcefa6/rpds_py-0.30.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:7e6ecfcb62edfd632e56983964e6884851786443739dbfe3582947e87274f7cb", size = 364868, upload-time = "2025-11-30T20:23:52.494Z" }, + { url = "https://files.pythonhosted.org/packages/83/69/8bbc8b07ec854d92a8b75668c24d2abcb1719ebf890f5604c61c9369a16f/rpds_py-0.30.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a1d0bc22a7cdc173fedebb73ef81e07faef93692b8c1ad3733b67e31e1b6e1b8", size = 353747, upload-time = "2025-11-30T20:23:54.036Z" }, + { url = "https://files.pythonhosted.org/packages/ab/00/ba2e50183dbd9abcce9497fa5149c62b4ff3e22d338a30d690f9af970561/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0d08f00679177226c4cb8c5265012eea897c8ca3b93f429e546600c971bcbae7", size = 383795, upload-time = "2025-11-30T20:23:55.556Z" }, + { url = "https://files.pythonhosted.org/packages/05/6f/86f0272b84926bcb0e4c972262f54223e8ecc556b3224d281e6598fc9268/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5965af57d5848192c13534f90f9dd16464f3c37aaf166cc1da1cae1fd5a34898", size = 393330, upload-time = "2025-11-30T20:23:57.033Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e9/0e02bb2e6dc63d212641da45df2b0bf29699d01715913e0d0f017ee29438/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9a4e86e34e9ab6b667c27f3211ca48f73dba7cd3d90f8d5b11be56e5dbc3fb4e", size = 518194, upload-time = "2025-11-30T20:23:58.637Z" }, + { url = "https://files.pythonhosted.org/packages/ee/ca/be7bca14cf21513bdf9c0606aba17d1f389ea2b6987035eb4f62bd923f25/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e5d3e6b26f2c785d65cc25ef1e5267ccbe1b069c5c21b8cc724efee290554419", size = 408340, upload-time = "2025-11-30T20:24:00.2Z" }, + { url = "https://files.pythonhosted.org/packages/c2/c7/736e00ebf39ed81d75544c0da6ef7b0998f8201b369acf842f9a90dc8fce/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:626a7433c34566535b6e56a1b39a7b17ba961e97ce3b80ec62e6f1312c025551", size = 383765, upload-time = "2025-11-30T20:24:01.759Z" }, + { url = "https://files.pythonhosted.org/packages/4a/3f/da50dfde9956aaf365c4adc9533b100008ed31aea635f2b8d7b627e25b49/rpds_py-0.30.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:acd7eb3f4471577b9b5a41baf02a978e8bdeb08b4b355273994f8b87032000a8", size = 396834, upload-time = "2025-11-30T20:24:03.687Z" }, + { url = "https://files.pythonhosted.org/packages/4e/00/34bcc2565b6020eab2623349efbdec810676ad571995911f1abdae62a3a0/rpds_py-0.30.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fe5fa731a1fa8a0a56b0977413f8cacac1768dad38d16b3a296712709476fbd5", size = 415470, upload-time = "2025-11-30T20:24:05.232Z" }, + { url = "https://files.pythonhosted.org/packages/8c/28/882e72b5b3e6f718d5453bd4d0d9cf8df36fddeb4ddbbab17869d5868616/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:74a3243a411126362712ee1524dfc90c650a503502f135d54d1b352bd01f2404", size = 565630, upload-time = "2025-11-30T20:24:06.878Z" }, + { url = "https://files.pythonhosted.org/packages/3b/97/04a65539c17692de5b85c6e293520fd01317fd878ea1995f0367d4532fb1/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3e8eeb0544f2eb0d2581774be4c3410356eba189529a6b3e36bbbf9696175856", size = 591148, upload-time = "2025-11-30T20:24:08.445Z" }, + { url = "https://files.pythonhosted.org/packages/85/70/92482ccffb96f5441aab93e26c4d66489eb599efdcf96fad90c14bbfb976/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dbd936cde57abfee19ab3213cf9c26be06d60750e60a8e4dd85d1ab12c8b1f40", size = 556030, upload-time = "2025-11-30T20:24:10.956Z" }, + { url = "https://files.pythonhosted.org/packages/20/53/7c7e784abfa500a2b6b583b147ee4bb5a2b3747a9166bab52fec4b5b5e7d/rpds_py-0.30.0-cp314-cp314t-win32.whl", hash = "sha256:dc824125c72246d924f7f796b4f63c1e9dc810c7d9e2355864b3c3a73d59ade0", size = 211570, upload-time = "2025-11-30T20:24:12.735Z" }, + { url = "https://files.pythonhosted.org/packages/d0/02/fa464cdfbe6b26e0600b62c528b72d8608f5cc49f96b8d6e38c95d60c676/rpds_py-0.30.0-cp314-cp314t-win_amd64.whl", hash = "sha256:27f4b0e92de5bfbc6f86e43959e6edd1425c33b5e69aab0984a72047f2bcf1e3", size = 226532, upload-time = "2025-11-30T20:24:14.634Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/73/e1/4508a569211b35599016e84ba65c1a992b7a4004b4b6c4bea02a851cba1b/ruff-0.16.2.tar.gz", hash = "sha256:c3d7828d12e8927a6fc65fe38e2c2541b9e762d360a1786d752cb1b8883b3c9c", size = 4885811, upload-time = "2026-08-07T13:31:01.432Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/57/db19951540f98859c956b50bdb4d31089b4d91e9f15e2968e7d5193806d5/ruff-0.16.2-py3-none-linux_armv6l.whl", hash = "sha256:3c8de4cf2181f01d57946d87d777aa52916976fc09942aed89938fab5e013318", size = 10847925, upload-time = "2026-08-07T13:30:14.468Z" }, + { url = "https://files.pythonhosted.org/packages/13/5a/995fe85a8470d3e391ac0f7fa8054bb454eaf33ee138196d6172ed1079c0/ruff-0.16.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9a48cc05c6fbc811ca81b5d7ba95375affea6582d1b8024e455e41afbbf55344", size = 11072662, upload-time = "2026-08-07T13:30:18.143Z" }, + { url = "https://files.pythonhosted.org/packages/32/53/370d767c61c71a971a4ace36703a7ecd8c393956349a7325d7fab2b56827/ruff-0.16.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:a2c0d14fcbb26c91f0f867a6dc9bd71bbc30b1b6151829c884f23faeab2e5700", size = 10566771, upload-time = "2026-08-07T13:30:20.899Z" }, + { url = "https://files.pythonhosted.org/packages/85/d6/9d96948caf5a632be62d62202d5ec914d6856f204fd79eb036e5915e79ea/ruff-0.16.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:335c621622c4650330be50842561c6586ac6971bb8ab5407fe34dcc9efb16bbe", size = 10975825, upload-time = "2026-08-07T13:30:23.517Z" }, + { url = "https://files.pythonhosted.org/packages/3b/92/ea87129b3414acb0b5770563779c51804d37ac67675c7ba35447ddb14773/ruff-0.16.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:20e66910f2c37cc753f9ef6580c914a621b80c4fa3549d3e3521e29d0f5bfc3f", size = 10649437, upload-time = "2026-08-07T13:30:26.097Z" }, + { url = "https://files.pythonhosted.org/packages/ac/43/f8f291dcd4af5bb7872b74fdfa41a7cd7c856ca1d4069670971cf1b9f5cb/ruff-0.16.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7e36fbfba65510548156902bcf1350a979a958ce0347ce0f90d73894036b39f", size = 11446761, upload-time = "2026-08-07T13:30:28.752Z" }, + { url = "https://files.pythonhosted.org/packages/71/4a/ef991fb2fcf516ab71f0808adcdd8da5e18c8cde447f4ceaf5f47a5132a5/ruff-0.16.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f0eab35f80df8f134aae5d1630e751901321d317cc8e50dc39e36fa3ed34cd12", size = 12336364, upload-time = "2026-08-07T13:30:31.468Z" }, + { url = "https://files.pythonhosted.org/packages/f3/24/f615e74f307e6ca0e56a482872477b856c70d530aa356abfb6dfe5ca8a80/ruff-0.16.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:40ea8c0594feb894e89c8c61ab9c103d38b0ea72dfde6c594107147ca31b1140", size = 11630720, upload-time = "2026-08-07T13:30:34.426Z" }, + { url = "https://files.pythonhosted.org/packages/c5/d3/8ef50149e8412a77f7ab409efdef0e2b23803707a3863da4fc64cb23d459/ruff-0.16.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ab3d62dde0b19facdd632008cc4827fc28ada7736c6bd35ab6f1050f0bfed53f", size = 11466130, upload-time = "2026-08-07T13:30:36.958Z" }, + { url = "https://files.pythonhosted.org/packages/dd/a7/a19334985c4dea8c381981fa252cd854c7ee52dc4b1686dc16f4a911c702/ruff-0.16.2-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:e43e1f5b8388da9eca1b9e88328d47a5cec794633ccf6f7484ac2dd15eee92c0", size = 11523634, upload-time = "2026-08-07T13:30:39.822Z" }, + { url = "https://files.pythonhosted.org/packages/6e/6c/96d192b0e742412ceda08c0a50f9669b253dde9fd6a60ea1a10c9fa79a63/ruff-0.16.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:c24788a980581e1d7ea3a0cbe4344c4fbeb0a6a9b1f4713aa46bb104f8294690", size = 10949807, upload-time = "2026-08-07T13:30:42.745Z" }, + { url = "https://files.pythonhosted.org/packages/fa/51/e26599ceca11e79ee255c7df515995561edf87e9ca1893284e44d98f5a86/ruff-0.16.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:81806b08329130005dd4a8a8394a0c9da8c6f4cafb16ba438d2a2ee6a18bedf1", size = 10646891, upload-time = "2026-08-07T13:30:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/68/01/800c4b1f97bc8d7c6029e06b1f20473a3cf1e13c4933d8f3342add83fc55/ruff-0.16.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:4ce4e02bad779bef557f541a1b31f20d6abeae1cc05ed1b1ac019d4ffd1044c8", size = 11162063, upload-time = "2026-08-07T13:30:48.131Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d0/1477ea50fc5a0d4b0b71d1d63d50770bdd794d90b43e37a7618e63ec9894/ruff-0.16.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:e0422abdf70070255fc4073ce9dfc814cc03db577013761ddd09bc1e4a9a4fbd", size = 11556038, upload-time = "2026-08-07T13:30:50.686Z" }, + { url = "https://files.pythonhosted.org/packages/b8/76/a7776f32048d991e16d4fa8ff91790b877342d3596cc3ed04acdbf1aaedc/ruff-0.16.2-py3-none-win32.whl", hash = "sha256:bf3a63d78fb39f4bf5ac8ae52051c5520505301abe19ba4e204c453b3f09bb0b", size = 10872850, upload-time = "2026-08-07T13:30:53.471Z" }, + { url = "https://files.pythonhosted.org/packages/00/0d/929c800d920e61397d82a01b60bffc68da3052c17d31de59efaad2e4ed75/ruff-0.16.2-py3-none-win_amd64.whl", hash = "sha256:bcabe2f6d0fc7819f1431793005af4e4de7371927d037345bf941252b195b9fa", size = 12023338, upload-time = "2026-08-07T13:30:56.193Z" }, + { url = "https://files.pythonhosted.org/packages/5b/6c/93e26c22c5f78ff87363e07da49c84955affbeb1098bd1936bf3b3f293bf/ruff-0.16.2-py3-none-win_arm64.whl", hash = "sha256:d614e95cedf38a2053fd351c55b103ba30d017d61688fdbfd40ee0412852a99f", size = 11374065, upload-time = "2026-08-07T13:30:58.775Z" }, +] + +[[package]] +name = "s3fs" +version = "2026.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiobotocore" }, + { name = "aiohttp" }, + { name = "fsspec" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/12/60/69fc080b72a32971b2fb5acbc80802b0e876b606f6e27b1689caac4bb57b/s3fs-2026.7.0.tar.gz", hash = "sha256:76b062d1b2bc7bf4bcd9e7d8f1eb2b5dd9d5cee96ce888664c4ddb5f563146bf", size = 87595, upload-time = "2026-07-28T17:14:10.595Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/cc/bcde19a37952ecc58e7d9d67ecaa048e1e21b17d014ce0863a6a6101e606/s3fs-2026.7.0-py3-none-any.whl", hash = "sha256:64edf3c01ebffab1eec38ff9c09eefbf86a3db14c87d248f795da0e7b801d698", size = 32659, upload-time = "2026-07-28T17:14:09.497Z" }, +] + +[[package]] +name = "s3transfer" +version = "0.17.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9b/ec/7c692cde9125b77e84b307354d4fb705f98b8ccad59a036d5957ca75bfc3/s3transfer-0.17.0.tar.gz", hash = "sha256:9edeb6d1c3c2f89d6050348548834ad8289610d886e5bf7b7207728bd43ce33a", size = 155337, upload-time = "2026-04-29T22:07:36.33Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/72/c6c32d2b657fa3dad1de340254e14390b1e334ce38268b7ad51abda3c8c2/s3transfer-0.17.0-py3-none-any.whl", hash = "sha256:ce3801712acf4ad3e89fb9990df97b4972e93f4b3b0004d214be5bce12814c20", size = 86811, upload-time = "2026-04-29T22:07:34.966Z" }, +] + +[[package]] +name = "setuptools" +version = "83.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/34/26/f5d29e25ffdb535afef2d35cdb55b325298f96debd670da4c325e08d70f4/setuptools-83.0.0.tar.gz", hash = "sha256:025bccbbf0fa05b6192bc64ae1e7b16e001fd6d6d4d5de03c97b1c1ade523bef", size = 1154254, upload-time = "2026-07-04T15:31:22.699Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/40/e1e72872c6354b306daef1703549e8e83b4d43cfea356311bf722a043752/setuptools-83.0.0-py3-none-any.whl", hash = "sha256:29b23c360f22f414dc7336bb39178cc7bcbf6021ed2733cde173f09dba19abb3", size = 1008090, upload-time = "2026-07-04T15:31:20.885Z" }, +] + +[[package]] +name = "shellingham" +version = "1.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "snowballstemmer" +version = "3.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/75/a7/9810d872919697c9d01295633f5d574fb416d47e535f258272ca1f01f447/snowballstemmer-3.0.1.tar.gz", hash = "sha256:6d5eeeec8e9f84d4d56b847692bacf79bc2c8e90c7f80ca4444ff8b6f2e52895", size = 105575, upload-time = "2025-05-09T16:34:51.843Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/78/3565d011c61f5a43488987ee32b6f3f656e7f107ac2782dd57bdd7d91d9a/snowballstemmer-3.0.1-py3-none-any.whl", hash = "sha256:6cd7b3897da8d6c9ffb968a6781fa6532dce9c3618a4b127d920dab764a19064", size = 103274, upload-time = "2025-05-09T16:34:50.371Z" }, +] + +[[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 = "sphinx" +version = "9.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "alabaster" }, + { name = "babel" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "docutils" }, + { name = "imagesize" }, + { name = "jinja2" }, + { name = "packaging" }, + { name = "pygments" }, + { name = "requests" }, + { name = "roman-numerals" }, + { name = "snowballstemmer" }, + { name = "sphinxcontrib-applehelp" }, + { name = "sphinxcontrib-devhelp" }, + { name = "sphinxcontrib-htmlhelp" }, + { name = "sphinxcontrib-jsmath" }, + { name = "sphinxcontrib-qthelp" }, + { name = "sphinxcontrib-serializinghtml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cd/bd/f08eb0f4eed5c83f1ba2a3bd18f7745a2b1525fad70660a1c00224ec468a/sphinx-9.1.0.tar.gz", hash = "sha256:7741722357dd75f8190766926071fed3bdc211c74dd2d7d4df5404da95930ddb", size = 8718324, upload-time = "2025-12-31T15:09:27.646Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/f7/b1884cb3188ab181fc81fa00c266699dab600f927a964df02ec3d5d1916a/sphinx-9.1.0-py3-none-any.whl", hash = "sha256:c84fdd4e782504495fe4f2c0b3413d6c2bf388589bb352d439b2a3bb99991978", size = 3921742, upload-time = "2025-12-31T15:09:25.561Z" }, +] + +[[package]] +name = "sphinxcontrib-applehelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/6e/b837e84a1a704953c62ef8776d45c3e8d759876b4a84fe14eba2859106fe/sphinxcontrib_applehelp-2.0.0.tar.gz", hash = "sha256:2f29ef331735ce958efa4734873f084941970894c6090408b079c61b2e1c06d1", size = 20053, upload-time = "2024-07-29T01:09:00.465Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/85/9ebeae2f76e9e77b952f4b274c27238156eae7979c5421fba91a28f4970d/sphinxcontrib_applehelp-2.0.0-py3-none-any.whl", hash = "sha256:4cd3f0ec4ac5dd9c17ec65e9ab272c9b867ea77425228e68ecf08d6b28ddbdb5", size = 119300, upload-time = "2024-07-29T01:08:58.99Z" }, +] + +[[package]] +name = "sphinxcontrib-devhelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/d2/5beee64d3e4e747f316bae86b55943f51e82bb86ecd325883ef65741e7da/sphinxcontrib_devhelp-2.0.0.tar.gz", hash = "sha256:411f5d96d445d1d73bb5d52133377b4248ec79db5c793ce7dbe59e074b4dd1ad", size = 12967, upload-time = "2024-07-29T01:09:23.417Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/7a/987e583882f985fe4d7323774889ec58049171828b58c2217e7f79cdf44e/sphinxcontrib_devhelp-2.0.0-py3-none-any.whl", hash = "sha256:aefb8b83854e4b0998877524d1029fd3e6879210422ee3780459e28a1f03a8a2", size = 82530, upload-time = "2024-07-29T01:09:21.945Z" }, +] + +[[package]] +name = "sphinxcontrib-htmlhelp" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/93/983afd9aa001e5201eab16b5a444ed5b9b0a7a010541e0ddfbbfd0b2470c/sphinxcontrib_htmlhelp-2.1.0.tar.gz", hash = "sha256:c9e2916ace8aad64cc13a0d233ee22317f2b9025b9cf3295249fa985cc7082e9", size = 22617, upload-time = "2024-07-29T01:09:37.889Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/7b/18a8c0bcec9182c05a0b3ec2a776bba4ead82750a55ff798e8d406dae604/sphinxcontrib_htmlhelp-2.1.0-py3-none-any.whl", hash = "sha256:166759820b47002d22914d64a075ce08f4c46818e17cfc9470a9786b759b19f8", size = 98705, upload-time = "2024-07-29T01:09:36.407Z" }, +] + +[[package]] +name = "sphinxcontrib-jsmath" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b2/e8/9ed3830aeed71f17c026a07a5097edcf44b692850ef215b161b8ad875729/sphinxcontrib-jsmath-1.0.1.tar.gz", hash = "sha256:a9925e4a4587247ed2191a22df5f6970656cb8ca2bd6284309578f2153e0c4b8", size = 5787, upload-time = "2019-01-21T16:10:16.347Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/42/4c8646762ee83602e3fb3fbe774c2fac12f317deb0b5dbeeedd2d3ba4b77/sphinxcontrib_jsmath-1.0.1-py2.py3-none-any.whl", hash = "sha256:2ec2eaebfb78f3f2078e73666b1415417a116cc848b72e5172e596c871103178", size = 5071, upload-time = "2019-01-21T16:10:14.333Z" }, +] + +[[package]] +name = "sphinxcontrib-qthelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/68/bc/9104308fc285eb3e0b31b67688235db556cd5b0ef31d96f30e45f2e51cae/sphinxcontrib_qthelp-2.0.0.tar.gz", hash = "sha256:4fe7d0ac8fc171045be623aba3e2a8f613f8682731f9153bb2e40ece16b9bbab", size = 17165, upload-time = "2024-07-29T01:09:56.435Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/27/83/859ecdd180cacc13b1f7e857abf8582a64552ea7a061057a6c716e790fce/sphinxcontrib_qthelp-2.0.0-py3-none-any.whl", hash = "sha256:b18a828cdba941ccd6ee8445dbe72ffa3ef8cbe7505d8cd1fa0d42d3f2d5f3eb", size = 88743, upload-time = "2024-07-29T01:09:54.885Z" }, +] + +[[package]] +name = "sphinxcontrib-serializinghtml" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3b/44/6716b257b0aa6bfd51a1b31665d1c205fb12cb5ad56de752dfa15657de2f/sphinxcontrib_serializinghtml-2.0.0.tar.gz", hash = "sha256:e9d912827f872c029017a53f0ef2180b327c3f7fd23c87229f7a8e8b70031d4d", size = 16080, upload-time = "2024-07-29T01:10:09.332Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/52/a7/d2782e4e3f77c8450f727ba74a8f12756d5ba823d81b941f1b04da9d033a/sphinxcontrib_serializinghtml-2.0.0-py3-none-any.whl", hash = "sha256:6e2cb0eef194e10c27ec0023bfeb25badbbb5868244cf5bc5bdc04e4464bf331", size = 92072, upload-time = "2024-07-29T01:10:08.203Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "tinycss2" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "webencodings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/fd/7a5ee21fd08ff70d3d33a5781c255cbe779659bd03278feb98b19ee550f4/tinycss2-1.4.0.tar.gz", hash = "sha256:10c0972f6fc0fbee87c3edb76549357415e94548c1ae10ebccdea16fb404a9b7", size = 87085, upload-time = "2024-10-24T14:58:29.895Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/34/ebdc18bae6aa14fbee1a08b63c015c72b64868ff7dae68808ab500c492e2/tinycss2-1.4.0-py3-none-any.whl", hash = "sha256:3a49cf47b7675da0b15d0c6e1df8df4ebd96e9394bb905a5775adb0d884c5289", size = 26610, upload-time = "2024-10-24T14:58:28.029Z" }, +] + +[[package]] +name = "tomlkit" +version = "0.15.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/96/e07752635b98536177fa1f37671c8f3cdde2e724c6bcf6034b2cfb571565/tomlkit-0.15.1.tar.gz", hash = "sha256:e25bbf38843005246210a12982776f27f99cb9be67160e14434d0c0d21ee1e97", size = 180129, upload-time = "2026-07-17T01:48:04.562Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/bc/8c13eb66537dce1d2bd3a57132902f38d0e7f5bb46fa9f4daed9fe9d76ee/tomlkit-0.15.1-py3-none-any.whl", hash = "sha256:177a05aece5a8ca5266fd3c448abb47b8d352f09d477d3ca8332db4d89b24304", size = 49449, upload-time = "2026-07-17T01:48:05.728Z" }, +] + +[[package]] +name = "towncrier" +version = "25.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "jinja2" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c2/eb/5bf25a34123698d3bbab39c5bc5375f8f8bcbcc5a136964ade66935b8b9d/towncrier-25.8.0.tar.gz", hash = "sha256:eef16d29f831ad57abb3ae32a0565739866219f1ebfbdd297d32894eb9940eb1", size = 76322, upload-time = "2025-08-30T11:41:55.393Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/42/06/8ba22ec32c74ac1be3baa26116e3c28bc0e76a5387476921d20b6fdade11/towncrier-25.8.0-py3-none-any.whl", hash = "sha256:b953d133d98f9aeae9084b56a3563fd2519dfc6ec33f61c9cd2c61ff243fb513", size = 65101, upload-time = "2025-08-30T11:41:53.644Z" }, +] + +[[package]] +name = "typer" +version = "0.27.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "rich" }, + { name = "shellingham" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/40/4a3db7990d1f62a53182aa96eaef57aeb2886a27f90a195bc66713565d31/typer-0.27.1.tar.gz", hash = "sha256:a79bef8469a79c45498e7b814ecf8d603cc7644e9acbd9e19cac0334240b18df", size = 203994, upload-time = "2026-08-03T14:41:03.438Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/89/9518bc0c3929bee36b3a4a8e3daddd6e03f92f9961c66d4983b837160543/typer-0.27.1-py3-none-any.whl", hash = "sha256:53150287edd11baeb4e4722c8e394fcdf8181c0ae89485cba8d25c778d5edd56", size = 122874, upload-time = "2026-08-03T14:41:04.391Z" }, +] + +[[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 = "typing-inspection" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac53367ae42139cf4b1ca5f36bb3dc6c9d33acdb43655/typing_inspection-0.4.2.tar.gz", hash = "sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464", size = 75949, upload-time = "2025-10-01T02:14:41.687Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" }, +] + +[[package]] +name = "universal-pathlib" +version = "0.3.10" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fsspec" }, + { name = "pathlib-abc" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/6e/d997a70ee8f4c61f9a7e2f4f8af721cf072a3326848fc881b05187e52558/universal_pathlib-0.3.10.tar.gz", hash = "sha256:4487cbc90730a48cfb64f811d99e14b6faed6d738420cd5f93f59f48e6930bfb", size = 261110, upload-time = "2026-02-22T14:40:58.87Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/1a/5d9a402b39ec892d856bbdd9db502ff73ce28cdf4aff72eb1ce1d6843506/universal_pathlib-0.3.10-py3-none-any.whl", hash = "sha256:dfaf2fb35683d2eb1287a3ed7b215e4d6016aa6eaf339c607023d22f90821c66", size = 83528, upload-time = "2026-02-22T14:40:57.316Z" }, +] + +[[package]] +name = "urllib3" +version = "2.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, +] + +[[package]] +name = "uv" +version = "0.12.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3c/fa/19a665278931fca142cf1c21927b18b36cffb5fd137bf5228f937a977f84/uv-0.12.3.tar.gz", hash = "sha256:1eb3fea456aea47489d92e10451c9129b7dd9fd8854c4eb17020ba68489d5d9a", size = 5877698, upload-time = "2026-08-07T16:33:32.486Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0e/b1/eabb1f57339a63630a9b195f8bcdbcca101f4f5cbc5556e6f592d6049d80/uv-0.12.3-py3-none-linux_armv6l.whl", hash = "sha256:0c0561cd369002a5968e138ea477e86507a337b3ede44f441c90d85ed2f54714", size = 21777249, upload-time = "2026-08-07T16:32:18.631Z" }, + { url = "https://files.pythonhosted.org/packages/ed/52/7d23602e140bdd5bb25ffa8bf3943a86688e8cd558a9894dfbb83728e943/uv-0.12.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:0550669163cc67d5a7dc8e1702bc011e4a075a4ae52ad50891be654fc6635e0d", size = 20081726, upload-time = "2026-08-07T16:32:23.182Z" }, + { url = "https://files.pythonhosted.org/packages/e4/66/ba257c91d69921d773f523c9e4c3ffb04e233694c415517f5ef797403a4f/uv-0.12.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7c99f2524fe4b11d74dec85cef9b4d8b725d142dec04cd237f1c06fbdae1ee54", size = 18426262, upload-time = "2026-08-07T16:32:27.55Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e4/7e93226f4f33c3cc25dc942056f46be9c48e846338f8644a700123726dc8/uv-0.12.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:ac21bea426ddf95fa76d8dc1f67350faed7b4a81951825cf2aaef99fc4144815", size = 21156889, upload-time = "2026-08-07T16:32:31.447Z" }, + { url = "https://files.pythonhosted.org/packages/bd/b7/2504476931b7102cc6bfec5289efefe1279fe03964cb8ad7113691372605/uv-0.12.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:1e569258e17a536c1bd90a68935dc8250b0ecc81ba80efd814ed169c33de0f93", size = 21319192, upload-time = "2026-08-07T16:32:35.638Z" }, + { url = "https://files.pythonhosted.org/packages/e3/83/e9a93bf4d737bf00d7fa4e2a82ed0ed23bc30d44262127f5f8b9a4dd9150/uv-0.12.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6c8e5a2d2ce4ea511293f919357c427dab0f12104ebfdd6602727f5c38958c22", size = 21334826, upload-time = "2026-08-07T16:32:40.034Z" }, + { url = "https://files.pythonhosted.org/packages/5a/ef/19215f66a02451ca2698062e98690d5f2a7e65574104ba04c188c4b59c70/uv-0.12.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:115e96e176fa3525ffb999572ec6041b915f15189403613ccefcc1f128f0ea0c", size = 22014926, upload-time = "2026-08-07T16:32:44.159Z" }, + { url = "https://files.pythonhosted.org/packages/7c/a3/38526a97a5d376c59955025e54740ae35a4c7d8d80c6dfbee13fae588964/uv-0.12.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:913dc068e906f459df892cac789e6e9e10ac9d6af0bbb3c36fcc09347b0c986c", size = 23248637, upload-time = "2026-08-07T16:32:48.342Z" }, + { url = "https://files.pythonhosted.org/packages/38/63/a7a98d075383669b6a3ff4ca410cb9c18b6d0921df1c524bd0859a8474fe/uv-0.12.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:77fa7f501baa7c4d097b0c424914d7924db8e54f882c4f40056228ecf56feb98", size = 22929428, upload-time = "2026-08-07T16:32:52.452Z" }, + { url = "https://files.pythonhosted.org/packages/8d/c4/97fdd4fca11d06633bb500849f70e4e6b201bcba3833894732e709be2d60/uv-0.12.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1482d1462b1aecd18ee33627363fe1c63d6a194f12d40d37efc446d9e0d800a1", size = 22346263, upload-time = "2026-08-07T16:32:56.563Z" }, + { url = "https://files.pythonhosted.org/packages/c4/46/ab0906c8c3b6eeaf2412ab5af6077a38930db90e2c99c1b82e066f240a81/uv-0.12.3-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:248b6b282f96f98d79dddecd1b2acd1893efd84667321f26703feffff6433211", size = 21288225, upload-time = "2026-08-07T16:33:00.578Z" }, + { url = "https://files.pythonhosted.org/packages/2e/0f/f40530b0b336212fff1bc50887d263a9f03d8859e6c1c5210e11d104df10/uv-0.12.3-py3-none-manylinux_2_31_riscv64.musllinux_1_1_riscv64.whl", hash = "sha256:9201c7a1edadb07f64b695f17eac9db2d264eeb4b888c195aa11e7908d0ebf41", size = 21981757, upload-time = "2026-08-07T16:33:05.101Z" }, + { url = "https://files.pythonhosted.org/packages/0a/cf/240a3bebd15be490f867e155aa59522889d8d6310985421902f87d1fad99/uv-0.12.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:6114afd294411995a761c4cde0b721d550ff6d2fc2312046e8403eca6adacda5", size = 22117547, upload-time = "2026-08-07T16:33:09.124Z" }, + { url = "https://files.pythonhosted.org/packages/2f/da/fb143759f86b260f20634e11a27b9312eb6ff9c43c6756102e82875cd82d/uv-0.12.3-py3-none-musllinux_1_1_i686.whl", hash = "sha256:ba034f32abf966a101cf2434455faaf8d54dfacfff0d4b4c70d673f36e985728", size = 21255639, upload-time = "2026-08-07T16:33:13.38Z" }, + { url = "https://files.pythonhosted.org/packages/91/40/c1e0b626919792bf66847429d0c0bbf580a5f148a37268c10d9132f4871a/uv-0.12.3-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:13535c7d40faa7821c3763f5b6c605eef8556ea16277dc1a07a21203fd3c19e4", size = 22560342, upload-time = "2026-08-07T16:33:17.484Z" }, + { url = "https://files.pythonhosted.org/packages/fa/bf/246d088b4baf0239c8a06afa0ce155ce460942d08a9ac505fac5d0f99fe1/uv-0.12.3-py3-none-win32.whl", hash = "sha256:67b639a56dd36193b55a3bcea10f9dffcab37ed3c1eb26e964e52896df0bb205", size = 19420018, upload-time = "2026-08-07T16:33:21.544Z" }, + { url = "https://files.pythonhosted.org/packages/59/ed/3f816f972357578f1a21afdff8af9c93e87416afd0e150fc60be7eb280ab/uv-0.12.3-py3-none-win_amd64.whl", hash = "sha256:aeafd6e02b9a8d8beb447040bfc57ab172bdf244208f7147b4f7bbc327135797", size = 20215028, upload-time = "2026-08-07T16:33:25.751Z" }, + { url = "https://files.pythonhosted.org/packages/ff/63/0b08bf418b4d00e911465ad24a5f09040cc51247c362ffe56f859173e99f/uv-0.12.3-py3-none-win_arm64.whl", hash = "sha256:59121ef7217567adf4af41f7d3b04e42abb0c6a11bc87c930b838f9354f9c651", size = 19120228, upload-time = "2026-08-07T16:33:29.609Z" }, +] + +[[package]] +name = "verspec" +version = "0.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/44/8126f9f0c44319b2efc65feaad589cadef4d77ece200ae3c9133d58464d0/verspec-0.1.0.tar.gz", hash = "sha256:c4504ca697b2056cdb4bfa7121461f5a0e81809255b41c03dda4ba823637c01e", size = 27123, upload-time = "2020-11-30T02:24:09.646Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/ce/3b6fee91c85626eaf769d617f1be9d2e15c1cca027bbdeb2e0d751469355/verspec-0.1.0-py3-none-any.whl", hash = "sha256:741877d5633cc9464c45a469ae2a31e801e6dbbaa85b9675d481cda100f11c31", size = 19640, upload-time = "2020-11-30T02:24:08.387Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +] + +[[package]] +name = "webencodings" +version = "0.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0b/02/ae6ceac1baeda530866a85075641cec12989bd8d31af6d5ab4a3e8c92f47/webencodings-0.5.1.tar.gz", hash = "sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923", size = 9721, upload-time = "2017-04-05T20:21:34.189Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/24/2a3e3df732393fed8b3ebf2ec078f05546de641fe1b667ee316ec1dcf3b7/webencodings-0.5.1-py2.py3-none-any.whl", hash = "sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78", size = 11774, upload-time = "2017-04-05T20:21:32.581Z" }, +] + +[[package]] +name = "werkzeug" +version = "3.1.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dd/b2/381be8cfdee792dd117872481b6e378f85c957dd7c5bca38897b08f765fd/werkzeug-3.1.8.tar.gz", hash = "sha256:9bad61a4268dac112f1c5cd4630a56ede601b6ed420300677a869083d70a4c44", size = 875852, upload-time = "2026-04-02T18:49:14.268Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/93/8c/2e650f2afeb7ee576912636c23ddb621c91ac6a98e66dc8d29c3c69446e1/werkzeug-3.1.8-py3-none-any.whl", hash = "sha256:63a77fb8892bf28ebc3178683445222aa500e48ebad5ec77b0ad80f8726b1f50", size = 226459, upload-time = "2026-04-02T18:49:12.72Z" }, +] + +[[package]] +name = "wrapt" +version = "2.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2e/64/925f213fdcbb9baeb1530449ac71a4d57fc361c053d06bf78d0c5c7cd80c/wrapt-2.1.2.tar.gz", hash = "sha256:3996a67eecc2c68fd47b4e3c564405a5777367adfd9b8abb58387b63ee83b21e", size = 81678, upload-time = "2026-03-06T02:53:25.134Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4c/b6/1db817582c49c7fcbb7df6809d0f515af29d7c2fbf57eb44c36e98fb1492/wrapt-2.1.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ff2aad9c4cda28a8f0653fc2d487596458c2a3f475e56ba02909e950a9efa6a9", size = 61255, upload-time = "2026-03-06T02:52:45.663Z" }, + { url = "https://files.pythonhosted.org/packages/a2/16/9b02a6b99c09227c93cd4b73acc3678114154ec38da53043c0ddc1fba0dc/wrapt-2.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6433ea84e1cfacf32021d2a4ee909554ade7fd392caa6f7c13f1f4bf7b8e8748", size = 61848, upload-time = "2026-03-06T02:53:48.728Z" }, + { url = "https://files.pythonhosted.org/packages/af/aa/ead46a88f9ec3a432a4832dfedb84092fc35af2d0ba40cd04aea3889f247/wrapt-2.1.2-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c20b757c268d30d6215916a5fa8461048d023865d888e437fab451139cad6c8e", size = 121433, upload-time = "2026-03-06T02:54:40.328Z" }, + { url = "https://files.pythonhosted.org/packages/3a/9f/742c7c7cdf58b59085a1ee4b6c37b013f66ac33673a7ef4aaed5e992bc33/wrapt-2.1.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:79847b83eb38e70d93dc392c7c5b587efe65b3e7afcc167aa8abd5d60e8761c8", size = 123013, upload-time = "2026-03-06T02:53:26.58Z" }, + { url = "https://files.pythonhosted.org/packages/e8/44/2c3dd45d53236b7ed7c646fcf212251dc19e48e599debd3926b52310fafb/wrapt-2.1.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f8fba1bae256186a83d1875b2b1f4e2d1242e8fac0f58ec0d7e41b26967b965c", size = 117326, upload-time = "2026-03-06T02:53:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/74/e2/b17d66abc26bd96f89dec0ecd0ef03da4a1286e6ff793839ec431b9fae57/wrapt-2.1.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e3d3b35eedcf5f7d022291ecd7533321c4775f7b9cd0050a31a68499ba45757c", size = 121444, upload-time = "2026-03-06T02:54:09.5Z" }, + { url = "https://files.pythonhosted.org/packages/3c/62/e2977843fdf9f03daf1586a0ff49060b1b2fc7ff85a7ea82b6217c1ae36e/wrapt-2.1.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:6f2c5390460de57fa9582bc8a1b7a6c86e1a41dfad74c5225fc07044c15cc8d1", size = 116237, upload-time = "2026-03-06T02:54:03.884Z" }, + { url = "https://files.pythonhosted.org/packages/88/dd/27fc67914e68d740bce512f11734aec08696e6b17641fef8867c00c949fc/wrapt-2.1.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7dfa9f2cf65d027b951d05c662cc99ee3bd01f6e4691ed39848a7a5fffc902b2", size = 120563, upload-time = "2026-03-06T02:53:20.412Z" }, + { url = "https://files.pythonhosted.org/packages/ec/9f/b750b3692ed2ef4705cb305bd68858e73010492b80e43d2a4faa5573cbe7/wrapt-2.1.2-cp312-cp312-win32.whl", hash = "sha256:eba8155747eb2cae4a0b913d9ebd12a1db4d860fc4c829d7578c7b989bd3f2f0", size = 58198, upload-time = "2026-03-06T02:53:37.732Z" }, + { url = "https://files.pythonhosted.org/packages/8e/b2/feecfe29f28483d888d76a48f03c4c4d8afea944dbee2b0cd3380f9df032/wrapt-2.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:1c51c738d7d9faa0b3601708e7e2eda9bf779e1b601dce6c77411f2a1b324a63", size = 60441, upload-time = "2026-03-06T02:52:47.138Z" }, + { url = "https://files.pythonhosted.org/packages/44/e1/e328f605d6e208547ea9fd120804fcdec68536ac748987a68c47c606eea8/wrapt-2.1.2-cp312-cp312-win_arm64.whl", hash = "sha256:c8e46ae8e4032792eb2f677dbd0d557170a8e5524d22acc55199f43efedd39bf", size = 58836, upload-time = "2026-03-06T02:53:22.053Z" }, + { url = "https://files.pythonhosted.org/packages/4c/7a/d936840735c828b38d26a854e85d5338894cda544cb7a85a9d5b8b9c4df7/wrapt-2.1.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:787fd6f4d67befa6fe2abdffcbd3de2d82dfc6fb8a6d850407c53332709d030b", size = 61259, upload-time = "2026-03-06T02:53:41.922Z" }, + { url = "https://files.pythonhosted.org/packages/5e/88/9a9b9a90ac8ca11c2fdb6a286cb3a1fc7dd774c00ed70929a6434f6bc634/wrapt-2.1.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4bdf26e03e6d0da3f0e9422fd36bcebf7bc0eeb55fdf9c727a09abc6b9fe472e", size = 61851, upload-time = "2026-03-06T02:52:48.672Z" }, + { url = "https://files.pythonhosted.org/packages/03/a9/5b7d6a16fd6533fed2756900fc8fc923f678179aea62ada6d65c92718c00/wrapt-2.1.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:bbac24d879aa22998e87f6b3f481a5216311e7d53c7db87f189a7a0266dafffb", size = 121446, upload-time = "2026-03-06T02:54:14.013Z" }, + { url = "https://files.pythonhosted.org/packages/45/bb/34c443690c847835cfe9f892be78c533d4f32366ad2888972c094a897e39/wrapt-2.1.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:16997dfb9d67addc2e3f41b62a104341e80cac52f91110dece393923c0ebd5ca", size = 123056, upload-time = "2026-03-06T02:54:10.829Z" }, + { url = "https://files.pythonhosted.org/packages/93/b9/ff205f391cb708f67f41ea148545f2b53ff543a7ac293b30d178af4d2271/wrapt-2.1.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:162e4e2ba7542da9027821cb6e7c5e068d64f9a10b5f15512ea28e954893a267", size = 117359, upload-time = "2026-03-06T02:53:03.623Z" }, + { url = "https://files.pythonhosted.org/packages/1f/3d/1ea04d7747825119c3c9a5e0874a40b33594ada92e5649347c457d982805/wrapt-2.1.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f29c827a8d9936ac320746747a016c4bc66ef639f5cd0d32df24f5eacbf9c69f", size = 121479, upload-time = "2026-03-06T02:53:45.844Z" }, + { url = "https://files.pythonhosted.org/packages/78/cc/ee3a011920c7a023b25e8df26f306b2484a531ab84ca5c96260a73de76c0/wrapt-2.1.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a9dd9813825f7ecb018c17fd147a01845eb330254dff86d3b5816f20f4d6aaf8", size = 116271, upload-time = "2026-03-06T02:54:46.356Z" }, + { url = "https://files.pythonhosted.org/packages/98/fd/e5ff7ded41b76d802cf1191288473e850d24ba2e39a6ec540f21ae3b57cb/wrapt-2.1.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6f8dbdd3719e534860d6a78526aafc220e0241f981367018c2875178cf83a413", size = 120573, upload-time = "2026-03-06T02:52:50.163Z" }, + { url = "https://files.pythonhosted.org/packages/47/c5/242cae3b5b080cd09bacef0591691ba1879739050cc7c801ff35c8886b66/wrapt-2.1.2-cp313-cp313-win32.whl", hash = "sha256:5c35b5d82b16a3bc6e0a04349b606a0582bc29f573786aebe98e0c159bc48db6", size = 58205, upload-time = "2026-03-06T02:53:47.494Z" }, + { url = "https://files.pythonhosted.org/packages/12/69/c358c61e7a50f290958809b3c61ebe8b3838ea3e070d7aac9814f95a0528/wrapt-2.1.2-cp313-cp313-win_amd64.whl", hash = "sha256:f8bc1c264d8d1cf5b3560a87bbdd31131573eb25f9f9447bb6252b8d4c44a3a1", size = 60452, upload-time = "2026-03-06T02:53:30.038Z" }, + { url = "https://files.pythonhosted.org/packages/8e/66/c8a6fcfe321295fd8c0ab1bd685b5a01462a9b3aa2f597254462fc2bc975/wrapt-2.1.2-cp313-cp313-win_arm64.whl", hash = "sha256:3beb22f674550d5634642c645aba4c72a2c66fb185ae1aebe1e955fae5a13baf", size = 58842, upload-time = "2026-03-06T02:52:52.114Z" }, + { url = "https://files.pythonhosted.org/packages/da/55/9c7052c349106e0b3f17ae8db4b23a691a963c334de7f9dbd60f8f74a831/wrapt-2.1.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0fc04bc8664a8bc4c8e00b37b5355cffca2535209fba1abb09ae2b7c76ddf82b", size = 63075, upload-time = "2026-03-06T02:53:19.108Z" }, + { url = "https://files.pythonhosted.org/packages/09/a8/ce7b4006f7218248dd71b7b2b732d0710845a0e49213b18faef64811ffef/wrapt-2.1.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a9b9d50c9af998875a1482a038eb05755dfd6fe303a313f6a940bb53a83c3f18", size = 63719, upload-time = "2026-03-06T02:54:33.452Z" }, + { url = "https://files.pythonhosted.org/packages/e4/e5/2ca472e80b9e2b7a17f106bb8f9df1db11e62101652ce210f66935c6af67/wrapt-2.1.2-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2d3ff4f0024dd224290c0eabf0240f1bfc1f26363431505fb1b0283d3b08f11d", size = 152643, upload-time = "2026-03-06T02:52:42.721Z" }, + { url = "https://files.pythonhosted.org/packages/36/42/30f0f2cefca9d9cbf6835f544d825064570203c3e70aa873d8ae12e23791/wrapt-2.1.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3278c471f4468ad544a691b31bb856374fbdefb7fee1a152153e64019379f015", size = 158805, upload-time = "2026-03-06T02:54:25.441Z" }, + { url = "https://files.pythonhosted.org/packages/bb/67/d08672f801f604889dcf58f1a0b424fe3808860ede9e03affc1876b295af/wrapt-2.1.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a8914c754d3134a3032601c6984db1c576e6abaf3fc68094bb8ab1379d75ff92", size = 145990, upload-time = "2026-03-06T02:53:57.456Z" }, + { url = "https://files.pythonhosted.org/packages/68/a7/fd371b02e73babec1de6ade596e8cd9691051058cfdadbfd62a5898f3295/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:ff95d4264e55839be37bafe1536db2ab2de19da6b65f9244f01f332b5286cfbf", size = 155670, upload-time = "2026-03-06T02:54:55.309Z" }, + { url = "https://files.pythonhosted.org/packages/86/2d/9fe0095dfdb621009f40117dcebf41d7396c2c22dca6eac779f4c007b86c/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:76405518ca4e1b76fbb1b9f686cff93aebae03920cc55ceeec48ff9f719c5f67", size = 144357, upload-time = "2026-03-06T02:54:24.092Z" }, + { url = "https://files.pythonhosted.org/packages/0e/b6/ec7b4a254abbe4cde9fa15c5d2cca4518f6b07d0f1b77d4ee9655e30280e/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c0be8b5a74c5824e9359b53e7e58bef71a729bacc82e16587db1c4ebc91f7c5a", size = 150269, upload-time = "2026-03-06T02:53:31.268Z" }, + { url = "https://files.pythonhosted.org/packages/6e/6b/2fabe8ebf148f4ee3c782aae86a795cc68ffe7d432ef550f234025ce0cfa/wrapt-2.1.2-cp313-cp313t-win32.whl", hash = "sha256:f01277d9a5fc1862f26f7626da9cf443bebc0abd2f303f41c5e995b15887dabd", size = 59894, upload-time = "2026-03-06T02:54:15.391Z" }, + { url = "https://files.pythonhosted.org/packages/ca/fb/9ba66fc2dedc936de5f8073c0217b5d4484e966d87723415cc8262c5d9c2/wrapt-2.1.2-cp313-cp313t-win_amd64.whl", hash = "sha256:84ce8f1c2104d2f6daa912b1b5b039f331febfeee74f8042ad4e04992bd95c8f", size = 63197, upload-time = "2026-03-06T02:54:41.943Z" }, + { url = "https://files.pythonhosted.org/packages/c0/1c/012d7423c95d0e337117723eb8ecf73c622ce15a97847e84cf3f8f26cd7e/wrapt-2.1.2-cp313-cp313t-win_arm64.whl", hash = "sha256:a93cd767e37faeddbe07d8fc4212d5cba660af59bdb0f6372c93faaa13e6e679", size = 60363, upload-time = "2026-03-06T02:54:48.093Z" }, + { url = "https://files.pythonhosted.org/packages/39/25/e7ea0b417db02bb796182a5316398a75792cd9a22528783d868755e1f669/wrapt-2.1.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:1370e516598854e5b4366e09ce81e08bfe94d42b0fd569b88ec46cc56d9164a9", size = 61418, upload-time = "2026-03-06T02:53:55.706Z" }, + { url = "https://files.pythonhosted.org/packages/ec/0f/fa539e2f6a770249907757eaeb9a5ff4deb41c026f8466c1c6d799088a9b/wrapt-2.1.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6de1a3851c27e0bd6a04ca993ea6f80fc53e6c742ee1601f486c08e9f9b900a9", size = 61914, upload-time = "2026-03-06T02:52:53.37Z" }, + { url = "https://files.pythonhosted.org/packages/53/37/02af1867f5b1441aaeda9c82deed061b7cd1372572ddcd717f6df90b5e93/wrapt-2.1.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:de9f1a2bbc5ac7f6012ec24525bdd444765a2ff64b5985ac6e0692144838542e", size = 120417, upload-time = "2026-03-06T02:54:30.74Z" }, + { url = "https://files.pythonhosted.org/packages/c3/b7/0138a6238c8ba7476c77cf786a807f871672b37f37a422970342308276e7/wrapt-2.1.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:970d57ed83fa040d8b20c52fe74a6ae7e3775ae8cff5efd6a81e06b19078484c", size = 122797, upload-time = "2026-03-06T02:54:51.539Z" }, + { url = "https://files.pythonhosted.org/packages/e1/ad/819ae558036d6a15b7ed290d5b14e209ca795dd4da9c58e50c067d5927b0/wrapt-2.1.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3969c56e4563c375861c8df14fa55146e81ac11c8db49ea6fb7f2ba58bc1ff9a", size = 117350, upload-time = "2026-03-06T02:54:37.651Z" }, + { url = "https://files.pythonhosted.org/packages/8b/2d/afc18dc57a4600a6e594f77a9ae09db54f55ba455440a54886694a84c71b/wrapt-2.1.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:57d7c0c980abdc5f1d98b11a2aa3bb159790add80258c717fa49a99921456d90", size = 121223, upload-time = "2026-03-06T02:54:35.221Z" }, + { url = "https://files.pythonhosted.org/packages/b9/5b/5ec189b22205697bc56eb3b62aed87a1e0423e9c8285d0781c7a83170d15/wrapt-2.1.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:776867878e83130c7a04237010463372e877c1c994d449ca6aaafeab6aab2586", size = 116287, upload-time = "2026-03-06T02:54:19.654Z" }, + { url = "https://files.pythonhosted.org/packages/f7/2d/f84939a7c9b5e6cdd8a8d0f6a26cabf36a0f7e468b967720e8b0cd2bdf69/wrapt-2.1.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:fab036efe5464ec3291411fabb80a7a39e2dd80bae9bcbeeca5087fdfa891e19", size = 119593, upload-time = "2026-03-06T02:54:16.697Z" }, + { url = "https://files.pythonhosted.org/packages/0b/fe/ccd22a1263159c4ac811ab9374c061bcb4a702773f6e06e38de5f81a1bdc/wrapt-2.1.2-cp314-cp314-win32.whl", hash = "sha256:e6ed62c82ddf58d001096ae84ce7f833db97ae2263bff31c9b336ba8cfe3f508", size = 58631, upload-time = "2026-03-06T02:53:06.498Z" }, + { url = "https://files.pythonhosted.org/packages/65/0a/6bd83be7bff2e7efaac7b4ac9748da9d75a34634bbbbc8ad077d527146df/wrapt-2.1.2-cp314-cp314-win_amd64.whl", hash = "sha256:467e7c76315390331c67073073d00662015bb730c566820c9ca9b54e4d67fd04", size = 60875, upload-time = "2026-03-06T02:53:50.252Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c0/0b3056397fe02ff80e5a5d72d627c11eb885d1ca78e71b1a5c1e8c7d45de/wrapt-2.1.2-cp314-cp314-win_arm64.whl", hash = "sha256:da1f00a557c66225d53b095a97eace0fc5349e3bfda28fa34ffae238978ee575", size = 59164, upload-time = "2026-03-06T02:53:59.128Z" }, + { url = "https://files.pythonhosted.org/packages/71/ed/5d89c798741993b2371396eb9d4634f009ff1ad8a6c78d366fe2883ea7a6/wrapt-2.1.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:62503ffbc2d3a69891cf29beeaccdb4d5e0a126e2b6a851688d4777e01428dbb", size = 63163, upload-time = "2026-03-06T02:52:54.873Z" }, + { url = "https://files.pythonhosted.org/packages/c6/8c/05d277d182bf36b0a13d6bd393ed1dec3468a25b59d01fba2dd70fe4d6ae/wrapt-2.1.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c7e6cd120ef837d5b6f860a6ea3745f8763805c418bb2f12eeb1fa6e25f22d22", size = 63723, upload-time = "2026-03-06T02:52:56.374Z" }, + { url = "https://files.pythonhosted.org/packages/f4/27/6c51ec1eff4413c57e72d6106bb8dec6f0c7cdba6503d78f0fa98767bcc9/wrapt-2.1.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3769a77df8e756d65fbc050333f423c01ae012b4f6731aaf70cf2bef61b34596", size = 152652, upload-time = "2026-03-06T02:53:23.79Z" }, + { url = "https://files.pythonhosted.org/packages/db/4c/d7dd662d6963fc7335bfe29d512b02b71cdfa23eeca7ab3ac74a67505deb/wrapt-2.1.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a76d61a2e851996150ba0f80582dd92a870643fa481f3b3846f229de88caf044", size = 158807, upload-time = "2026-03-06T02:53:35.742Z" }, + { url = "https://files.pythonhosted.org/packages/b4/4d/1e5eea1a78d539d346765727422976676615814029522c76b87a95f6bcdd/wrapt-2.1.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6f97edc9842cf215312b75fe737ee7c8adda75a89979f8e11558dfff6343cc4b", size = 146061, upload-time = "2026-03-06T02:52:57.574Z" }, + { url = "https://files.pythonhosted.org/packages/89/bc/62cabea7695cd12a288023251eeefdcb8465056ddaab6227cb78a2de005b/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:4006c351de6d5007aa33a551f600404ba44228a89e833d2fadc5caa5de8edfbf", size = 155667, upload-time = "2026-03-06T02:53:39.422Z" }, + { url = "https://files.pythonhosted.org/packages/e9/99/6f2888cd68588f24df3a76572c69c2de28287acb9e1972bf0c83ce97dbc1/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:a9372fc3639a878c8e7d87e1556fa209091b0a66e912c611e3f833e2c4202be2", size = 144392, upload-time = "2026-03-06T02:54:22.41Z" }, + { url = "https://files.pythonhosted.org/packages/40/51/1dfc783a6c57971614c48e361a82ca3b6da9055879952587bc99fe1a7171/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3144b027ff30cbd2fca07c0a87e67011adb717eb5f5bd8496325c17e454257a3", size = 150296, upload-time = "2026-03-06T02:54:07.848Z" }, + { url = "https://files.pythonhosted.org/packages/6c/38/cbb8b933a0201076c1f64fc42883b0023002bdc14a4964219154e6ff3350/wrapt-2.1.2-cp314-cp314t-win32.whl", hash = "sha256:3b8d15e52e195813efe5db8cec156eebe339aaf84222f4f4f051a6c01f237ed7", size = 60539, upload-time = "2026-03-06T02:54:00.594Z" }, + { url = "https://files.pythonhosted.org/packages/82/dd/e5176e4b241c9f528402cebb238a36785a628179d7d8b71091154b3e4c9e/wrapt-2.1.2-cp314-cp314t-win_amd64.whl", hash = "sha256:08ffa54146a7559f5b8df4b289b46d963a8e74ed16ba3687f99896101a3990c5", size = 63969, upload-time = "2026-03-06T02:54:39Z" }, + { url = "https://files.pythonhosted.org/packages/5c/99/79f17046cf67e4a95b9987ea129632ba8bcec0bc81f3fb3d19bdb0bd60cd/wrapt-2.1.2-cp314-cp314t-win_arm64.whl", hash = "sha256:72aaa9d0d8e4ed0e2e98019cea47a21f823c9dd4b43c7b77bba6679ffcca6a00", size = 60554, upload-time = "2026-03-06T02:53:14.132Z" }, + { url = "https://files.pythonhosted.org/packages/1a/c7/8528ac2dfa2c1e6708f647df7ae144ead13f0a31146f43c7264b4942bf12/wrapt-2.1.2-py3-none-any.whl", hash = "sha256:b8fd6fa2b2c4e7621808f8c62e8317f4aae56e59721ad933bac5239d913cf0e8", size = 43993, upload-time = "2026-03-06T02:53:12.905Z" }, +] + +[[package]] +name = "xmltodict" +version = "1.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/19/70/80f3b7c10d2630aa66414bf23d210386700aa390547278c789afa994fd7e/xmltodict-1.0.4.tar.gz", hash = "sha256:6d94c9f834dd9e44514162799d344d815a3a4faec913717a9ecbfa5be1bb8e61", size = 26124, upload-time = "2026-02-22T02:21:22.074Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/34/98a2f52245f4d47be93b580dae5f9861ef58977d73a79eb47c58f1ad1f3a/xmltodict-1.0.4-py3-none-any.whl", hash = "sha256:a4a00d300b0e1c59fc2bfccb53d7b2e88c32f200df138a0dd2229f842497026a", size = 13580, upload-time = "2026-02-22T02:21:21.039Z" }, +] + +[[package]] +name = "yarl" +version = "1.23.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/23/6e/beb1beec874a72f23815c1434518bfc4ed2175065173fb138c3705f658d4/yarl-1.23.0.tar.gz", hash = "sha256:53b1ea6ca88ebd4420379c330aea57e258408dd0df9af0992e5de2078dc9f5d5", size = 194676, upload-time = "2026-03-01T22:07:53.373Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/8a/94615bc31022f711add374097ad4144d569e95ff3c38d39215d07ac153a0/yarl-1.23.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1932b6b8bba8d0160a9d1078aae5838a66039e8832d41d2992daa9a3a08f7860", size = 124737, upload-time = "2026-03-01T22:05:12.897Z" }, + { url = "https://files.pythonhosted.org/packages/e3/6f/c6554045d59d64052698add01226bc867b52fe4a12373415d7991fdca95d/yarl-1.23.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:411225bae281f114067578891bc75534cfb3d92a3b4dfef7a6ca78ba354e6069", size = 87029, upload-time = "2026-03-01T22:05:14.376Z" }, + { url = "https://files.pythonhosted.org/packages/19/2a/725ecc166d53438bc88f76822ed4b1e3b10756e790bafd7b523fe97c322d/yarl-1.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:13a563739ae600a631c36ce096615fe307f131344588b0bc0daec108cdb47b25", size = 86310, upload-time = "2026-03-01T22:05:15.71Z" }, + { url = "https://files.pythonhosted.org/packages/99/30/58260ed98e6ff7f90ba84442c1ddd758c9170d70327394a6227b310cd60f/yarl-1.23.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9cbf44c5cb4a7633d078788e1b56387e3d3cf2b8139a3be38040b22d6c3221c8", size = 97587, upload-time = "2026-03-01T22:05:17.384Z" }, + { url = "https://files.pythonhosted.org/packages/76/0a/8b08aac08b50682e65759f7f8dde98ae8168f72487e7357a5d684c581ef9/yarl-1.23.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:53ad387048f6f09a8969631e4de3f1bf70c50e93545d64af4f751b2498755072", size = 92528, upload-time = "2026-03-01T22:05:18.804Z" }, + { url = "https://files.pythonhosted.org/packages/52/07/0b7179101fe5f8385ec6c6bb5d0cb9f76bd9fb4a769591ab6fb5cdbfc69a/yarl-1.23.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4a59ba56f340334766f3a4442e0efd0af895fae9e2b204741ef885c446b3a1a8", size = 105339, upload-time = "2026-03-01T22:05:20.235Z" }, + { url = "https://files.pythonhosted.org/packages/d3/8a/36d82869ab5ec829ca8574dfcb92b51286fcfb1e9c7a73659616362dc880/yarl-1.23.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:803a3c3ce4acc62eaf01eaca1208dcf0783025ef27572c3336502b9c232005e7", size = 105061, upload-time = "2026-03-01T22:05:22.268Z" }, + { url = "https://files.pythonhosted.org/packages/66/3e/868e5c3364b6cee19ff3e1a122194fa4ce51def02c61023970442162859e/yarl-1.23.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a3d2bff8f37f8d0f96c7ec554d16945050d54462d6e95414babaa18bfafc7f51", size = 100132, upload-time = "2026-03-01T22:05:23.638Z" }, + { url = "https://files.pythonhosted.org/packages/cf/26/9c89acf82f08a52cb52d6d39454f8d18af15f9d386a23795389d1d423823/yarl-1.23.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c75eb09e8d55bceb4367e83496ff8ef2bc7ea6960efb38e978e8073ea59ecb67", size = 99289, upload-time = "2026-03-01T22:05:25.749Z" }, + { url = "https://files.pythonhosted.org/packages/6f/54/5b0db00d2cb056922356104468019c0a132e89c8d3ab67d8ede9f4483d2a/yarl-1.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:877b0738624280e34c55680d6054a307aa94f7d52fa0e3034a9cc6e790871da7", size = 96950, upload-time = "2026-03-01T22:05:27.318Z" }, + { url = "https://files.pythonhosted.org/packages/f6/40/10fa93811fd439341fad7e0718a86aca0de9548023bbb403668d6555acab/yarl-1.23.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:b5405bb8f0e783a988172993cfc627e4d9d00432d6bbac65a923041edacf997d", size = 93960, upload-time = "2026-03-01T22:05:28.738Z" }, + { url = "https://files.pythonhosted.org/packages/bc/d2/8ae2e6cd77d0805f4526e30ec43b6f9a3dfc542d401ac4990d178e4bf0cf/yarl-1.23.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1c3a3598a832590c5a3ce56ab5576361b5688c12cb1d39429cf5dba30b510760", size = 104703, upload-time = "2026-03-01T22:05:30.438Z" }, + { url = "https://files.pythonhosted.org/packages/2f/0c/b3ceacf82c3fe21183ce35fa2acf5320af003d52bc1fcf5915077681142e/yarl-1.23.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:8419ebd326430d1cbb7efb5292330a2cf39114e82df5cc3d83c9a0d5ebeaf2f2", size = 98325, upload-time = "2026-03-01T22:05:31.835Z" }, + { url = "https://files.pythonhosted.org/packages/9d/e0/12900edd28bdab91a69bd2554b85ad7b151f64e8b521fe16f9ad2f56477a/yarl-1.23.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:be61f6fff406ca40e3b1d84716fde398fc08bc63dd96d15f3a14230a0973ed86", size = 105067, upload-time = "2026-03-01T22:05:33.358Z" }, + { url = "https://files.pythonhosted.org/packages/15/61/74bb1182cf79c9bbe4eb6b1f14a57a22d7a0be5e9cedf8e2d5c2086474c3/yarl-1.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3ceb13c5c858d01321b5d9bb65e4cf37a92169ea470b70fec6f236b2c9dd7e34", size = 100285, upload-time = "2026-03-01T22:05:35.4Z" }, + { url = "https://files.pythonhosted.org/packages/69/7f/cd5ef733f2550de6241bd8bd8c3febc78158b9d75f197d9c7baa113436af/yarl-1.23.0-cp312-cp312-win32.whl", hash = "sha256:fffc45637bcd6538de8b85f51e3df3223e4ad89bccbfca0481c08c7fc8b7ed7d", size = 82359, upload-time = "2026-03-01T22:05:36.811Z" }, + { url = "https://files.pythonhosted.org/packages/f5/be/25216a49daeeb7af2bec0db22d5e7df08ed1d7c9f65d78b14f3b74fd72fc/yarl-1.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:f69f57305656a4852f2a7203efc661d8c042e6cc67f7acd97d8667fb448a426e", size = 87674, upload-time = "2026-03-01T22:05:38.171Z" }, + { url = "https://files.pythonhosted.org/packages/d2/35/aeab955d6c425b227d5b7247eafb24f2653fedc32f95373a001af5dfeb9e/yarl-1.23.0-cp312-cp312-win_arm64.whl", hash = "sha256:6e87a6e8735b44816e7db0b2fbc9686932df473c826b0d9743148432e10bb9b9", size = 81879, upload-time = "2026-03-01T22:05:40.006Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4b/a0a6e5d0ee8a2f3a373ddef8a4097d74ac901ac363eea1440464ccbe0898/yarl-1.23.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:16c6994ac35c3e74fb0ae93323bf8b9c2a9088d55946109489667c510a7d010e", size = 123796, upload-time = "2026-03-01T22:05:41.412Z" }, + { url = "https://files.pythonhosted.org/packages/67/b6/8925d68af039b835ae876db5838e82e76ec87b9782ecc97e192b809c4831/yarl-1.23.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4a42e651629dafb64fd5b0286a3580613702b5809ad3f24934ea87595804f2c5", size = 86547, upload-time = "2026-03-01T22:05:42.841Z" }, + { url = "https://files.pythonhosted.org/packages/ae/50/06d511cc4b8e0360d3c94af051a768e84b755c5eb031b12adaaab6dec6e5/yarl-1.23.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7c6b9461a2a8b47c65eef63bb1c76a4f1c119618ffa99ea79bc5bb1e46c5821b", size = 85854, upload-time = "2026-03-01T22:05:44.85Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f4/4e30b250927ffdab4db70da08b9b8d2194d7c7b400167b8fbeca1e4701ca/yarl-1.23.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2569b67d616eab450d262ca7cb9f9e19d2f718c70a8b88712859359d0ab17035", size = 98351, upload-time = "2026-03-01T22:05:46.836Z" }, + { url = "https://files.pythonhosted.org/packages/86/fc/4118c5671ea948208bdb1492d8b76bdf1453d3e73df051f939f563e7dcc5/yarl-1.23.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e9d9a4d06d3481eab79803beb4d9bd6f6a8e781ec078ac70d7ef2dcc29d1bea5", size = 92711, upload-time = "2026-03-01T22:05:48.316Z" }, + { url = "https://files.pythonhosted.org/packages/56/11/1ed91d42bd9e73c13dc9e7eb0dd92298d75e7ac4dd7f046ad0c472e231cd/yarl-1.23.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f514f6474e04179d3d33175ed3f3e31434d3130d42ec153540d5b157deefd735", size = 106014, upload-time = "2026-03-01T22:05:50.028Z" }, + { url = "https://files.pythonhosted.org/packages/ce/c9/74e44e056a23fbc33aca71779ef450ca648a5bc472bdad7a82339918f818/yarl-1.23.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fda207c815b253e34f7e1909840fd14299567b1c0eb4908f8c2ce01a41265401", size = 105557, upload-time = "2026-03-01T22:05:51.416Z" }, + { url = "https://files.pythonhosted.org/packages/66/fe/b1e10b08d287f518994f1e2ff9b6d26f0adeecd8dd7d533b01bab29a3eda/yarl-1.23.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34b6cf500e61c90f305094911f9acc9c86da1a05a7a3f5be9f68817043f486e4", size = 101559, upload-time = "2026-03-01T22:05:52.872Z" }, + { url = "https://files.pythonhosted.org/packages/72/59/c5b8d94b14e3d3c2a9c20cb100119fd534ab5a14b93673ab4cc4a4141ea5/yarl-1.23.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d7504f2b476d21653e4d143f44a175f7f751cd41233525312696c76aa3dbb23f", size = 100502, upload-time = "2026-03-01T22:05:54.954Z" }, + { url = "https://files.pythonhosted.org/packages/77/4f/96976cb54cbfc5c9fd73ed4c51804f92f209481d1fb190981c0f8a07a1d7/yarl-1.23.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:578110dd426f0d209d1509244e6d4a3f1a3e9077655d98c5f22583d63252a08a", size = 98027, upload-time = "2026-03-01T22:05:56.409Z" }, + { url = "https://files.pythonhosted.org/packages/63/6e/904c4f476471afdbad6b7e5b70362fb5810e35cd7466529a97322b6f5556/yarl-1.23.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:609d3614d78d74ebe35f54953c5bbd2ac647a7ddb9c30a5d877580f5e86b22f2", size = 95369, upload-time = "2026-03-01T22:05:58.141Z" }, + { url = "https://files.pythonhosted.org/packages/9d/40/acfcdb3b5f9d68ef499e39e04d25e141fe90661f9d54114556cf83be8353/yarl-1.23.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4966242ec68afc74c122f8459abd597afd7d8a60dc93d695c1334c5fd25f762f", size = 105565, upload-time = "2026-03-01T22:06:00.286Z" }, + { url = "https://files.pythonhosted.org/packages/5e/c6/31e28f3a6ba2869c43d124f37ea5260cac9c9281df803c354b31f4dd1f3c/yarl-1.23.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e0fd068364a6759bc794459f0a735ab151d11304346332489c7972bacbe9e72b", size = 99813, upload-time = "2026-03-01T22:06:01.712Z" }, + { url = "https://files.pythonhosted.org/packages/08/1f/6f65f59e72d54aa467119b63fc0b0b1762eff0232db1f4720cd89e2f4a17/yarl-1.23.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:39004f0ad156da43e86aa71f44e033de68a44e5a31fc53507b36dd253970054a", size = 105632, upload-time = "2026-03-01T22:06:03.188Z" }, + { url = "https://files.pythonhosted.org/packages/a3/c4/18b178a69935f9e7a338127d5b77d868fdc0f0e49becd286d51b3a18c61d/yarl-1.23.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e5723c01a56c5028c807c701aa66722916d2747ad737a046853f6c46f4875543", size = 101895, upload-time = "2026-03-01T22:06:04.651Z" }, + { url = "https://files.pythonhosted.org/packages/8f/54/f5b870b5505663911dba950a8e4776a0dbd51c9c54c0ae88e823e4b874a0/yarl-1.23.0-cp313-cp313-win32.whl", hash = "sha256:1b6b572edd95b4fa8df75de10b04bc81acc87c1c7d16bcdd2035b09d30acc957", size = 82356, upload-time = "2026-03-01T22:06:06.04Z" }, + { url = "https://files.pythonhosted.org/packages/7a/84/266e8da36879c6edcd37b02b547e2d9ecdfea776be49598e75696e3316e1/yarl-1.23.0-cp313-cp313-win_amd64.whl", hash = "sha256:baaf55442359053c7d62f6f8413a62adba3205119bcb6f49594894d8be47e5e3", size = 87515, upload-time = "2026-03-01T22:06:08.107Z" }, + { url = "https://files.pythonhosted.org/packages/00/fd/7e1c66efad35e1649114fa13f17485f62881ad58edeeb7f49f8c5e748bf9/yarl-1.23.0-cp313-cp313-win_arm64.whl", hash = "sha256:fb4948814a2a98e3912505f09c9e7493b1506226afb1f881825368d6fb776ee3", size = 81785, upload-time = "2026-03-01T22:06:10.181Z" }, + { url = "https://files.pythonhosted.org/packages/9c/fc/119dd07004f17ea43bb91e3ece6587759edd7519d6b086d16bfbd3319982/yarl-1.23.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:aecfed0b41aa72b7881712c65cf764e39ce2ec352324f5e0837c7048d9e6daaa", size = 130719, upload-time = "2026-03-01T22:06:11.708Z" }, + { url = "https://files.pythonhosted.org/packages/e6/0d/9f2348502fbb3af409e8f47730282cd6bc80dec6630c1e06374d882d6eb2/yarl-1.23.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:a41bcf68efd19073376eb8cf948b8d9be0af26256403e512bb18f3966f1f9120", size = 89690, upload-time = "2026-03-01T22:06:13.429Z" }, + { url = "https://files.pythonhosted.org/packages/50/93/e88f3c80971b42cfc83f50a51b9d165a1dbf154b97005f2994a79f212a07/yarl-1.23.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:cde9a2ecd91668bcb7f077c4966d8ceddb60af01b52e6e3e2680e4cf00ad1a59", size = 89851, upload-time = "2026-03-01T22:06:15.53Z" }, + { url = "https://files.pythonhosted.org/packages/1c/07/61c9dd8ba8f86473263b4036f70fb594c09e99c0d9737a799dfd8bc85651/yarl-1.23.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5023346c4ee7992febc0068e7593de5fa2bf611848c08404b35ebbb76b1b0512", size = 95874, upload-time = "2026-03-01T22:06:17.553Z" }, + { url = "https://files.pythonhosted.org/packages/9e/e9/f9ff8ceefba599eac6abddcfb0b3bee9b9e636e96dbf54342a8577252379/yarl-1.23.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d1009abedb49ae95b136a8904a3f71b342f849ffeced2d3747bf29caeda218c4", size = 88710, upload-time = "2026-03-01T22:06:19.004Z" }, + { url = "https://files.pythonhosted.org/packages/eb/78/0231bfcc5d4c8eec220bc2f9ef82cb4566192ea867a7c5b4148f44f6cbcd/yarl-1.23.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a8d00f29b42f534cc8aa3931cfe773b13b23e561e10d2b26f27a8d309b0e82a1", size = 101033, upload-time = "2026-03-01T22:06:21.203Z" }, + { url = "https://files.pythonhosted.org/packages/cd/9b/30ea5239a61786f18fd25797151a17fbb3be176977187a48d541b5447dd4/yarl-1.23.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:95451e6ce06c3e104556d73b559f5da6c34a069b6b62946d3ad66afcd51642ea", size = 100817, upload-time = "2026-03-01T22:06:22.738Z" }, + { url = "https://files.pythonhosted.org/packages/62/e2/a4980481071791bc83bce2b7a1a1f7adcabfa366007518b4b845e92eeee3/yarl-1.23.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:531ef597132086b6cf96faa7c6c1dcd0361dd5f1694e5cc30375907b9b7d3ea9", size = 97482, upload-time = "2026-03-01T22:06:24.21Z" }, + { url = "https://files.pythonhosted.org/packages/e5/1e/304a00cf5f6100414c4b5a01fc7ff9ee724b62158a08df2f8170dfc72a2d/yarl-1.23.0-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:88f9fb0116fbfcefcab70f85cf4b74a2b6ce5d199c41345296f49d974ddb4123", size = 95949, upload-time = "2026-03-01T22:06:25.697Z" }, + { url = "https://files.pythonhosted.org/packages/68/03/093f4055ed4cae649ac53bca3d180bd37102e9e11d048588e9ab0c0108d0/yarl-1.23.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e7b0460976dc75cb87ad9cc1f9899a4b97751e7d4e77ab840fc9b6d377b8fd24", size = 95839, upload-time = "2026-03-01T22:06:27.309Z" }, + { url = "https://files.pythonhosted.org/packages/b9/28/4c75ebb108f322aa8f917ae10a8ffa4f07cae10a8a627b64e578617df6a0/yarl-1.23.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:115136c4a426f9da976187d238e84139ff6b51a20839aa6e3720cd1026d768de", size = 90696, upload-time = "2026-03-01T22:06:29.048Z" }, + { url = "https://files.pythonhosted.org/packages/23/9c/42c2e2dd91c1a570402f51bdf066bfdb1241c2240ba001967bad778e77b7/yarl-1.23.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:ead11956716a940c1abc816b7df3fa2b84d06eaed8832ca32f5c5e058c65506b", size = 100865, upload-time = "2026-03-01T22:06:30.525Z" }, + { url = "https://files.pythonhosted.org/packages/74/05/1bcd60a8a0a914d462c305137246b6f9d167628d73568505fce3f1cb2e65/yarl-1.23.0-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:fe8f8f5e70e6dbdfca9882cd9deaac058729bcf323cf7a58660901e55c9c94f6", size = 96234, upload-time = "2026-03-01T22:06:32.692Z" }, + { url = "https://files.pythonhosted.org/packages/90/b2/f52381aac396d6778ce516b7bc149c79e65bfc068b5de2857ab69eeea3b7/yarl-1.23.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:a0e317df055958a0c1e79e5d2aa5a5eaa4a6d05a20d4b0c9c3f48918139c9fc6", size = 100295, upload-time = "2026-03-01T22:06:34.268Z" }, + { url = "https://files.pythonhosted.org/packages/e5/e8/638bae5bbf1113a659b2435d8895474598afe38b4a837103764f603aba56/yarl-1.23.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6f0fd84de0c957b2d280143522c4f91a73aada1923caee763e24a2b3fda9f8a5", size = 97784, upload-time = "2026-03-01T22:06:35.864Z" }, + { url = "https://files.pythonhosted.org/packages/80/25/a3892b46182c586c202629fc2159aa13975d3741d52ebd7347fd501d48d5/yarl-1.23.0-cp313-cp313t-win32.whl", hash = "sha256:93a784271881035ab4406a172edb0faecb6e7d00f4b53dc2f55919d6c9688595", size = 88313, upload-time = "2026-03-01T22:06:37.39Z" }, + { url = "https://files.pythonhosted.org/packages/43/68/8c5b36aa5178900b37387937bc2c2fe0e9505537f713495472dcf6f6fccc/yarl-1.23.0-cp313-cp313t-win_amd64.whl", hash = "sha256:dd00607bffbf30250fe108065f07453ec124dbf223420f57f5e749b04295e090", size = 94932, upload-time = "2026-03-01T22:06:39.579Z" }, + { url = "https://files.pythonhosted.org/packages/c6/cc/d79ba8292f51f81f4dc533a8ccfb9fc6992cabf0998ed3245de7589dc07c/yarl-1.23.0-cp313-cp313t-win_arm64.whl", hash = "sha256:ac09d42f48f80c9ee1635b2fcaa819496a44502737660d3c0f2ade7526d29144", size = 84786, upload-time = "2026-03-01T22:06:41.988Z" }, + { url = "https://files.pythonhosted.org/packages/90/98/b85a038d65d1b92c3903ab89444f48d3cee490a883477b716d7a24b1a78c/yarl-1.23.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:21d1b7305a71a15b4794b5ff22e8eef96ff4a6d7f9657155e5aa419444b28912", size = 124455, upload-time = "2026-03-01T22:06:43.615Z" }, + { url = "https://files.pythonhosted.org/packages/39/54/bc2b45559f86543d163b6e294417a107bb87557609007c007ad889afec18/yarl-1.23.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:85610b4f27f69984932a7abbe52703688de3724d9f72bceb1cca667deff27474", size = 86752, upload-time = "2026-03-01T22:06:45.425Z" }, + { url = "https://files.pythonhosted.org/packages/24/f9/e8242b68362bffe6fb536c8db5076861466fc780f0f1b479fc4ffbebb128/yarl-1.23.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:23f371bd662cf44a7630d4d113101eafc0cfa7518a2760d20760b26021454719", size = 86291, upload-time = "2026-03-01T22:06:46.974Z" }, + { url = "https://files.pythonhosted.org/packages/ea/d8/d1cb2378c81dd729e98c716582b1ccb08357e8488e4c24714658cc6630e8/yarl-1.23.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c4a80f77dc1acaaa61f0934176fccca7096d9b1ff08c8ba9cddf5ae034a24319", size = 99026, upload-time = "2026-03-01T22:06:48.459Z" }, + { url = "https://files.pythonhosted.org/packages/0a/ff/7196790538f31debe3341283b5b0707e7feb947620fc5e8236ef28d44f72/yarl-1.23.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:bd654fad46d8d9e823afbb4f87c79160b5a374ed1ff5bde24e542e6ba8f41434", size = 92355, upload-time = "2026-03-01T22:06:50.306Z" }, + { url = "https://files.pythonhosted.org/packages/c1/56/25d58c3eddde825890a5fe6aa1866228377354a3c39262235234ab5f616b/yarl-1.23.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:682bae25f0a0dd23a056739f23a134db9f52a63e2afd6bfb37ddc76292bbd723", size = 106417, upload-time = "2026-03-01T22:06:52.1Z" }, + { url = "https://files.pythonhosted.org/packages/51/8a/882c0e7bc8277eb895b31bce0138f51a1ba551fc2e1ec6753ffc1e7c1377/yarl-1.23.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a82836cab5f197a0514235aaf7ffccdc886ccdaa2324bc0aafdd4ae898103039", size = 106422, upload-time = "2026-03-01T22:06:54.424Z" }, + { url = "https://files.pythonhosted.org/packages/42/2b/fef67d616931055bf3d6764885990a3ac647d68734a2d6a9e1d13de437a2/yarl-1.23.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1c57676bdedc94cd3bc37724cf6f8cd2779f02f6aba48de45feca073e714fe52", size = 101915, upload-time = "2026-03-01T22:06:55.895Z" }, + { url = "https://files.pythonhosted.org/packages/18/6a/530e16aebce27c5937920f3431c628a29a4b6b430fab3fd1c117b26ff3f6/yarl-1.23.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c7f8dc16c498ff06497c015642333219871effba93e4a2e8604a06264aca5c5c", size = 100690, upload-time = "2026-03-01T22:06:58.21Z" }, + { url = "https://files.pythonhosted.org/packages/88/08/93749219179a45e27b036e03260fda05190b911de8e18225c294ac95bbc9/yarl-1.23.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:5ee586fb17ff8f90c91cf73c6108a434b02d69925f44f5f8e0d7f2f260607eae", size = 98750, upload-time = "2026-03-01T22:06:59.794Z" }, + { url = "https://files.pythonhosted.org/packages/d9/cf/ea424a004969f5d81a362110a6ac1496d79efdc6d50c2c4b2e3ea0fc2519/yarl-1.23.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:17235362f580149742739cc3828b80e24029d08cbb9c4bda0242c7b5bc610a8e", size = 94685, upload-time = "2026-03-01T22:07:01.375Z" }, + { url = "https://files.pythonhosted.org/packages/e2/b7/14341481fe568e2b0408bcf1484c652accafe06a0ade9387b5d3fd9df446/yarl-1.23.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:0793e2bd0cf14234983bbb371591e6bea9e876ddf6896cdcc93450996b0b5c85", size = 106009, upload-time = "2026-03-01T22:07:03.151Z" }, + { url = "https://files.pythonhosted.org/packages/0a/e6/5c744a9b54f4e8007ad35bce96fbc9218338e84812d36f3390cea616881a/yarl-1.23.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:3650dc2480f94f7116c364096bc84b1d602f44224ef7d5c7208425915c0475dd", size = 100033, upload-time = "2026-03-01T22:07:04.701Z" }, + { url = "https://files.pythonhosted.org/packages/0c/23/e3bfc188d0b400f025bc49d99793d02c9abe15752138dcc27e4eaf0c4a9e/yarl-1.23.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:f40e782d49630ad384db66d4d8b73ff4f1b8955dc12e26b09a3e3af064b3b9d6", size = 106483, upload-time = "2026-03-01T22:07:06.231Z" }, + { url = "https://files.pythonhosted.org/packages/72/42/f0505f949a90b3f8b7a363d6cbdf398f6e6c58946d85c6d3a3bc70595b26/yarl-1.23.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:94f8575fbdf81749008d980c17796097e645574a3b8c28ee313931068dad14fe", size = 102175, upload-time = "2026-03-01T22:07:08.4Z" }, + { url = "https://files.pythonhosted.org/packages/aa/65/b39290f1d892a9dd671d1c722014ca062a9c35d60885d57e5375db0404b5/yarl-1.23.0-cp314-cp314-win32.whl", hash = "sha256:c8aa34a5c864db1087d911a0b902d60d203ea3607d91f615acd3f3108ac32169", size = 83871, upload-time = "2026-03-01T22:07:09.968Z" }, + { url = "https://files.pythonhosted.org/packages/a9/5b/9b92f54c784c26e2a422e55a8d2607ab15b7ea3349e28359282f84f01d43/yarl-1.23.0-cp314-cp314-win_amd64.whl", hash = "sha256:63e92247f383c85ab00dd0091e8c3fa331a96e865459f5ee80353c70a4a42d70", size = 89093, upload-time = "2026-03-01T22:07:11.501Z" }, + { url = "https://files.pythonhosted.org/packages/e0/7d/8a84dc9381fd4412d5e7ff04926f9865f6372b4c2fd91e10092e65d29eb8/yarl-1.23.0-cp314-cp314-win_arm64.whl", hash = "sha256:70efd20be968c76ece7baa8dafe04c5be06abc57f754d6f36f3741f7aa7a208e", size = 83384, upload-time = "2026-03-01T22:07:13.069Z" }, + { url = "https://files.pythonhosted.org/packages/dd/8d/d2fad34b1c08aa161b74394183daa7d800141aaaee207317e82c790b418d/yarl-1.23.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:9a18d6f9359e45722c064c97464ec883eb0e0366d33eda61cb19a244bf222679", size = 131019, upload-time = "2026-03-01T22:07:14.903Z" }, + { url = "https://files.pythonhosted.org/packages/19/ff/33009a39d3ccf4b94d7d7880dfe17fb5816c5a4fe0096d9b56abceea9ac7/yarl-1.23.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2803ed8b21ca47a43da80a6fd1ed3019d30061f7061daa35ac54f63933409412", size = 89894, upload-time = "2026-03-01T22:07:17.372Z" }, + { url = "https://files.pythonhosted.org/packages/0c/f1/dab7ac5e7306fb79c0190766a3c00b4cb8d09a1f390ded68c85a5934faf5/yarl-1.23.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:394906945aa8b19fc14a61cf69743a868bb8c465efe85eee687109cc540b98f4", size = 89979, upload-time = "2026-03-01T22:07:19.361Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b1/08e95f3caee1fad6e65017b9f26c1d79877b502622d60e517de01e72f95d/yarl-1.23.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71d006bee8397a4a89f469b8deb22469fe7508132d3c17fa6ed871e79832691c", size = 95943, upload-time = "2026-03-01T22:07:21.266Z" }, + { url = "https://files.pythonhosted.org/packages/c0/cc/6409f9018864a6aa186c61175b977131f373f1988e198e031236916e87e4/yarl-1.23.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:62694e275c93d54f7ccedcfef57d42761b2aad5234b6be1f3e3026cae4001cd4", size = 88786, upload-time = "2026-03-01T22:07:23.129Z" }, + { url = "https://files.pythonhosted.org/packages/76/40/cc22d1d7714b717fde2006fad2ced5efe5580606cb059ae42117542122f3/yarl-1.23.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a31de1613658308efdb21ada98cbc86a97c181aa050ba22a808120bb5be3ab94", size = 101307, upload-time = "2026-03-01T22:07:24.689Z" }, + { url = "https://files.pythonhosted.org/packages/8f/0d/476c38e85ddb4c6ec6b20b815bdd779aa386a013f3d8b85516feee55c8dc/yarl-1.23.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fb1e8b8d66c278b21d13b0a7ca22c41dd757a7c209c6b12c313e445c31dd3b28", size = 100904, upload-time = "2026-03-01T22:07:26.287Z" }, + { url = "https://files.pythonhosted.org/packages/72/32/0abe4a76d59adf2081dcb0397168553ece4616ada1c54d1c49d8936c74f8/yarl-1.23.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50f9d8d531dfb767c565f348f33dd5139a6c43f5cbdf3f67da40d54241df93f6", size = 97728, upload-time = "2026-03-01T22:07:27.906Z" }, + { url = "https://files.pythonhosted.org/packages/b7/35/7b30f4810fba112f60f5a43237545867504e15b1c7647a785fbaf588fac2/yarl-1.23.0-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:575aa4405a656e61a540f4a80eaa5260f2a38fff7bfdc4b5f611840d76e9e277", size = 95964, upload-time = "2026-03-01T22:07:30.198Z" }, + { url = "https://files.pythonhosted.org/packages/2d/86/ed7a73ab85ef00e8bb70b0cb5421d8a2a625b81a333941a469a6f4022828/yarl-1.23.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:041b1a4cefacf65840b4e295c6985f334ba83c30607441ae3cf206a0eed1a2e4", size = 95882, upload-time = "2026-03-01T22:07:32.132Z" }, + { url = "https://files.pythonhosted.org/packages/19/90/d56967f61a29d8498efb7afb651e0b2b422a1e9b47b0ab5f4e40a19b699b/yarl-1.23.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:d38c1e8231722c4ce40d7593f28d92b5fc72f3e9774fe73d7e800ec32299f63a", size = 90797, upload-time = "2026-03-01T22:07:34.404Z" }, + { url = "https://files.pythonhosted.org/packages/72/00/8b8f76909259f56647adb1011d7ed8b321bcf97e464515c65016a47ecdf0/yarl-1.23.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d53834e23c015ee83a99377db6e5e37d8484f333edb03bd15b4bc312cc7254fb", size = 101023, upload-time = "2026-03-01T22:07:35.953Z" }, + { url = "https://files.pythonhosted.org/packages/ac/e2/cab11b126fb7d440281b7df8e9ddbe4851e70a4dde47a202b6642586b8d9/yarl-1.23.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:2e27c8841126e017dd2a054a95771569e6070b9ee1b133366d8b31beb5018a41", size = 96227, upload-time = "2026-03-01T22:07:37.594Z" }, + { url = "https://files.pythonhosted.org/packages/c2/9b/2c893e16bfc50e6b2edf76c1a9eb6cb0c744346197e74c65e99ad8d634d0/yarl-1.23.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:76855800ac56f878847a09ce6dba727c93ca2d89c9e9d63002d26b916810b0a2", size = 100302, upload-time = "2026-03-01T22:07:39.334Z" }, + { url = "https://files.pythonhosted.org/packages/28/ec/5498c4e3a6d5f1003beb23405671c2eb9cdbf3067d1c80f15eeafe301010/yarl-1.23.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e09fd068c2e169a7070d83d3bde728a4d48de0549f975290be3c108c02e499b4", size = 98202, upload-time = "2026-03-01T22:07:41.717Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c3/cd737e2d45e70717907f83e146f6949f20cc23cd4bf7b2688727763aa458/yarl-1.23.0-cp314-cp314t-win32.whl", hash = "sha256:73309162a6a571d4cbd3b6a1dcc703c7311843ae0d1578df6f09be4e98df38d4", size = 90558, upload-time = "2026-03-01T22:07:43.433Z" }, + { url = "https://files.pythonhosted.org/packages/e1/19/3774d162f6732d1cfb0b47b4140a942a35ca82bb19b6db1f80e9e7bdc8f8/yarl-1.23.0-cp314-cp314t-win_amd64.whl", hash = "sha256:4503053d296bc6e4cbd1fad61cf3b6e33b939886c4f249ba7c78b602214fabe2", size = 97610, upload-time = "2026-03-01T22:07:45.773Z" }, + { url = "https://files.pythonhosted.org/packages/51/47/3fa2286c3cb162c71cdb34c4224d5745a1ceceb391b2bd9b19b668a8d724/yarl-1.23.0-cp314-cp314t-win_arm64.whl", hash = "sha256:44bb7bef4ea409384e3f8bc36c063d77ea1b8d4a5b2706956c0d6695f07dcc25", size = 86041, upload-time = "2026-03-01T22:07:49.026Z" }, + { url = "https://files.pythonhosted.org/packages/69/68/c8739671f5699c7dc470580a4f821ef37c32c4cb0b047ce223a7f115757f/yarl-1.23.0-py3-none-any.whl", hash = "sha256:a2df6afe50dea8ae15fa34c9f824a3ee958d785fd5d089063d960bae1daa0a3f", size = 48288, upload-time = "2026-03-01T22:07:51.388Z" }, +] + +[[package]] +name = "zarr" +source = { editable = "." } +dependencies = [ + { name = "donfig" }, + { name = "google-crc32c" }, + { name = "msgspec" }, + { name = "numcodecs" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "typing-extensions" }, +] + +[package.optional-dependencies] +cast-value-rs = [ + { name = "cast-value-rs" }, +] +cli = [ + { name = "typer" }, +] +gpu = [ + { name = "cupy-cuda12x", marker = "sys_platform != 'darwin'" }, +] +optional = [ + { name = "universal-pathlib" }, +] +remote = [ + { name = "fsspec" }, + { name = "obstore" }, +] + +[package.dev-dependencies] +dev = [ + { name = "astroid" }, + { name = "botocore" }, + { name = "coverage" }, + { name = "fsspec" }, + { name = "griffe-inherited-docstrings" }, + { name = "hypothesis" }, + { name = "markdown-exec", extra = ["ansi"] }, + { name = "mike" }, + { name = "mkdocs" }, + { name = "mkdocs-material", extra = ["imaging"] }, + { name = "mkdocs-redirects" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "moto", extra = ["s3", "server"] }, + { name = "mypy" }, + { name = "numcodecs", extra = ["msgpack"] }, + { name = "numpydoc" }, + { name = "obstore" }, + { name = "pytest" }, + { name = "pytest-accept" }, + { name = "pytest-asyncio" }, + { name = "pytest-benchmark" }, + { name = "pytest-codspeed" }, + { name = "pytest-cov" }, + { name = "pytest-reportlog" }, + { name = "pytest-xdist" }, + { name = "requests" }, + { name = "ruff" }, + { name = "s3fs" }, + { name = "tomlkit" }, + { name = "towncrier" }, + { name = "universal-pathlib" }, + { name = "uv" }, +] +docs = [ + { name = "astroid" }, + { name = "griffe-inherited-docstrings" }, + { name = "markdown-exec", extra = ["ansi"] }, + { name = "mike" }, + { name = "mkdocs" }, + { name = "mkdocs-material", extra = ["imaging"] }, + { name = "mkdocs-redirects" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "numcodecs", extra = ["msgpack"] }, + { name = "pytest" }, + { name = "ruff" }, + { name = "s3fs" }, + { name = "towncrier" }, +] +release = [ + { name = "towncrier" }, +] +remote-tests = [ + { name = "botocore" }, + { name = "coverage" }, + { name = "fsspec" }, + { name = "hypothesis" }, + { name = "moto", extra = ["s3", "server"] }, + { name = "numpydoc" }, + { name = "obstore" }, + { name = "pytest" }, + { name = "pytest-accept" }, + { name = "pytest-asyncio" }, + { name = "pytest-benchmark" }, + { name = "pytest-codspeed" }, + { name = "pytest-cov" }, + { name = "pytest-reportlog" }, + { name = "pytest-xdist" }, + { name = "requests" }, + { name = "s3fs" }, + { name = "tomlkit" }, + { name = "uv" }, +] +test = [ + { name = "coverage" }, + { name = "hypothesis" }, + { name = "numpydoc" }, + { name = "pytest" }, + { name = "pytest-accept" }, + { name = "pytest-asyncio" }, + { name = "pytest-benchmark" }, + { name = "pytest-codspeed" }, + { name = "pytest-cov" }, + { name = "pytest-reportlog" }, + { name = "pytest-xdist" }, + { name = "tomlkit" }, + { name = "uv" }, +] + +[package.metadata] +requires-dist = [ + { name = "cast-value-rs", marker = "extra == 'cast-value-rs'", specifier = ">=0.4.2" }, + { name = "cupy-cuda12x", marker = "sys_platform != 'darwin' and extra == 'gpu'" }, + { name = "donfig", specifier = ">=0.8" }, + { name = "fsspec", marker = "extra == 'remote'", specifier = ">=2023.10.0" }, + { name = "google-crc32c", specifier = ">=1.5" }, + { name = "msgspec", specifier = ">=0.19" }, + { name = "numcodecs", specifier = ">=0.14" }, + { name = "numpy", specifier = ">=2" }, + { name = "obstore", marker = "extra == 'remote'", specifier = ">=0.5.1" }, + { name = "packaging", specifier = ">=22.0" }, + { name = "typer", marker = "extra == 'cli'" }, + { name = "typing-extensions", specifier = ">=4.14" }, + { name = "universal-pathlib", marker = "extra == 'optional'" }, +] +provides-extras = ["cast-value-rs", "cli", "gpu", "optional", "remote"] + +[package.metadata.requires-dev] +dev = [ + { name = "astroid", specifier = "==4.3.0" }, + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.4" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "hypothesis", specifier = "==6.165.5" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "mypy", specifier = "==2.3.0" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-reportlog", specifier = "==1.0.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "ruff", specifier = "==0.16.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "towncrier", specifier = "==25.8.0" }, + { name = "universal-pathlib" }, + { name = "uv", specifier = "==0.12.3" }, +] +docs = [ + { name = "astroid", specifier = "==4.3.0" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "ruff", specifier = "==0.16.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "towncrier", specifier = "==25.8.0" }, +] +release = [{ name = "towncrier", specifier = "==25.8.0" }] +remote-tests = [ + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.4" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "hypothesis", specifier = "==6.165.5" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-reportlog", specifier = "==1.0.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.3" }, +] +test = [ + { name = "coverage", specifier = "==7.15.4" }, + { name = "hypothesis", specifier = "==6.165.5" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-reportlog", specifier = "==1.0.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.3" }, +]